@chaibuilder/pages 0.7.1-beta.2 → 0.7.1-beta.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{B4MFY5CR-BZxWJ7zv.cjs → B4MFY5CR-Ce21IjAd.cjs} +1 -1
- package/dist/{B4MFY5CR-DXulpjuf.js → B4MFY5CR-CwNIV8x6.js} +1 -1
- package/dist/{HO4MOOFI-BVjj5z_y.cjs → HO4MOOFI-Av3UJGkm.cjs} +1 -1
- package/dist/{HO4MOOFI-FbC2oevJ.js → HO4MOOFI-BEZHTpXA.js} +2 -2
- package/dist/{HUY7CZI3-DvxfQh-B.cjs → HUY7CZI3-DqMa7qGt.cjs} +1 -1
- package/dist/{HUY7CZI3-BhKIDTHM.js → HUY7CZI3-khwS6Ahu.js} +2 -2
- package/dist/{index-D8t9Rrcz.js → index-EhOUX8r8.js} +14 -13
- package/dist/{index-C0wqsYPh.cjs → index-IuWCAl0p.cjs} +4 -4
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +14 -0
- package/dist/index.js +21 -20
- package/package.json +1 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
"use strict";var Za=Object.defineProperty;var cn=e=>{throw TypeError(e)};var er=(e,s,n)=>s in e?Za(e,s,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[s]=n;var As=(e,s,n)=>er(e,typeof s!="symbol"?s+"":s,n),un=(e,s,n)=>s.has(e)||cn("Cannot "+n);var X=(e,s,n)=>(un(e,s,"read from private field"),n?n.call(e):s.get(e)),ge=(e,s,n)=>s.has(e)?cn("Cannot add the same private member more than once"):s instanceof WeakSet?s.add(e):s.set(e,n),fe=(e,s,n,a)=>(un(e,s,"write to private field"),a?a.call(e,n):s.set(e,n),n);const t=require("react/jsx-runtime"),m=require("lodash-es"),f=require("react"),Ie=require("jotai"),D=require("@tanstack/react-query"),V=require("sonner"),q=require("@chaibuilder/sdk"),o=require("@chaibuilder/sdk/ui"),Ct=require("date-fns"),E=require("lucide-react"),In=require("@chaibuilder/runtime"),ls=require("zod"),tr=require("react-dropzone"),sr=require("@chaibuilder/sdk/web-blocks");function nr(e){const s=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const n in e)if(n!=="default"){const a=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(s,n,a.get?a:{enumerable:!0,get:()=>e[n]})}}return s.default=e,Object.freeze(s)}const we=nr(f),ke={ab:"Abkhazian",aa:"Afar",af:"Afrikaans",ak:"Akan",sq:"Albanian",am:"Amharic",ar:"Arabic",an:"Aragonese",hy:"Armenian",as:"Assamese",av:"Avaric",ae:"Avestan",ay:"Aymara",az:"Azerbaijani",bm:"Bambara",ba:"Bashkir",eu:"Basque",be:"Belarusian",bn:"Bengali",bh:"Bihari",bi:"Bislama",bs:"Bosnian",br:"Breton",bg:"Bulgarian",my:"Burmese",ca:"Catalan",ch:"Chamorro",ce:"Chechen",ny:"Chichewa",zh:"Chinese","zh-Hans":"Chinese (Simplified)","zh-Hant":"Chinese (Traditional)",cv:"Chuvash",kw:"Cornish",co:"Corsican",cr:"Cree",hr:"Croatian",cs:"Czech",da:"Danish",dv:"Maldivian",nl:"Dutch",dz:"Dzongkha",en:"English",eo:"Esperanto",et:"Estonian",ee:"Ewe",fo:"Faroese",fj:"Fijian",fi:"Finnish",fr:"French",ff:"Fula, Pular",gl:"Galician",gd:"Gaelic (Scottish)",gv:"Manx",ka:"Georgian",de:"German",el:"Greek",kl:"Kalaallisut",gn:"Guarani",gu:"Gujarati",ht:"Haitian Creole",ha:"Hausa",he:"Hebrew",hz:"Herero",hi:"Hindi",ho:"Hiri Motu",hu:"Hungarian",is:"Icelandic",io:"Ido",ig:"Igbo",id:"Indonesian",ia:"Interlingua",ie:"Interlingue",iu:"Inuktitut",ik:"Inupiak",ga:"Irish",it:"Italian",ja:"Japanese",jv:"Javanese",kn:"Kannada",kr:"Kanuri",ks:"Kashmiri",kk:"Kazakh",km:"Khmer",ki:"Kikuyu",rw:"Kinyarwanda",rn:"Kirundi",ky:"Kyrgyz",kv:"Komi",kg:"Kongo",ko:"Korean",ku:"Kurdish",kj:"Kwanyama",lo:"Lao",la:"Latin",lv:"Latvian",li:"Limburgish",ln:"Lingala",lt:"Lithuanian",lu:"Luga-Katanga",lg:"Luganda, Ganda",lb:"Luxembourgish",mk:"Macedonian",mg:"Malagasy",ms:"Malay",ml:"Malayalam",mt:"Maltese",mi:"Maori",mr:"Marathi",mh:"Marshallese",mo:"Moldavian",mn:"Mongolian",na:"Nauru",nv:"Navajo",ng:"Ndonga",nd:"Northern Ndebele",ne:"Nepali",no:"Norwegian",nb:"Norwegian bokmål",nn:"Norwegian nynorsk",ii:"Sichuan Yi",oc:"Occitan",oj:"Ojibwe",cu:"Old Church Slavonic",or:"Oriya",om:"Oromo",os:"Ossetian",pi:"Pāli",ps:"Pashto, Pushto",fa:"Persian (Farsi)",pl:"Polish",pt:"Portuguese",pa:"Punjabi (Eastern)",qu:"Quechua",rm:"Romansh",ro:"Romanian",ru:"Russian",se:"Sami",sm:"Samoan",sg:"Sango",sa:"Sanskrit",sr:"Serbian",sh:"Serbo-Croatian",st:"Sesotho",tn:"Setswana",sn:"Shona",sd:"Sindhi",si:"Sinhalese",ss:"Swati",sk:"Slovak",sl:"Slovenian",so:"Somali",nr:"Southern Ndebele",es:"Spanish",su:"Sundanese",sw:"Swahili (Kiswahili)",sv:"Swedish",tl:"Tagalog",ty:"Tahitian",tg:"Tajik",ta:"Tamil",tt:"Tatar",te:"Telugu",th:"Thai",bo:"Tibetan",ti:"Tigrinya",to:"Tonga",ts:"Tsonga",tr:"Turkish",tk:"Turkmen",tw:"Twi",ug:"Uyghur",uk:"Ukrainian",ur:"Urdu",uz:"Uzbek",ve:"Venda",vi:"Vietnamese",vo:"Volapük",wa:"Wallon",cy:"Welsh",wo:"Wolof",fy:"Western Frisian",xh:"Xhosa",yi:"Yiddish",yo:"Yoruba",za:"Zhuang, Chuang",zu:"Zulu"},L={GENERATE_SEO_FIELD:"GENERATE_SEO_FIELD",UPDATE_PAGE_METADATA:"UPDATE_PAGE_METADATA",GET_BLOCK_ASYNC_PROPS:"GET_BLOCK_ASYNC_PROPS",ASK_AI:"ASK_AI",GET_DRAFT_PAGE:"GET_DRAFT_PAGE",CREATE_PAGE:"CREATE_PAGE",UPDATE_PAGE:"UPDATE_PAGE",DELETE_PAGE:"DELETE_PAGE",DUPLICATE_PAGE:"DUPLICATE_PAGE",CHANGE_SLUG:"CHANGE_SLUG",TAKE_OFFLINE:"TAKE_OFFLINE",PUBLISH_PAGE:"PUBLISH_PAGE",PUBLISH_CHANGES:"PUBLISH_CHANGES",ADD_NEW_LANGUAGE:"ADD_NEW_LANGUAGE",EDIT_LANGUAGE:"EDIT_LANGUAGE",DELETE_LANGUAGE:"DELETE_LANGUAGE",GET_CHANGES:"GET_CHANGES",GET_SERVER_BLOCK:"GET_SERVER_BLOCK",GET_LANGUAGE_PAGES:"GET_LANGUAGE_PAGES",GET_PROJECT_PAGES:"GET_PROJECT_PAGES",GET_WEBSITE_PAGES:"GET_WEBSITE_PAGES",UPDATE_WEBSITE_SETTINGS:"UPDATE_WEBSITE_SETTINGS",GET_COLLECTIONS:"GET_COLLECTIONS",GET_PAGE_TYPES:"GET_PAGE_TYPES",SEARCH_PAGES:"SEARCH_PAGES",GET_WEBSITE_DRAFT_SETTINGS:"GET_WEBSITE_DRAFT_SETTINGS",AI_CONTEXT:"AI_CONTEXT",GET_WEBSITE_DATA:"GET_WEBSITE_DATA",UPDATE_WEBSITE_DATA:"UPDATE_WEBSITE_DATA",GET_CHAI_USER:"GET_CHAI_USER",RELEASE_LOCK:"RELEASE_LOCK",GET_SEO_FIELDS:"GET_SEO_FIELDS",GET_BUILDER_PAGE_DATA:"GET_BUILDER_PAGE_DATA",GET_PAGE_REVISIONS:"GET_PAGE_REVISIONS",DELETE_PAGE_REVISION:"DELETE_PAGE_REVISION",RESTORE_PAGE_REVISION:"RESTORE_PAGE_REVISION",GET_ROLE_AND_PERMISSIONS:"GET_ROLE_AND_PERMISSIONS",UPSERT_LIBRARY_ITEM:"UPSERT_LIBRARY_ITEM",GET_LIBRARIES:"GET_LIBRARIES",GET_LIBRARY_ITEM:"GET_LIBRARY_ITEM",GET_LIBRARY_ITEMS:"GET_LIBRARY_ITEMS",DELETE_LIBRARY_ITEM:"DELETE_LIBRARY_ITEM",MARK_AS_TEMPLATE:"MARK_AS_TEMPLATE",UNMARK_AS_TEMPLATE:"UNMARK_AS_TEMPLATE",GET_TEMPLATES_BY_TYPE:"GET_TEMPLATES_BY_TYPE",GET_DYNAMIC_PAGES:"GET_DYNAMIC_PAGES",UPLOAD_ASSET:"UPLOAD_ASSET",DELETE_ASSET:"DELETE_ASSET",UPDATE_ASSET:"UPDATE_ASSET",GET_ASSETS:"GET_ASSETS",GET_ASSET:"GET_ASSET"},Y="chaibuilder";let ar=0;function dn(e,s){const n=`atom${++ar}`,a={toString(){return n}};return typeof e=="function"?a.read=e:(a.init=e,a.read=rr,a.write=ir),s&&(a.write=s),a}function rr(e){return e(this)}function ir(e,s,n){return s(this,typeof n=="function"?n(e(this)):n)}const lr=Symbol(""),or=e=>typeof(e==null?void 0:e.then)=="function";function cr(e=()=>{try{return window.localStorage}catch{return}},s){var n;let a,r;const i={getItem:(u,d)=>{var h,g;const b=p=>{if(p=p||"",a!==p){try{r=JSON.parse(p,s==null?void 0:s.reviver)}catch{return d}a=p}return r},y=(g=(h=e())==null?void 0:h.getItem(u))!=null?g:null;return or(y)?y.then(b):b(y)},setItem:(u,d)=>{var h;return(h=e())==null?void 0:h.setItem(u,JSON.stringify(d,void 0))},removeItem:u=>{var d;return(d=e())==null?void 0:d.removeItem(u)}},l=u=>(d,h,g)=>u(d,b=>{let y;try{y=JSON.parse(b||"")}catch{y=g}h(y)});let c;try{c=(n=e())==null?void 0:n.subscribe}catch{}return!c&&typeof window<"u"&&typeof window.addEventListener=="function"&&window.Storage&&(c=(u,d)=>{if(!(e()instanceof window.Storage))return()=>{};const h=g=>{g.storageArea===e()&&g.key===u&&d(g.newValue)};return window.addEventListener("storage",h),()=>{window.removeEventListener("storage",h)}}),c&&(i.subscribe=l(c)),i}const ur=cr();function _n(e,s,n=ur,a){const r=dn(s);return r.onMount=l=>{l(n.getItem(e,s));let c;return n.subscribe&&(c=n.subscribe(e,l,s)),c},dn(l=>l(r),(l,c,u)=>{const d=typeof u=="function"?u(l(r)):u;return d===lr?(c(r,s),n.removeItem(e)):d instanceof Promise?d.then(h=>(c(r,h),n.setItem(e,h))):(c(r,d),n.setItem(e,d))})}localStorage.removeItem("_chai_user");localStorage.removeItem("__chai__user");const Dn="__logged_in_user",dr=_n(Dn,null),Ue=()=>{const[e,s]=Ie.useAtom(dr),n=f.useCallback(()=>{s(null),localStorage.removeItem(Dn)},[s]),a=f.useMemo(()=>{if(!(e!=null&&e.expiresAt))return!1;if(!e||!(e!=null&&e.refreshToken))return!0;const r=Math.floor(Date.now()/1e3);return e.expiresAt-r<=0},[e]);return{isLoggedIn:!!e,isSessionExpired:a,user:e,setUser:s,logout:n}},$s=async(e,s,n={})=>await fetch(e,{method:"POST",headers:{"Content-Type":"application/json",...n},body:JSON.stringify(s)}),J=()=>{const{user:e,logout:s}=Ue(),n=D.useQueryClient(),a=e==null?void 0:e.accessToken;return f.useCallback(async(r,i,l={})=>{if(!a)return null;try{const c=m.get(i,"action","").toLowerCase(),u=await $s(r+(c?`?action=${c}`:""),i,{...l,Authorization:`Bearer ${a}`});if(u.status===401)return console.log("401 Response",u),n.invalidateQueries({queryKey:[Y]}),s(),null;if(!u.ok){const d=await u.json();throw console.error(`API Error (${u.status}):`,d),{status:u.status,statusText:u.statusText,...d,message:d.error||d.message||`Server error: ${u.status}`}}return await u.json()}catch(c){throw console.error("API request failed:",i,c),c}},[a,s,n])},Bn=()=>{const e=re(),s=D.useQueryClient(),n=J();return D.useMutation({mutationFn:async a=>n(e,{action:L.RELEASE_LOCK,data:a}),onSuccess:()=>{s.invalidateQueries({queryKey:[Y,L.GET_DRAFT_PAGE]})}})},Mn=()=>{const e=re(),s=D.useQueryClient(),n=J();return D.useMutation({mutationFn:async a=>n(e,{action:L.UPDATE_WEBSITE_SETTINGS,data:a}),onSuccess:(a,r)=>{var i;s.invalidateQueries({queryKey:[Y,L.GET_WEBSITE_DRAFT_SETTINGS]}),(i=r==null?void 0:r.settings)!=null&&i.theme||V.toast.success("Website settings updated successfully.")},onError:a=>{V.toast.error("Failed to update website settings",{description:a.message})}})},mr=()=>{const e=re(),s=D.useQueryClient(),n=J();return D.useMutation({mutationFn:async a=>n(e,{action:L.UPDATE_WEBSITE_DATA,data:a}),onSuccess:()=>{s.invalidateQueries({queryKey:[Y,L.GET_WEBSITE_DATA]}),V.toast.success("Website data updated successfully.")},onError:a=>{V.toast.error("Failed to update website data",{description:a.message})}})};function _e(){const[e,s]=f.useState(new URLSearchParams(window.location.search));return f.useEffect(()=>{const n=()=>{s(new URLSearchParams(window.location.search))};return window.addEventListener("popstate",n),()=>{window.removeEventListener("popstate",n)}},[]),[e,s]}const hr=Ie.atom({}),On=()=>Ie.useAtom(hr),fr=()=>{const[e]=_e(),s=e.get("page"),n=f.useRef(""),{mutate:a}=Bn();f.useEffect(()=>{!m.isEmpty(n.current)&&s!==n.current&&a({id:n.current}),n.current=s},[s,a,n])},He=(e,s)=>{const[n]=On();return f.useMemo(()=>m.get(n,e,s),[n,e,s])},re=()=>He("apiUrl","/chai/api"),js=()=>He("usersApiUrl","/chai/users"),Xt=()=>He("assetsApiUrl","/chai/assets"),Gn=()=>He("realtimeInstance",null),Ke=e=>{const s=re(),[n]=_e(),a=e??n.get("page"),r=J();return D.useQuery({queryKey:[Y,L.GET_LANGUAGE_PAGES,a],initialData:[],queryFn:async()=>{if(!a)return null;const i=await r(s,{action:L.GET_LANGUAGE_PAGES,data:{id:a}});return m.reverse(m.sortBy(i,"primaryPage"))},enabled:!!a})},Ze=()=>{const e=re(),s=J();return D.useQuery({queryKey:[Y,L.GET_WEBSITE_DRAFT_SETTINGS],initialData:{theme:{},fallbackLang:"en",languages:[]},queryFn:async()=>s(e,{action:L.GET_WEBSITE_DRAFT_SETTINGS,data:{draft:!0}})})},Rn=e=>{const{fallbackLang:s}=q.useLanguages(),{data:n}=Ze(),{data:a,isFetching:r}=Ke(),i=f.useMemo(()=>{const l={[s]:!0};return m.each(m.get(n,"languages"),c=>{const u=m.find(a,{lang:c});l[c]=!!u}),l},[s,a,n]);return r||m.isEmpty(e)||e&&i[e]},Vs=()=>{const e=D.useQueryClient(),{data:s}=D.useQuery({queryKey:[Y,L.AI_CONTEXT],initialData:"",queryFn:()=>"",staleTime:0});return{setAiContext:f.useCallback(a=>{e.setQueryData([Y,L.AI_CONTEXT],a)},[e]),aiContext:s}},Zt=()=>{const e=J(),s=re();return D.useQuery({queryKey:[Y,L.GET_WEBSITE_PAGES],staleTime:1e3*60*5,queryFn:async()=>e(s,{action:L.GET_WEBSITE_PAGES})||[],placeholderData:n=>n})},gr=Ie.atom({lastSaved:void 0}),vs=()=>Ie.useAtom(gr),Te=()=>{const[e]=_e(),s=e.get("page"),[n]=Un(),{data:a,isFetching:r}=Zt();return{data:f.useMemo(()=>({...m.find(a,{id:s})||{},metadata:n}),[a,s,n]),isFetching:r}},At=()=>{const[e]=_e(),s=e.get("lang")??"",{data:n,isFetching:a}=Ke();return{data:f.useMemo(()=>m.find(n,{lang:s})||{},[n,s]),isFetching:a}},xr=Ie.atom({}),Un=()=>Ie.useAtom(xr),et=e=>{const s=js(),n=J();return D.useQuery({queryKey:[Y,"chaiUserInfo",e],queryFn:async()=>await n(s,{action:L.GET_CHAI_USER,data:{userId:e}}),enabled:!m.isEmpty(e)})},pr=Ie.atom(void 0),Hs=Ie.atom({status:"checking",requestedBy:"",isTakeOverRequested:!1}),es=()=>{const[e]=_e(),s=e.get("page"),{user:n}=Ue(),[a,r]=Ie.useAtom(pr),[i]=Ie.useAtom(Hs),l=q.useChaiFeatureFlag("realtime-page-lock");return f.useMemo(()=>({isLocked:l?s&&i.status==="locked":s&&(n==null?void 0:n.id)!==a,currentEditor:a,setCurrentEditor:c=>r(c)}),[l,s,i.status,n==null?void 0:n.id,a,r])},yr=()=>{const e=Gn(),{data:s}=Te(),{user:n}=Ue(),a=s==null?void 0:s.id,[r,i]=Ie.useAtom(Hs),l=f.useRef(!1),c=q.useChaiFeatureFlag("realtime-page-lock");return f.useEffect(()=>{r.status==="locked"||!a||!(n!=null&&n.id)||!e||!c||l.current||setTimeout(()=>{l.current||(l.current=!0,e==null||e.listenEvent("TAKE_OVER_REQUESTED",u=>{(u==null?void 0:u.requesterUserId)!==(n==null?void 0:n.id)&&i({...r,requestedBy:u==null?void 0:u.requesterUserId})}))},1e3)},[r,e,i,a,c,n==null?void 0:n.id]),f.useEffect(()=>{if(!c||!e||!a||!(n!=null&&n.id))return;async function u(){const d=await(e==null?void 0:e.joinPage(a,n==null?void 0:n.id));i({...r,status:d?"editing":"locked",requestedBy:""})}return u(),()=>{e==null||e.leavePage(a,n==null?void 0:n.id)}},[a,c]),{}},Fn=()=>{const e=Gn(),{data:s}=Te(),{user:n}=Ue(),a=s==null?void 0:s.id,[r,i]=Ie.useAtom(Hs),{saveState:l,savePage:c}=q.useSavePage(),u=D.useQueryClient(),d=f.useCallback(()=>{!e||!a||!(n!=null&&n.id)||(i({...r,isTakeOverRequested:!0}),e==null||e.requestTakeOver(a,n==null?void 0:n.id),e==null||e.listenEvent("TAKE_OVER_REQUEST_ACCEPTED",()=>{V.toast.success("Your Page Take Over Request Accepted",{position:"top-center"}),i({status:"editing",requestedBy:"",isTakeOverRequested:!1}),u.invalidateQueries({queryKey:[Y,L.GET_DRAFT_PAGE]})}),e==null||e.listenEvent("TAKE_OVER_REQUEST_REJECTED",()=>{i({...r,isTakeOverRequested:!1}),V.toast.warning("Your Page Take Over Request Rejected",{position:"top-center",closeButton:!0,duration:1/0})}))},[e,a,n==null?void 0:n.id,i,r,u]),h=f.useCallback(async()=>{!e||!a||!(n!=null&&n.id)||(l!=="SAVED"&&(c(),await new Promise(b=>setTimeout(b,1500))),e==null||e.acceptTakeOver(a,n==null?void 0:n.id),i({status:"locked",requestedBy:"",isTakeOverRequested:!1}))},[a,e,n==null?void 0:n.id,i,c,l]),g=f.useCallback(()=>{!e||!a||!(n!=null&&n.id)||(e==null||e.rejectTakeOver(a,n==null?void 0:n.id),i({status:"editing",requestedBy:"",isTakeOverRequested:!1}))},[a,e,n==null?void 0:n.id,i]);return{pageLock:r,requestTakeOver:d,acceptTakeOver:h,rejectTakeOver:g}},Ks=()=>{const{data:e}=Ze();return f.useMemo(()=>(e==null?void 0:e.fallbackLang)||"en",[e])},jr=Ie.atom(null),qn=()=>Ie.useAtom(jr),zn=()=>{const[e]=qn();return(e==null?void 0:e.slug)||""};function vr(e,s){const[n,a]=f.useState(e);return f.useEffect(()=>{const r=setTimeout(()=>a(e),s);return()=>clearTimeout(r)},[e,s]),n}const br=({query:e,uuid:s})=>{const{selectedLang:n,fallbackLang:a}=q.useLanguages(),{data:r}=Te(),i=r==null?void 0:r.pageType,l=re(),c=J(),{data:u,isFetching:d}=D.useQuery({queryKey:[L.GET_DYNAMIC_PAGES,e,i,s],initialData:[],queryFn:async()=>await c(l,{action:L.GET_DYNAMIC_PAGES,data:{query:e,pageType:i,uuid:s}})||[]}),h=f.useMemo(()=>n===""?u.filter(g=>g.lang===""||g.lang===a):u.filter(g=>g.lang===n),[n,a,u]);return{allLangPages:u,data:h,isFetching:d}},wr=()=>{const{selectedLang:e,fallbackLang:s}=q.useLanguages(),[n,a]=qn(),[r,i]=f.useState(""),l=vr(r,500),{allLangPages:c,data:u,isFetching:d}=br({query:l}),h=f.useCallback(y=>a(y),[a]),g=f.useCallback(y=>i(y),[i]),b=f.useCallback(()=>{if(!n)return;const y=!(n!=null&&n.primaryPage),p=e.length===0,w=y?n==null?void 0:n.id:n==null?void 0:n.primaryPage,N=c.filter(C=>(C==null?void 0:C.primaryPage)===w||C.id===w).find(C=>p?C.lang===e||C.lang===s:C.lang===e);a(N||n)},[n,e,c,a,s]);return{isPending:d,dynamicPage:n,searchQuery:r,selectedLang:e,dynamicPages:u,allLangPages:c,updateDynamicPage:h,updateSearchQuery:g,onChangeLanguage:b}},$n=()=>{const[e]=_e(),s=e.get("page"),n=re(),{setAiContext:a}=Vs(),{setCurrentEditor:r}=es(),[,i]=vs(),[,l]=Un(),c=J();return D.useQuery({queryKey:[Y,L.GET_DRAFT_PAGE,s],staleTime:1/0,gcTime:1/0,queryFn:async()=>{r("");const u=await c(n,{action:L.GET_DRAFT_PAGE,data:{id:s,draft:!0}});r(u.currentEditor);const d=u.blocks??[],h=m.find(d,{_type:"@chai/ai-context"});return a(m.get(h,"_value","")||""),i(g=>({...g,lastSaved:u.lastSaved})),l(m.get(u,"metadata",{})),d},enabled:!!s})},Qs=()=>{const{data:e}=Te(),{data:s}=At(),n=re(),a=J(),r=Ks(),i=zn();return D.useQuery({queryKey:[Y,L.GET_BUILDER_PAGE_DATA,s==null?void 0:s.id,i],initialData:{},queryFn:async()=>a(n,{action:L.GET_BUILDER_PAGE_DATA,data:{pageType:e==null?void 0:e.pageType,lang:(s==null?void 0:s.lang)||r,dynamic:e==null?void 0:e.dynamic,pageProps:{slug:(s==null?void 0:s.slug)+i,searchParams:{},pageType:s==null?void 0:s.pageType,fallbackLang:r,lastSaved:s.lastSaved,pageId:e.id,primaryPageId:s.primaryPage||e.id,pageBaseSlug:s==null?void 0:s.slug,dynamic:e==null?void 0:e.dynamic,languagePageId:s.id}}}),enabled:!!(s!=null&&s.pageType)})},Sr=({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 flex items-center gap-1 text-xs font-light text-gray-500",children:t.jsxs(o.Tooltip,{children:[t.jsx(o.TooltipTrigger,{children:t.jsx(E.LockIcon,{className:"h-3 w-3"})}),t.jsx(o.TooltipContent,{children:t.jsxs("p",{children:[n.name," is editing"]})})]})})},mn=({userId:e})=>{const{data:s}=et(e);return(s==null?void 0:s.name)||"Unknown"};function Er({avatar:e,name:s,email:n,lastSaved:a,onTakeOver:r,pageLock:i,realtimePageLockEnabled:l}){const[c,u]=f.useState(!1),d=()=>{u(!1),r()};return t.jsx("div",{className:"fixed bottom-0 left-0 right-0 top-[50px] z-[20] flex w-screen items-center justify-center bg-black/30 backdrop-blur-sm",children:t.jsxs(o.Card,{className:"mx-auto w-full max-w-md",children:[t.jsx(o.CardHeader,{className:"space-y-1",children:t.jsxs(o.CardTitle,{className:"flex items-center gap-2 text-2xl",children:[t.jsx(E.LockIcon,{className:"h-6 w-6 text-yellow-500"}),"Page locked for editing"]})}),t.jsx(o.CardContent,{className:"grid gap-4",children:t.jsxs("div",{children:[t.jsxs("div",{className:"flex items-center space-x-4",children:[e?t.jsx("img",{src:e,alt:s,className:"h-12 w-12 rounded-full border border-gray-300"}):t.jsx(E.UserIcon,{className:"h-12 w-12 rounded-full border border-gray-300 p-2"}),t.jsxs("div",{className:"space-y-1",children:[t.jsx("h3",{className:"font-semibold",children:s}),n&&t.jsx("p",{className:"text-sm text-muted-foreground",children:n}),a&&t.jsxs("p",{className:"text-sm text-muted-foreground",children:["Last saved:"," ",Ct.formatDistanceToNow(new Date(a),{addSuffix:!0})]})]})]}),t.jsx("div",{className:"mt-4 text-sm",children:t.jsx("p",{children:"This user is currently editing the page. You cannot make changes."})})]})}),t.jsx(o.CardFooter,{children:l?t.jsx(o.Button,{disabled:i.isTakeOverRequested,onClick:d,className:"w-full",variant:"destructive",children:i.isTakeOverRequested?"Page take is requested.":"Request take over"}):t.jsxs(o.AlertDialog,{open:c,onOpenChange:u,children:[t.jsx(o.AlertDialogTrigger,{asChild:!0,children:t.jsxs("span",{className:"flex flex-col items-center",children:[t.jsx(o.Button,{className:"w-full",variant:"destructive",children:"Take over"}),t.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:"If you need to edit, you can take over the lock, but be aware that the other user might lose unsaved changes."})]})}),t.jsxs(o.AlertDialogContent,{className:"z-[99]",children:[t.jsxs(o.AlertDialogHeader,{children:[t.jsx(o.AlertDialogTitle,{children:"Are you sure you want to take over?"}),t.jsxs(o.AlertDialogDescription,{children:[t.jsxs("span",{className:"flex items-center space-x-2 text-yellow-500",children:[t.jsx(E.AlertTriangleIcon,{className:"h-5 w-5"}),t.jsx("span",{children:"This action might cause the other user to lose unsaved changes."})]}),t.jsx("br",{}),t.jsxs("span",{className:"mt-2",children:["By taking over, you will become the active editor of this page, and ",s," will lose their editing access."]})]})]}),t.jsxs(o.AlertDialogFooter,{children:[t.jsx(o.AlertDialogCancel,{children:"Cancel"}),t.jsx(o.AlertDialogAction,{onClick:d,children:"Yes, Take Over"})]})]})]})})]})})}const Nr=()=>{const{pageLock:e,acceptTakeOver:s,rejectTakeOver:n}=Fn();return t.jsx("div",{className:"fixed bottom-0 left-0 right-0 top-[50px] z-[20] flex w-screen items-center justify-center bg-black/30 backdrop-blur-sm",children:t.jsxs(o.Card,{className:"mx-auto w-full max-w-md",children:[t.jsx(o.CardHeader,{className:"space-y-1",children:t.jsxs(o.CardTitle,{className:"flex items-center gap-2 text-2xl",children:[t.jsx(E.AccessibilityIcon,{className:"h-6 w-6 text-yellow-500"}),t.jsx(mn,{userId:e==null?void 0:e.requestedBy})," has requested to take over this page"]})}),t.jsx(o.CardContent,{className:"grid gap-4",children:t.jsx("div",{children:t.jsx("div",{className:"mt-4 text-sm",children:t.jsxs("p",{children:[t.jsx(mn,{userId:e==null?void 0:e.requestedBy})," has requested to take over this page. Do you want to accept the request?"]})})})}),t.jsxs(o.CardFooter,{className:"flex items-center justify-end gap-2",children:[t.jsx(o.Button,{onClick:s,children:"Yes"}),t.jsx(o.Button,{variant:"outline",onClick:n,children:"No"})]})]})})},Cr=()=>{const{isLocked:e,currentEditor:s}=es(),{data:n}=et(s),[a]=_e(),r=a.get("page"),{mutate:i}=Bn(),{isFetching:l}=$n(),[c]=vs(),{pageLock:u,requestTakeOver:d}=Fn(),h=q.useChaiFeatureFlag("realtime-page-lock"),g=f.useCallback(()=>{h?d():i({id:r})},[r,i,d,h]);return h&&(u!=null&&u.requestedBy)?t.jsx(Nr,{}):(h?u.status!=="locked":!e||l)?t.jsx("div",{className:""}):t.jsx(Er,{...n,name:(n==null?void 0:n.name)||"Unknown User",email:(n==null?void 0:n.email)||"",lastSaved:(c==null?void 0:c.lastSaved)||"",onTakeOver:g,pageLock:u,realtimePageLockEnabled:h})},Ar=()=>{const[e,s]=_e(),n=e.get("lang"),a=Rn(n),{setSelectedLang:r}=q.useLanguages(),i=()=>{const c=new URLSearchParams(window.location.search);c.delete("lang");const u=c.toString(),d=`${window.location.pathname}${u?`?${u}`:""}`;window.history.pushState({},"",d),s(c),r(""),window.dispatchEvent(new PopStateEvent("popstate"))};if(a)return null;const l=m.get(ke,n);return t.jsx("div",{className:"fixed bottom-0 left-0 right-0 top-12 z-[20] flex w-screen items-center justify-center bg-black/30 backdrop-blur-sm",children:t.jsxs(o.Card,{className:"mx-auto w-full max-w-md",children:[t.jsx(o.CardHeader,{className:"space-y-1",children:t.jsxs(o.CardTitle,{className:"flex items-center gap-2 text-2xl",children:[t.jsx(E.LockIcon,{className:"h-6 w-6 text-yellow-500"}),'Page missing for "',l,'" language.']})}),t.jsx(o.CardContent,{className:"grid gap-4",children:t.jsxs("div",{children:['Page is not available in the "',l,'" language. Either create the page in the "',l,'" language or switch to the base language.']})}),t.jsx(o.CardFooter,{children:t.jsx(o.Button,{onClick:i,className:"w-full",variant:"destructive",children:"Switch to default language"})})]})})},Tr=e=>{const s=re(),n=J();return D.useMutation({mutationFn:async a=>n(s,{action:L.UPSERT_LIBRARY_ITEM,data:a}),onSuccess:a=>{e(a)},onError:a=>{console.error("Error saving block:",a),V.toast.error("Failed to save block",{description:a instanceof Error?a.message:"Unknown error"})}})},Pr=e=>{const s=re(),n=J();return D.useQuery({queryKey:[Y,"uiBlockDetails",e],enabled:!!e,queryFn:async()=>{if(!e)return null;try{return await n(s,{action:L.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})},kr=e=>{const s=re(),n=J();return D.useMutation({mutationFn:async a=>n(s,{action:L.DELETE_LIBRARY_ITEM,data:{id:a}}),onSuccess:()=>{e()},onError:a=>{console.error("Error deleting block:",a),V.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[l,c]=f.useState(!1),u=q.useUpdateBlocksPropsRealtime(),d=kr(()=>{u([e],{_libBlockId:void 0}),V.toast.success("Block deleted successfully"),c(!1),a()}),h=()=>{c(!0),d.mutate(s)},g=t.jsxs(o.Button,{type:"button",variant:"destructive",size:"sm",onClick:b=>b.preventDefault(),disabled:l,children:[t.jsx(E.Trash2,{className:"h-4 w-4 mr-2"}),"Delete"]});return t.jsxs(o.Popover,{open:n,onOpenChange:b=>!b&&a(),children:[t.jsx(o.PopoverTrigger,{asChild:!0,children:i||g}),t.jsx(o.PopoverContent,{className:"w-72 p-4 z-[9999]",sideOffset:5,align:"center",children:t.jsxs("div",{className:"space-y-3",children:[t.jsx("h4",{className:"font-medium",children:"Delete Block"}),t.jsxs("p",{className:"text-sm",children:["Are you sure you want to delete the block",t.jsxs("span",{className:"font-medium",children:[' "',r,'"']}),"?"]}),t.jsx("p",{className:"text-xs text-muted-foreground",children:"This block will be permanently removed from the library. This action cannot be undone."}),t.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[t.jsx(o.Button,{type:"button",variant:"outline",size:"sm",onClick:a,disabled:l,children:"Cancel"}),t.jsx(o.Button,{type:"button",variant:"destructive",size:"sm",onClick:h,disabled:l,children:l?"Deleting...":"Delete"})]})]})})]})},Ir=({blockId:e,libBlockId:s,blockName:n,size:a="sm",className:r="",close:i})=>{const[l,c]=f.useState(!1);return t.jsx(Lr,{blockId:e,libBlockId:s,isOpen:l,onClose:()=>{c(!1),i()},blockName:n,trigger:t.jsxs(o.Button,{type:"button",variant:"destructive",size:a,className:r,onClick:()=>c(!0),children:[t.jsx(E.Trash2,{className:"h-4 w-4 mr-2"}),"Delete"]})})},_r=()=>{const e=re(),s=J(),n=D.useQueryClient(),{data:a=[],isLoading:r,error:i}=D.useQuery({queryKey:[Y,"library-groups"],queryFn:async()=>{try{return await s(e,{action:"GET_LIBRARY_GROUPS"})||[]}catch(u){return console.error("Error fetching library groups:",u),[]}},initialData:[]}),{mutateAsync:l,isPending:c}=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:[Y,"library-groups"]}),V.toast.success("Group created successfully")},onError:u=>{console.error("Error creating group:",u),V.toast.error("Failed to create group",{description:u instanceof Error?u.message:"Unknown error"})}});return{groups:a,isLoading:r,error:i,createGroup:l,isCreating:c}},Dr=({value:e,onChange:s})=>{const[n,a]=f.useState(!1),[r,i]=f.useState(""),l=f.useRef(null),{groups:c}=_r(),[u,d]=f.useState([{id:"hero",name:"Hero"},{id:"feature",name:"Feature"},{id:"footer",name:"Footer"},{id:"content",name:"Content"},{id:"testimonial",name:"Testimonial"},{id:"pricing",name:"Pricing"},{id:"login",name:"Login"},{id:"logos",name:"Logos"},{id:"about",name:"About"},{id:"banner",name:"Banner"},{id:"blog",name:"Blog"},{id:"careers",name:"Careers"},{id:"casestudy",name:"Casestudy"},{id:"changelog",name:"Changelog"},{id:"compare",name:"Compare"},{id:"contact",name:"Contact"},{id:"cta",name:"Cta"},{id:"faq",name:"Faq"},{id:"gallery",name:"Gallery"},{id:"integration",name:"Integration"},{id:"list",name:"List"},{id:"navbar",name:"Navbar"},{id:"product",name:"Product"},{id:"signup",name:"Signup"},{id:"stats",name:"Stats"},{id:"team",name:"Team"},{id:"timeline",name:"Timeline"}]),h=f.useMemo(()=>[...c,...u.filter(y=>!c.some(p=>p.id===y.id))],[c,u]),g=()=>{const y=r.trim();if(!y)return;const p={id:y,name:y};d(w=>[...w,p]),s(p.id),i(""),a(!1)};f.useEffect(()=>{n&&l.current&&l.current.focus()},[n]);const b=y=>{y.key==="Enter"&&(y.preventDefault(),g())};return f.useEffect(()=>{e&&!h.some(y=>y.id===e)&&s("")},[e,h,s]),n?t.jsxs("div",{className:"space-y-2",children:[t.jsx(o.Input,{ref:l,placeholder:"Enter new group name",value:r,onChange:y=>i(y.target.value),onKeyDown:b}),t.jsxs("div",{className:"flex justify-end gap-2",children:[t.jsx(o.Button,{variant:"outline",size:"sm",onClick:()=>a(!1),children:"Cancel"}),t.jsx(o.Button,{size:"sm",onClick:g,children:"Create"})]})]}):t.jsxs("div",{className:"flex gap-2",children:[t.jsxs("select",{className:"w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",value:e,onChange:y=>s(y.target.value),children:[t.jsx("option",{value:"",children:"Select a group"}),c.length>0&&t.jsx("optgroup",{label:"Library Groups",children:c.map(y=>t.jsx("option",{value:y.id,children:y.name},`lib-${y.id}`))}),u.length>0&&t.jsx("optgroup",{label:"Predefined Groups",children:u.filter(y=>!c.some(p=>p.id===y.id)).map(y=>t.jsx("option",{value:y.id,children:y.name},`local-${y.id}`))})]}),t.jsx(o.Button,{type:"button",size:"icon",variant:"outline",onClick:()=>a(!0),children:t.jsx(E.Plus,{className:"h-4 w-4"})})]})},Br=10*1024*1024,Mr=({value:e,onChange:s})=>{const[n,a]=f.useState(!1),r=f.useRef(null),i=f.useCallback(u=>{var h;const d=(h=u.target.files)==null?void 0:h[0];if(d){if(d.size>Br){V.toast.error("File too large",{description:`Maximum file size is 10mb. Selected file is ${(d.size/1024/1024).toFixed(2)}MB.`}),r.current&&(r.current.value="");return}try{a(!0);const g=new FileReader;g.onloadend=()=>{s(g.result),a(!1)},g.readAsDataURL(d)}catch(g){console.error("Error reading file:",g),a(!1),V.toast.error("Failed to process image",{description:g instanceof Error?g.message:"Unknown error"})}}},[s]),l=()=>{s(""),r.current&&(r.current.value="")},c=()=>{var u;(u=r.current)==null||u.click()};return t.jsxs("div",{className:"space-y-2",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(o.Input,{type:"file",ref:r,onChange:i,accept:"image/*",className:"hidden"}),t.jsx(o.Button,{type:"button",variant:"outline",onClick:c,disabled:n,className:"w-full",children:n?t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsx("div",{className:"animate-spin h-4 w-4 border-2 border-current border-t-transparent rounded-full"}),"Uploading..."]}):t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsx(E.ImageIcon,{className:"h-4 w-4"}),"Select image"]})}),e&&t.jsx(o.Button,{type:"button",variant:"outline",size:"icon",onClick:l,children:t.jsx(E.X,{className:"h-4 w-4"})})]}),e&&t.jsx("div",{className:"rounded-md max-h-[200px] h-[200px] overflow-hidden border aspect-video",children:t.jsx("img",{src:e,alt:"Preview",className:"w-full h-full object-contain"})})]})},je={...q.PERMISSIONS,ADD_PAGE:"add_page",EDIT_PAGE:"edit_page",EDIT_SLUG:"edit_slug",DELETE_PAGE:"delete_page",CHANGE_PAGE_TYPE:"change_page_type",PUBLISH_PAGE:"publish_page",UNPUBLISH_PAGE:"unpublish_page",MARK_AS_TEMPLATE:"mark_as_template",UNMARK_AS_TEMPLATE:"unmark_as_template",ADD_PARTIAL:"add_partial",EDIT_PARTIAL:"edit_partial",DELETE_PARTIAL:"delete_partial",PUBLISH_PARTIAL:"publish_partial",UNPUBLISH_PARTIAL:"unpublish_partial",EDIT_SEO:"edit_seo",RESTORE_REVISION:"restore_revision",DELETE_REVISION:"delete_revision",PUBLISH_THEME:"publish_theme",EDIT_SETTINGS:"edit_settings",ADD_LIBRARY_BLOCK:"create_library_block",ADD_LIBRARY_TEMPLATE:"add_library_template",EDIT_LIBRARY_BLOCK:"edit_library_block",EDIT_LIBRARY_TEMPLATE:"edit_library_template",DELETE_LIBRARY_BLOCK:"delete_library_block",DELETE_LIBRARY_TEMPLATE:"delete_library_template",ADD_MEDIA:"add_media",EDIT_MEDIA:"edit_media",DELETE_MEDIA:"delete_media"},Or=e=>{const{blocks:s,close:n,blockId:a}=e,{getPartailBlocks:r}=q.usePartailBlocksStore(),i=s.find(A=>A._id===a),l=i==null?void 0:i._libBlockId,c=!!l,u=f.useMemo(()=>s.some(A=>A._type==="PartialBlock"||A._type==="GlobalBlock"),[s]),d=f.useMemo(()=>{let A=[];for(const M of s)if(M._type==="PartialBlock"||M._type==="GlobalBlock"){let G=r(M.partialBlockId);M._parent&&(G==null?void 0:G.length)>0&&(G=G.map(T=>(m.isEmpty(T._parent)&&m.set(T,"_parent",M._parent),T))),A=[...A,...G]}else A.push(M);return A},[s,r]),[h,g]=f.useState(""),[b,y]=f.useState(""),[p,w]=f.useState(""),[v,N]=f.useState(""),[C,B]=f.useState({}),[S,P]=f.useState(!1),[O,z]=f.useState(c),[$,se]=f.useState(!1),{hasPermission:H}=q.usePermissions(),K=H(je.DELETE_LIBRARY_BLOCK),te=q.useUpdateBlocksPropsRealtime(),Q=()=>{te([a],{_libBlockId:void 0}),V.toast.success("Block delinked from library"),n()},{data:ne,isLoading:_,isError:U}=Pr(l);f.useEffect(()=>{U&&c&&(se(!0),z(!1))},[U,c]),f.useEffect(()=>{ne&&!_&&(g(ne.name||""),y(ne.group||""),w(ne.description||""),N(ne.preview||""),z(!1))},[ne,_]),f.useEffect(()=>{const A=h.trim().length>=2,M=b.trim()!=="";P(A&&M)},[h,b]);const he=()=>{const A={};return h.trim()?h.length<2&&(A.name="Name must be at least 2 characters"):A.name="Name is required",b||(A.group="Group is required"),B(A),Object.keys(A).length===0},{resetLibrary:ye}=q.useLibraryBlocks({id:""}),ce=Tr(A=>{c||te([a],{_libBlockId:A.id}),V.toast.success(`Block ${c?"updated":"saved"} successfully`),ye(A.library),n()}),j=async A=>{if(A.preventDefault(),!he())return;const M=d.map(G=>(m.has(G,"_libBlockId")&&delete G._libBlockId,G));ce.mutate({name:h.trim(),group:b,blocks:M,description:p.trim(),...v&&v.startsWith("data:")?{previewImage:v}:{},...c?{id:l}:{}})},x=ce.isPending;return O||_?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"})}):$?t.jsxs("div",{className:"p-6 space-y-4",children:[t.jsx("div",{className:"text-destructive font-medium",children:"Block Not Found"}),t.jsx("p",{className:"text-sm text-muted-foreground",children:"This block could not be found on the server. It may have been deleted."}),t.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[t.jsx(o.Button,{type:"button",variant:"outline",onClick:n,children:"Cancel"}),t.jsx(o.Button,{onClick:Q,variant:"destructive",children:"Delink Block"})]})]}):t.jsxs("div",{children:[u&&t.jsxs("div",{className:"mb-4 p-3 border border-destructive/50 bg-destructive/10 text-destructive rounded-md flex items-start gap-2",children:[t.jsx(E.AlertCircle,{className:"h-5 w-5 flex-shrink-0 mt-0.5"}),t.jsxs("div",{children:[t.jsx("p",{className:"font-medium",children:"Partial Blocks Detected"}),t.jsx("p",{className:"text-xs mt-1",children:"This block contains one or more Partial Blocks. Partial blocks will be merged into the library block"})]})]}),t.jsxs("form",{onSubmit:j,className:"space-y-4",children:[t.jsxs("div",{className:"space-y-2",children:[t.jsx(o.Label,{htmlFor:"name",className:C.name?"text-destructive":"",children:"Name"}),t.jsx(o.Input,{id:"name",placeholder:"Enter block name",value:h,onChange:A=>g(A.target.value),className:C.name?"border-destructive":""}),C.name&&t.jsx("p",{className:"text-xs text-destructive",children:C.name})]}),t.jsxs("div",{className:"space-y-2",children:[t.jsx(o.Label,{htmlFor:"group",className:C.group?"text-destructive":"",children:"Group"}),t.jsx(Dr,{value:b,onChange:y}),C.group&&t.jsx("p",{className:"text-xs text-destructive",children:C.group})]}),t.jsxs("div",{className:"space-y-2",children:[t.jsx(o.Label,{htmlFor:"description",children:"Description (optional)"}),t.jsx(o.Input,{id:"description",placeholder:"Enter a brief description",className:"resize-none",value:p,onChange:A=>w(A.target.value)})]}),t.jsxs("div",{className:"space-y-2",children:[t.jsx(o.Label,{htmlFor:"previewImage",children:"Preview Image (optional)"}),t.jsx(Mr,{value:v,onChange:N})]}),t.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[c&&K&&t.jsx(Ir,{blockId:a,libBlockId:l,blockName:h,className:"mr-auto",close:n}),t.jsx(o.Button,{type:"button",variant:"outline",onClick:n,disabled:x,children:"Cancel"}),t.jsx(o.Button,{type:"submit",disabled:x||!S,children:x?"Saving...":c?"Update Block":"Save Block"})]})]})]})},ae={PREVIEW:"Preview",THEME:"Theme",SAVEDRAFT:"Save draft",SAVING:"Saving",SAVED:"Saved",PUBLISHED:"Published",PUBLISH:"Publish",UNPUBLISH:"Unpublish",WEBSITEDATA:"Website data",OPEN:"Open",EDIT_LANGUAGE:"Edit language",ADD_NEW_LANGUAGE:"Add new language page",ENTER_LANGUAGE_DETAILS:"Enter the details for the language",LANGUAGE:"Language",PAGE_NAME:"Page Name",SLUG:"Slug",UPDATE:"Update",UPDATING:"Updating...",ADDING:"Adding...",CHOOSE_LANGUAGE:"Choose language",ALL_AVAILABLE_LANGUAGE_PAGE:"All available language page is created.",TO_UPDATE_SLUG:"To update slug use 'Change slug' action",SLUG_SHOULD_START_WITH:" (Slug should start with /{lang})",CHOOSE_LANGUAGE_TO_ADD_SLUG:"Choose language to add slug",ENTER_PAGE_SLUG:"Enter page slug",ENTER_PAGE_NAME:"Enter page name",DELETE:"Delete",CHANGE_SLUG:"Change slug",PRIMARY:"Primary",SLUG_MUST_START_WITH:"Slug must start with /",EDIT:"Edit",UNPUBLISH_MSG:"Are you sure you want to unpublish",MARK_AS_TEMPLATE:"Mark as template",UNMARK_AS_TEMPLATE:"Unmark as template",PAGE_ADD_SUCCESS:"New page added successfully.",GLOBAL_BLOCK_ADD_SUCCESS:"New global block added successfully.",SEO_SETTINGS_UPDATE_SUCCESS:"SEO Settings updated successfully.",PAGE_UPDATE_SUCCESS:"Page updated successfully.",GLOBAL_BLOCK_UPDATE_SUCCESS:"Global block updated successfully.",PAGE_DELETE_SUCCESS:"Page deleted successfully.",GLOBAL_BLOCK_DELETE_SUCCESS:"Global block deleted successfully.",PAGE_UNPUBLISH_SUCCESS:"Page unpublished successfully.",GLOBAL_BLOCK_UNPUBLISH_SUCCESS:"Global block unpublished successfully.",PAGE_PUBLISH_SUCCESS:"Page published successfully.",GLOBAL_BLOCK_PUBLISH_SUCCESS:"Global block published successfully.",PAGES_PUBLISH_SUCCESS:"Your changes have been published successfully.",SLUG_CHANGE_SUCCESS:"Slug changed successfully."},Gr={SLUG_ALREADY_USED:"This slug is already in use. Please choose a different one."},Pe=()=>{const e=re(),s=J();return D.useQuery({queryKey:[Y,L.GET_PAGE_TYPES],initialData:[],queryFn:async()=>s(e,{action:L.GET_PAGE_TYPES})})},Vn=e=>{const{data:s}=Pe();return f.useMemo(()=>s==null?void 0:s.find(n=>n.key===e),[s,e])},Rr=()=>{const e=re(),s=J();return D.useMutation({mutationFn:async({pageType:n,query:a})=>{try{return s(e,{action:L.SEARCH_PAGES,data:{pageType:n,query:Array.isArray(a)&&a.length>0?a[0]:a}})||[]}catch(r){return console.error(r),[]}}})},Hn=()=>{const e=re(),s=D.useQueryClient(),n=J(),{data:a}=Pe();return D.useMutation({mutationFn:async r=>await n(e,{action:L.CREATE_PAGE,data:r}),onSuccess:(r,i)=>{var c;i&&(i!=null&&i.primaryPage)?s.invalidateQueries({queryKey:[Y,L.GET_LANGUAGE_PAGES,i==null?void 0:i.primaryPage]}):s.invalidateQueries({queryKey:[Y,L.GET_WEBSITE_PAGES]});const l=i.template?`Page created from "${i.template.name}" template`:i.hasSlug===!1?"New "+((c=m.find(a,{key:i.pageType}))==null?void 0:c.name)+" added successfully":"New page added successfully";V.toast.success(l)},onError:(r,i)=>{const l=m.find(a,{key:i.pageType});V.toast.error(`Failed to add new ${l!=null&&l.hasSlug?"page":l.name}.`,{description:m.get(Gr,r.message,r.message)})}})},Ws=()=>{const e=re(),s=D.useQueryClient(),n=J(),{data:a}=Pe();return D.useMutation({mutationFn:async r=>await n(e,{action:L.UPDATE_PAGE,data:r}),onSuccess:(r,i)=>{i&&(i!=null&&i.primaryPage||i!=null&&i.seo)?s.invalidateQueries({queryKey:[Y,L.GET_LANGUAGE_PAGES,i==null?void 0:i.primaryPage]}):s.invalidateQueries({queryKey:[Y,L.GET_WEBSITE_PAGES]})},onError:(r,i)=>{const l=m.find(a,{key:i.pageType});V.toast.error(`Failed to update ${l!=null&&l.hasSlug?"page":l.name}.`,{description:r.message})}})},Ur=()=>{const e=re(),s=D.useQueryClient(),n=J(),{data:a}=Pe();return D.useMutation({mutationFn:async r=>n(e,{action:L.DELETE_PAGE,data:{id:r==null?void 0:r.id}}),onSuccess:(r,i)=>{if(r.code==="PAGE_LOCKED"){V.toast.error("Delete not allowed",{description:"Page is currently being edited by another user."});return}i&&(i!=null&&i.primaryPage)?s.invalidateQueries({queryKey:[Y,L.GET_LANGUAGE_PAGES,i==null?void 0:i.primaryPage]}):s.invalidateQueries({queryKey:[Y,L.GET_WEBSITE_PAGES]})},onError:(r,i)=>{const l=m.find(a,{key:i.pageType});V.toast.error(`Failed to delete ${l!=null&&l.hasSlug?"page":l.name}.`,{description:r.message})}})},Fr=()=>{const e=re(),s=D.useQueryClient(),n=J(),{data:a}=Pe();return D.useMutation({mutationFn:async r=>n(e,{action:L.TAKE_OFFLINE,data:{id:r==null?void 0:r.id}}),onSuccess:(r,i)=>{i&&(i!=null&&i.primaryPage)?s.invalidateQueries({queryKey:[Y,L.GET_LANGUAGE_PAGES,i==null?void 0:i.primaryPage]}):s.invalidateQueries({queryKey:[Y,L.GET_WEBSITE_PAGES]});const l=m.find(a,{key:i.pageType});V.toast.success(l!=null&&l.hasSlug?ae.PAGE_UNPUBLISH_SUCCESS:"New "+l.name+" added successfully.")},onError:(r,i)=>{const l=m.find(a,{key:i.pageType});V.toast.error(`Failed to take offline ${l!=null&&l.hasSlug?"page":l.name}.`,{description:r.message})}})},Ys=()=>{const e=re(),s=J(),n=D.useQueryClient(),{data:a}=Te();return D.useMutation({mutationFn:async({ids:r})=>s(e,{action:L.PUBLISH_CHANGES,data:{ids:r}}),onSuccess:()=>{n.invalidateQueries({queryKey:[Y,L.GET_CHANGES]}),n.invalidateQueries({queryKey:[Y,L.GET_WEBSITE_PAGES]}),n.invalidateQueries({queryKey:[Y,L.GET_LANGUAGE_PAGES,a==null?void 0:a.id]})},onError:()=>{V.toast.error("Failed to publish pages.")}})},qr=()=>{const e=re(),s=J(),n=D.useQueryClient();return D.useMutation({mutationFn:async a=>{var r;return s(e,{action:L.MARK_AS_TEMPLATE,data:{id:(r=a.page)==null?void 0:r.id,name:a.name,description:a.description,pageType:a.pageType,previewImage:a.previewImage}})},onSuccess:()=>{n.invalidateQueries({queryKey:[Y,L.GET_WEBSITE_PAGES]}),V.toast.success("Page marked as template successfully.")},onError:()=>{V.toast.error("Failed to mark page as template.")}})},zr=()=>{const e=re(),s=J(),n=D.useQueryClient();return D.useMutation({mutationFn:async a=>s(e,{action:L.UNMARK_AS_TEMPLATE,data:{id:a==null?void 0:a.id}}),onSuccess:()=>{n.invalidateQueries({queryKey:[Y,L.GET_WEBSITE_PAGES]}),V.toast.success("Page unmarked as template successfully.")},onError:()=>{V.toast.error("Failed to unmark page as template.")}})},$r=()=>{const e=re(),s=J(),n=D.useQueryClient();return D.useMutation({mutationFn:async({id:a,slug:r})=>s(e,{action:L.CHANGE_SLUG,data:{id:a,slug:r}}),onSuccess:(a,{primaryPage:r})=>{V.toast.success(ae.SLUG_CHANGE_SUCCESS),r?n.invalidateQueries({queryKey:[Y,L.GET_LANGUAGE_PAGES,r]}):n.invalidateQueries({queryKey:[Y,L.GET_WEBSITE_PAGES]})},onError:()=>{V.toast.error("Failed to change slug")}})};var Js={};(function e(s,n,a,r){var i=!!(s.Worker&&s.Blob&&s.Promise&&s.OffscreenCanvas&&s.OffscreenCanvasRenderingContext2D&&s.HTMLCanvasElement&&s.HTMLCanvasElement.prototype.transferControlToOffscreen&&s.URL&&s.URL.createObjectURL),l=typeof Path2D=="function"&&typeof DOMMatrix=="function",c=function(){if(!s.OffscreenCanvas)return!1;var j=new OffscreenCanvas(1,1),x=j.getContext("2d");x.fillRect(0,0,1,1);var A=j.transferToImageBitmap();try{x.createPattern(A,"no-repeat")}catch{return!1}return!0}();function u(){}function d(j){var x=n.exports.Promise,A=x!==void 0?x:s.Promise;return typeof A=="function"?new A(j):(j(u,u),null)}var h=function(j,x){return{transform:function(A){if(j)return A;if(x.has(A))return x.get(A);var M=new OffscreenCanvas(A.width,A.height),G=M.getContext("2d");return G.drawImage(A,0,0),x.set(A,M),M},clear:function(){x.clear()}}}(c,new Map),g=function(){var j=Math.floor(16.666666666666668),x,A,M={},G=0;return typeof requestAnimationFrame=="function"&&typeof cancelAnimationFrame=="function"?(x=function(T){var W=Math.random();return M[W]=requestAnimationFrame(function F(Z){G===Z||G+j-1<Z?(G=Z,delete M[W],T()):M[W]=requestAnimationFrame(F)}),W},A=function(T){M[T]&&cancelAnimationFrame(M[T])}):(x=function(T){return setTimeout(T,j)},A=function(T){return clearTimeout(T)}),{frame:x,cancel:A}}(),b=function(){var j,x,A={};function M(G){function T(W,F){G.postMessage({options:W||{},callback:F})}G.init=function(F){var Z=F.transferControlToOffscreen();G.postMessage({canvas:Z},[Z])},G.fire=function(F,Z,de){if(x)return T(F,null),x;var ve=Math.random().toString(36).slice(2);return x=d(function(oe){function R(be){be.data.callback===ve&&(delete A[ve],G.removeEventListener("message",R),x=null,h.clear(),de(),oe())}G.addEventListener("message",R),T(F,ve),A[ve]=R.bind(null,{data:{callback:ve}})}),x},G.reset=function(){G.postMessage({reset:!0});for(var F in A)A[F](),delete A[F]}}return function(){if(j)return j;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{j=new Worker(URL.createObjectURL(new Blob([G])))}catch(T){return typeof console!==void 0&&typeof console.warn=="function"&&console.warn("🎊 Could not load worker",T),null}M(j)}return j}}(),y={particleCount:50,angle:90,spread:45,startVelocity:45,decay:.9,gravity:1,drift:0,ticks:200,x:.5,y:.5,shapes:["square","circle"],zIndex:100,colors:["#26ccff","#a25afd","#ff5e7e","#88ff5a","#fcff42","#ffa62d","#ff36ff"],disableForReducedMotion:!1,scalar:1};function p(j,x){return x?x(j):j}function w(j){return j!=null}function v(j,x,A){return p(j&&w(j[x])?j[x]:y[x],A)}function N(j){return j<0?0:Math.floor(j)}function C(j,x){return Math.floor(Math.random()*(x-j))+j}function B(j){return parseInt(j,16)}function S(j){return j.map(P)}function P(j){var x=String(j).replace(/[^0-9a-f]/gi,"");return x.length<6&&(x=x[0]+x[0]+x[1]+x[1]+x[2]+x[2]),{r:B(x.substring(0,2)),g:B(x.substring(2,4)),b:B(x.substring(4,6))}}function O(j){var x=v(j,"origin",Object);return x.x=v(x,"x",Number),x.y=v(x,"y",Number),x}function z(j){j.width=document.documentElement.clientWidth,j.height=document.documentElement.clientHeight}function $(j){var x=j.getBoundingClientRect();j.width=x.width,j.height=x.height}function se(j){var x=document.createElement("canvas");return x.style.position="fixed",x.style.top="0px",x.style.left="0px",x.style.pointerEvents="none",x.style.zIndex=j,x}function H(j,x,A,M,G,T,W,F,Z){j.save(),j.translate(x,A),j.rotate(T),j.scale(M,G),j.arc(0,0,1,W,F,Z),j.restore()}function K(j){var x=j.angle*(Math.PI/180),A=j.spread*(Math.PI/180);return{x:j.x,y:j.y,wobble:Math.random()*10,wobbleSpeed:Math.min(.11,Math.random()*.1+.05),velocity:j.startVelocity*.5+Math.random()*j.startVelocity,angle2D:-x+(.5*A-Math.random()*A),tiltAngle:(Math.random()*(.75-.25)+.25)*Math.PI,color:j.color,shape:j.shape,tick:0,totalTicks:j.ticks,decay:j.decay,drift:j.drift,random:Math.random()+2,tiltSin:0,tiltCos:0,wobbleX:0,wobbleY:0,gravity:j.gravity*3,ovalScalar:.6,scalar:j.scalar,flat:j.flat}}function te(j,x){x.x+=Math.cos(x.angle2D)*x.velocity+x.drift,x.y+=Math.sin(x.angle2D)*x.velocity+x.gravity,x.velocity*=x.decay,x.flat?(x.wobble=0,x.wobbleX=x.x+10*x.scalar,x.wobbleY=x.y+10*x.scalar,x.tiltSin=0,x.tiltCos=0,x.random=1):(x.wobble+=x.wobbleSpeed,x.wobbleX=x.x+10*x.scalar*Math.cos(x.wobble),x.wobbleY=x.y+10*x.scalar*Math.sin(x.wobble),x.tiltAngle+=.1,x.tiltSin=Math.sin(x.tiltAngle),x.tiltCos=Math.cos(x.tiltAngle),x.random=Math.random()+2);var A=x.tick++/x.totalTicks,M=x.x+x.random*x.tiltCos,G=x.y+x.random*x.tiltSin,T=x.wobbleX+x.random*x.tiltCos,W=x.wobbleY+x.random*x.tiltSin;if(j.fillStyle="rgba("+x.color.r+", "+x.color.g+", "+x.color.b+", "+(1-A)+")",j.beginPath(),l&&x.shape.type==="path"&&typeof x.shape.path=="string"&&Array.isArray(x.shape.matrix))j.fill(he(x.shape.path,x.shape.matrix,x.x,x.y,Math.abs(T-M)*.1,Math.abs(W-G)*.1,Math.PI/10*x.wobble));else if(x.shape.type==="bitmap"){var F=Math.PI/10*x.wobble,Z=Math.abs(T-M)*.1,de=Math.abs(W-G)*.1,ve=x.shape.bitmap.width*x.scalar,oe=x.shape.bitmap.height*x.scalar,R=new DOMMatrix([Math.cos(F)*Z,Math.sin(F)*Z,-Math.sin(F)*de,Math.cos(F)*de,x.x,x.y]);R.multiplySelf(new DOMMatrix(x.shape.matrix));var be=j.createPattern(h.transform(x.shape.bitmap),"no-repeat");be.setTransform(R),j.globalAlpha=1-A,j.fillStyle=be,j.fillRect(x.x-ve/2,x.y-oe/2,ve,oe),j.globalAlpha=1}else if(x.shape==="circle")j.ellipse?j.ellipse(x.x,x.y,Math.abs(T-M)*x.ovalScalar,Math.abs(W-G)*x.ovalScalar,Math.PI/10*x.wobble,0,2*Math.PI):H(j,x.x,x.y,Math.abs(T-M)*x.ovalScalar,Math.abs(W-G)*x.ovalScalar,Math.PI/10*x.wobble,0,2*Math.PI);else if(x.shape==="star")for(var ie=Math.PI/2*3,Ne=4*x.scalar,De=8*x.scalar,I=x.x,le=x.y,Ee=5,Re=Math.PI/Ee;Ee--;)I=x.x+Math.cos(ie)*De,le=x.y+Math.sin(ie)*De,j.lineTo(I,le),ie+=Re,I=x.x+Math.cos(ie)*Ne,le=x.y+Math.sin(ie)*Ne,j.lineTo(I,le),ie+=Re;else j.moveTo(Math.floor(x.x),Math.floor(x.y)),j.lineTo(Math.floor(x.wobbleX),Math.floor(G)),j.lineTo(Math.floor(T),Math.floor(W)),j.lineTo(Math.floor(M),Math.floor(x.wobbleY));return j.closePath(),j.fill(),x.tick<x.totalTicks}function Q(j,x,A,M,G){var T=x.slice(),W=j.getContext("2d"),F,Z,de=d(function(ve){function oe(){F=Z=null,W.clearRect(0,0,M.width,M.height),h.clear(),G(),ve()}function R(){a&&!(M.width===r.width&&M.height===r.height)&&(M.width=j.width=r.width,M.height=j.height=r.height),!M.width&&!M.height&&(A(j),M.width=j.width,M.height=j.height),W.clearRect(0,0,M.width,M.height),T=T.filter(function(be){return te(W,be)}),T.length?F=g.frame(R):oe()}F=g.frame(R),Z=oe});return{addFettis:function(ve){return T=T.concat(ve),de},canvas:j,promise:de,reset:function(){F&&g.cancel(F),Z&&Z()}}}function ne(j,x){var A=!j,M=!!v(x||{},"resize"),G=!1,T=v(x,"disableForReducedMotion",Boolean),W=i&&!!v(x||{},"useWorker"),F=W?b():null,Z=A?z:$,de=j&&F?!!j.__confetti_initialized:!1,ve=typeof matchMedia=="function"&&matchMedia("(prefers-reduced-motion)").matches,oe;function R(ie,Ne,De){for(var I=v(ie,"particleCount",N),le=v(ie,"angle",Number),Ee=v(ie,"spread",Number),Re=v(ie,"startVelocity",Number),Ns=v(ie,"decay",Number),Cs=v(ie,"gravity",Number),ts=v(ie,"drift",Number),rt=v(ie,"colors",S),it=v(ie,"ticks",Number),Pt=v(ie,"shapes"),ss=v(ie,"scalar"),k=!!v(ie,"flat"),ue=O(ie),Me=I,Ce=[],Oe=j.width*ue.x,Fe=j.height*ue.y;Me--;)Ce.push(K({x:Oe,y:Fe,angle:le,spread:Ee,startVelocity:Re,color:rt[Me%rt.length],shape:Pt[C(0,Pt.length)],ticks:it,decay:Ns,gravity:Cs,drift:ts,scalar:ss,flat:k}));return oe?oe.addFettis(Ce):(oe=Q(j,Ce,Z,Ne,De),oe.promise)}function be(ie){var Ne=T||v(ie,"disableForReducedMotion",Boolean),De=v(ie,"zIndex",Number);if(Ne&&ve)return d(function(Re){Re()});A&&oe?j=oe.canvas:A&&!j&&(j=se(De),document.body.appendChild(j)),M&&!de&&Z(j);var I={width:j.width,height:j.height};F&&!de&&F.init(j),de=!0,F&&(j.__confetti_initialized=!0);function le(){if(F){var Re={getBoundingClientRect:function(){if(!A)return j.getBoundingClientRect()}};Z(Re),F.postMessage({resize:{width:Re.width,height:Re.height}});return}I.width=I.height=null}function Ee(){oe=null,M&&(G=!1,s.removeEventListener("resize",le)),A&&j&&(document.body.contains(j)&&document.body.removeChild(j),j=null,de=!1)}return M&&!G&&(G=!0,s.addEventListener("resize",le,!1)),F?F.fire(ie,I,Ee):R(ie,I,Ee)}return be.reset=function(){F&&F.reset(),oe&&oe.reset()},be}var _;function U(){return _||(_=ne(null,{useWorker:!0,resize:!0})),_}function he(j,x,A,M,G,T,W){var F=new Path2D(j),Z=new Path2D;Z.addPath(F,new DOMMatrix(x));var de=new Path2D;return de.addPath(Z,new DOMMatrix([Math.cos(W)*G,Math.sin(W)*G,-Math.sin(W)*T,Math.cos(W)*T,A,M])),de}function ye(j){if(!l)throw new Error("path confetti are not supported in this browser");var x,A;typeof j=="string"?x=j:(x=j.path,A=j.matrix);var M=new Path2D(x),G=document.createElement("canvas"),T=G.getContext("2d");if(!A){for(var W=1e3,F=W,Z=W,de=0,ve=0,oe,R,be=0;be<W;be+=2)for(var ie=0;ie<W;ie+=2)T.isPointInPath(M,be,ie,"nonzero")&&(F=Math.min(F,be),Z=Math.min(Z,ie),de=Math.max(de,be),ve=Math.max(ve,ie));oe=de-F,R=ve-Z;var Ne=10,De=Math.min(Ne/oe,Ne/R);A=[De,0,0,De,-Math.round(oe/2+F)*De,-Math.round(R/2+Z)*De]}return{type:"path",path:x,matrix:A}}function ce(j){var x,A=1,M="#000000",G='"Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji", "EmojiOne Color", "Android Emoji", "Twemoji Mozilla", "system emoji", sans-serif';typeof j=="string"?x=j:(x=j.text,A="scalar"in j?j.scalar:A,G="fontFamily"in j?j.fontFamily:G,M="color"in j?j.color:M);var T=10*A,W=""+T+"px "+G,F=new OffscreenCanvas(T,T),Z=F.getContext("2d");Z.font=W;var de=Z.measureText(x),ve=Math.ceil(de.actualBoundingBoxRight+de.actualBoundingBoxLeft),oe=Math.ceil(de.actualBoundingBoxAscent+de.actualBoundingBoxDescent),R=2,be=de.actualBoundingBoxLeft+R,ie=de.actualBoundingBoxAscent+R;ve+=R+R,oe+=R+R,F=new OffscreenCanvas(ve,oe),Z=F.getContext("2d"),Z.font=W,Z.fillStyle=M,Z.fillText(x,be,ie);var Ne=1/A;return{type:"bitmap",bitmap:F.transferToImageBitmap(),matrix:[Ne,0,0,Ne,-ve*Ne/2,-oe*Ne/2]}}n.exports=function(){return U().apply(this,arguments)},n.exports.reset=function(){U().reset()},n.exports.create=ne,n.exports.shapeFromPath=ye,n.exports.shapeFromText=ce})(function(){return typeof window<"u"?window:typeof self<"u"?self:this||{}}(),Js,!1);const Vr=Js.exports;Js.exports.create;const Hr={particleCount:350,spread:120,origin:{y:.6},angle:90},Kr={TOP_RIGHT:{angle:225,origin:{x:.9,y:0}},BOTTOM_RIGHT:{angle:100,origin:{x:.9,y:.9}}},Dt=e=>{let s=Kr[e];s||(s={});const n={...Hr,...s};Vr(n)},Qr=()=>{const[e]=q.useTheme(),{mutate:s,isPending:n}=Ys(),{mutateAsync:a,isPending:r}=Mn(),i=()=>{a({settings:{theme:e}})},l=()=>{s({ids:["THEME"]},{onSuccess:()=>{Dt("BOTTOM_RIGHT")}})};return t.jsxs("div",{className:"bg-white py-3 flex items-center justify-center gap-x-3 border-t",children:[t.jsx(o.Button,{size:"sm",variant:"outline",disabled:n||r,onClick:i,children:"Save draft"}),t.jsx(o.Button,{size:"sm",disabled:n||r,onClick:l,children:"Publish"})]})},Wr=({page:e,onClose:s})=>{const[n,a]=f.useState(e.slug||""),{mutate:r,isPending:i}=$r(),{data:l}=Pe(),c=m.find(l,{key:e==null?void 0:e.pageType}),u=h=>{if(h.preventDefault(),!(e!=null&&e.primaryPage)&&Object.keys(ke).some(y=>n===`/${y}`||m.startsWith(n,`/${y}/`))){V.toast.error("Error",{description:"Slugs cannot start with a language code for primary page"});return}r({...e,slug:n},{onSuccess:s})},d=(e==null?void 0:e.lang)||"";return t.jsx(o.Dialog,{open:!!e,onOpenChange:s,children:t.jsxs(o.DialogContent,{children:[t.jsxs(o.DialogHeader,{children:[t.jsx(o.DialogTitle,{children:"Change Slug"}),t.jsx(o.DialogDescription,{className:"text-xs",children:t.jsxs(o.Alert,{variant:"destructive",className:"mt-2",children:[t.jsx(E.AlertCircle,{className:"h-4 w-4"}),"Changing the slug may have impact on your SEO. Please proceed with caution."]})})]}),t.jsxs("form",{onSubmit:u,children:[t.jsxs("div",{className:"space-y-4 py-4 text-sm ",children:[t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{children:[t.jsx("span",{children:"Type:"}),t.jsxs("span",{className:"font-medium text-gray-600",children:[" ",(c==null?void 0:c.name)||(e==null?void 0:e.pageType)]})]}),t.jsxs("div",{children:[t.jsx("span",{children:"Name:"}),t.jsxs("span",{className:"font-medium text-gray-600",children:[" ",e.name]})]})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsxs(o.Label,{htmlFor:"slug",className:"text-right",children:["Slug"," ",t.jsxs("small",{className:"font-light text-gray-500",children:["Slug should start with /",d]})]}),t.jsx(o.Input,{id:"slug",value:n,onChange:h=>{const g=h.target.value;m.startsWith(g,`/${d}`)&&a(g)},className:"col-span-3",required:!0,pattern:"^/.*",title:"Slug must start with /",placeholder:"Enter page slug"})]})]}),t.jsx(o.DialogFooter,{children:t.jsx(o.Button,{type:"submit",disabled:i||!m.startsWith(n,`/${d}`)||m.isEqual(e==null?void 0:e.slug,n),children:i?"Changing...":"Change Slug"})})]})]})})};function Xs({page:e,onClose:s}){const[,n]=_e(),{mutate:a,isPending:r}=Ur(),{data:i}=Pe(),{setSelectedLang:l,fallbackLang:c}=q.useLanguages(),[,u]=q.useSidebarActivePanel(),d=()=>{r||a(e,{onSuccess:()=>{e!=null&&e.primaryPage?(window.history.replaceState({},"",`/?page=${e.primaryPage}`),n(new URLSearchParams({page:e.primaryPage}))):(window.history.replaceState({},"","/"),n(new URLSearchParams)),window.dispatchEvent(new PopStateEvent("popstate")),l(c),u("outline"),s()}})},h=i==null?void 0:i.find(g=>g.key===(e==null?void 0:e.pageType));return t.jsx(o.Dialog,{open:!!e,onOpenChange:s,children:t.jsxs(o.DialogContent,{children:[t.jsxs(o.DialogHeader,{children:[t.jsx(o.DialogTitle,{children:"Confirm Deletion"}),t.jsxs(o.DialogDescription,{className:"py-4 text-slate-500",children:[t.jsxs("div",{children:["Are you sure you want to remove ",t.jsx("b",{children:(e==null?void 0:e.name)??(e==null?void 0:e.slug)})," ",h!=null&&h.hasSlug?(h==null?void 0:h.name)+"?":`page? ${e!=null&&e.primaryPage?"":"This will also delete all associated language pages."}`]}),e.lang&&t.jsxs("div",{className:"py-2 text-sm",children:["Language:"," ",t.jsx("span",{className:"font-medium text-gray-500",children:m.get(ke,e.lang,e.lang)})]})]})]}),t.jsxs(o.DialogFooter,{children:[t.jsx(o.Button,{variant:"outline",onClick:s,children:"Cancel"}),t.jsx(o.Button,{variant:"destructive",disabled:r,onClick:d,children:r?"Deleting...":"Delete"})]})]})})}const Ge=({permission:e,permissions:s,children:n,fallback:a=null})=>{const{hasPermission:r}=q.usePermissions();return e&&!r(e)||s&&!s.some(i=>r(i))?a:n},bs=({page:e,onClose:s})=>{const{mutate:n,isPending:a}=Fr(),r=async()=>{n(e,{onSuccess:s})};return t.jsx(o.Dialog,{open:!!e,onOpenChange:s,children:t.jsxs(o.DialogContent,{children:[t.jsxs(o.DialogHeader,{children:[t.jsx(o.DialogTitle,{children:"Confirm action"}),t.jsxs(o.DialogDescription,{children:[ae.UNPUBLISH_MSG," ",t.jsx("b",{children:(e==null?void 0:e.name)??(e==null?void 0:e.slug)}),"?"]})]}),t.jsxs(o.DialogFooter,{children:[t.jsx(o.Button,{variant:"outline",onClick:s,children:"Cancel"}),t.jsx(o.Button,{variant:"destructive",disabled:a,onClick:r,children:a?ae.UPDATING:ae.UNPUBLISH})]})]})})},Yr=e=>{if(!e)return{base:e,extension:null};const s=e.lastIndexOf(".");if(s<=0)return{base:e,extension:null};const n=e.substring(s);return{base:e.substring(0,s),extension:n}},Ve=e=>{if(!e)return e;const{base:s}=Yr(e);return s},Jr=e=>e&&Ve(e),hn=(e,s)=>{const n=Ve(e||"");return!n||n==="/"?`/${s}`:`${n}/${s}`};function Zs({value:e,onChange:s,placeholder:n,parentSlug:a,onValidationChange:r,disabled:i=!1,fullSlug:l}){const[c,u]=f.useState(e),[d,h]=f.useState(null);f.useEffect(()=>{u(e)},[e]);const g=b=>{const p=b.target.value.replace(/\//g,"").replace(/\s+/g,"-").replace(/[^a-zA-Z0-9-_.]/g,"-").replace(/-+/g,"-").replace(/^-+/,"").toLowerCase(),w=(p.match(/\./g)||[]).length,v=w<=1;w>1?h("Invalid slug. Only one dot (.) is allowed in the slug"):h(null),r&&r(v),u(p),s(p)};return t.jsxs("div",{children:[a&&t.jsx("div",{className:"flex items-center mb-1",children:t.jsxs("span",{className:"text-xs text-gray-500",children:["Parent:"," ",t.jsx("span",{className:"font-mono text-gray-900",children:Jr(a)})]})}),t.jsxs("div",{className:"relative",children:[t.jsx(o.Input,{disabled:i,value:c,onChange:g,placeholder:n,className:d?"border-red-500":""}),d&&t.jsx("div",{className:"text-red-500 text-xs mt-1",children:d})]}),l&&t.jsx("div",{className:"flex items-center mt-1",children:t.jsxs("span",{className:"text-xs text-gray-500",children:["Complete Slug:"," ",t.jsx("span",{className:"font-mono text-gray-900",children:l})]})})]})}const Kn=({langProps:e,onClose:s,languages:n})=>{const{data:a}=Te(),r=a==null?void 0:a.dynamic,{data:i}=Pe(),[l,c]=f.useState(e.name||""),[u,d]=f.useState(e.edit?e.lang:""),[h,g]=f.useState(e.edit?e.slug:""),[b,y]=f.useState(!0),[p,w]=f.useState(!0),{mutate:v,isPending:N}=Hn(),{mutate:C,isPending:B}=Ws(),{data:S}=Ke(a==null?void 0:a.parent),{setSelectedLang:P,fallbackLang:O}=q.useLanguages(),[,z]=_e(),[,$]=q.useSidebarActivePanel(),se=f.useMemo(()=>i==null?void 0:i.find(j=>j.key===e.pageType),[i,e.pageType]),H=r||!(se!=null&&se.hasSlug),K=(a==null?void 0:a.slug)==="/",te=N||B,{parentSlug:Q,isRootPage:ne}=f.useMemo(()=>{if(K||!u)return{parentSlug:void 0,isRootPage:!(a!=null&&a.parent)};if(!(a!=null&&a.parent))return{parentSlug:p?`/${u}`:void 0,isRootPage:!(a!=null&&a.parent)};const j=S==null?void 0:S.find(x=>x.lang===u);return{parentSlug:j==null?void 0:j.slug,isRootPage:!1}},[a==null?void 0:a.parent,S,p,u,K]);f.useEffect(()=>{if(!e.edit)return;const x=(e.slug||"").split("/").filter(Boolean);let A="";const M=G=>w(G);if(K){const G=x.pop()||"";if(ke[G])M(!0);else{A=G;const T=x.pop()||"";M(!!ke[T])}}else if(ne){if(x.length){A=x.pop()||"";const G=x.pop()||"";M(!!ke[G])}}else x.length&&(A=x.pop()||"");g(A)},[e,K,ne]);const _=f.useMemo(()=>ne?!0:!!(S!=null&&S.find(j=>(j==null?void 0:j.lang)===u)),[u,S,ne]),U=()=>{let j="";return ne?j=`/${p?[u,h].filter(Boolean).join("/"):h}`:j=`${Ve(Q)}/${h}`,j.replace(/\/{2,}/g,"/").replace(/\/$/,"")},he=(j,x)=>{const A=new URLSearchParams(window.location.search);x&&j===x?A.delete("lang"):A.set("lang",j);const M=A.toString(),G=`${window.location.pathname}${M?`?${M}`:""}`;window.history.pushState({},"",G),z(A),window.dispatchEvent(new PopStateEvent("popstate"))},ye=j=>{j.preventDefault();const x={name:l,lang:u,primaryPage:a==null?void 0:a.id,slug:U(),pageType:a==null?void 0:a.pageType,tracking:{}};x.pageType=e.pageType,e.edit&&(x.id=e==null?void 0:e.id),e.edit?C(x,{onSuccess:s}):v(x,{onSuccess:()=>{u&&(P(u),he(u,O)),$("outline"),s()}})},ce=te||m.isEmpty(l)||m.isEmpty(u)||(H||K&&p?!1:!b||m.isEmpty(h));return t.jsx(o.Dialog,{open:!!e,onOpenChange:s,children:t.jsxs(o.DialogContent,{className:"sm:max-w-[425px] text-slate-600",children:[t.jsxs(o.DialogHeader,{children:[t.jsx(o.DialogTitle,{children:e.edit?ae.EDIT_LANGUAGE:ae.ADD_NEW_LANGUAGE}),t.jsx(o.DialogDescription,{className:"font-light",children:ae.ENTER_LANGUAGE_DETAILS})]}),t.jsxs("form",{onSubmit:ye,children:[t.jsxs("div",{className:"grid gap-4 py-4",children:[t.jsxs("div",{className:"space-y-1",children:[t.jsx(o.Label,{htmlFor:"lang",className:"text-right",children:ae.LANGUAGE}),t.jsxs("select",{value:u,disabled:e.edit||m.isEmpty(n),onChange:j=>{const x=j.target.value;d(x),!e.edit&&m.startsWith(l,e.name)&&c(`${e.name} - ${ke[x]}`)},className:"flex h-9 w-full rounded-md border border-border bg-background px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 col-span-3",children:[t.jsx("option",{value:"",disabled:!0,selected:!0,children:e.edit?m.get(ke,e.lang,e.lang):m.isEmpty(n)?ae.ALL_AVAILABLE_LANGUAGE_PAGE:ae.CHOOSE_LANGUAGE}),m.map(n,j=>t.jsx("option",{value:j,children:m.get(ke,j,j)},j))]})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsx(o.Label,{htmlFor:"slug",className:"text-right",children:ae.PAGE_NAME}),t.jsx(o.Input,{id:"name",value:u?l:"",onChange:j=>c(j.target.value),className:"col-span-3",required:!0,placeholder:u?ae.ENTER_PAGE_NAME:ae.CHOOSE_LANGUAGE_TO_ADD_SLUG,disabled:!_||!u})]}),!H&&t.jsx(t.Fragment,{children:t.jsxs("div",{className:"space-y-1",children:[ne&&u&&t.jsxs("div",{className:"flex items-center space-x-2 pb-1",children:[t.jsx("input",{type:"checkbox",id:"useLanguagePrefix",checked:p,onChange:j=>w(j.target.checked),className:"rounded border-gray-300"}),t.jsxs(o.Label,{htmlFor:"useLanguagePrefix",className:"text-sm font-normal leading-tight",children:["Add language code (",t.jsxs("span",{className:"font-mono text-gray-900",children:["/",u]}),") as slug prefix"]})]}),t.jsxs(o.Label,{htmlFor:"slug",className:"text-right",children:[ae.SLUG," "]}),t.jsx(Zs,{disabled:m.isEmpty(u)||!_,value:h,onChange:g,placeholder:m.isEmpty(u)?ae.CHOOSE_LANGUAGE_TO_ADD_SLUG:K&&p?"Leave empty for home page":ae.ENTER_PAGE_SLUG,parentSlug:Q,onValidationChange:y,fullSlug:ce?"":U()})]})}),r&&u&&_&&t.jsxs("p",{className:"text-sm pb-2",children:[t.jsx(o.Label,{children:"Dynamic Slug: "})," ",t.jsx("span",{className:"font-mono font-light",children:`${Ve(Q)}/${se==null?void 0:se.dynamicSlug}`})]})]}),t.jsx(o.DialogFooter,{children:_?t.jsx(o.Button,{type:"submit",disabled:ce,children:te?e.edit?ae.UPDATING:ae.ADDING:e.edit?ae.UPDATE:ae.ADD_NEW_LANGUAGE}):u&&t.jsx(o.Alert,{variant:"destructive",children:t.jsxs("p",{className:"text-center w-5/6 mx-auto",children:["You need to create the ",t.jsx("span",{className:"font-medium",children:ke[u]})," page in the parent to add here."]})})})]})]})})},Xr=()=>{const[e,s]=f.useState(null),{selectedLang:n,fallbackLang:a,setSelectedLang:r}=q.useLanguages(),{data:i,isFetching:l}=Ke(),{data:c}=Te(),{data:u}=Pe(),d=f.useMemo(()=>{const C=u==null?void 0:u.find(B=>B.key===(c==null?void 0:c.pageType));return C==null?void 0:C.dynamicSlug},[u,c==null?void 0:c.pageType]),[h,g]=f.useState(null),[b,y]=f.useState(null),[p,w]=f.useState(null),{data:v}=Ze(),N=m.filter(m.get(v,"languages")||["en"],C=>!m.find(i,{lang:C})&&C!==m.get(v,"fallbackLang"));return t.jsxs("div",{className:"space-y-4",children:[t.jsx("ul",{className:"space-y-2",children:l?t.jsxs("div",{className:"w-full space-y-3 py-4",children:[t.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"}),t.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"}),t.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"})]}):m.map(i,C=>{const B=C.lang,S=C.slug,P=!C.primaryPage,O=B===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 ${O?"bg-gray-200":"hover:bg-gray-100"}`,onClick:()=>r(B),children:[t.jsxs("div",{className:" flex-1 gap-x-3",children:[t.jsxs("div",{className:"text-[13px] text-slate-800 flex items-center gap-x-2",children:[t.jsx("div",{className:`w-2.5 h-2.5 rounded-full ${C.online?"bg-green-300":"bg-gray-300"}`}),m.get(ke,P?a:B,B)]}),t.jsxs("div",{children:[S&&t.jsxs("div",{className:"text-[11px] text-slate-600 font-light",children:["Slug: ",t.jsx("b",{className:"font-medium font-mono",children:d?`${S}/${d}`:S})]}),t.jsxs("div",{className:"text-[11px] text-slate-600 font-light",children:["Name:",t.jsxs("b",{className:"font-medium",children:[" ",C.name," "]})]})]})]}),P?t.jsxs("div",{className:"flex items-center text-[11px] text-orange-500 gap-x-1",children:[t.jsx(E.StarIcon,{fill:"orange",className:"w-3 h-3"}),t.jsx("b",{children:" Primary"})]}):t.jsx("div",{className:"flex items-center gap-x-3",children:t.jsx(Ge,{permissions:[je.EDIT_PAGE,je.DELETE_PAGE,je.UNPUBLISH_PAGE],children:t.jsxs(o.DropdownMenu,{children:[t.jsx(o.DropdownMenuTrigger,{asChild:!0,onClick:z=>z.stopPropagation(),children:t.jsx(o.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",children:t.jsx(E.MoreHorizontal,{className:"h-4 w-4"})})}),t.jsxs(o.DropdownMenuContent,{align:"end",className:"text-sm z-[9999]",children:[t.jsx(Ge,{permissions:[je.EDIT_PAGE],children:t.jsxs(o.DropdownMenuItem,{className:"flex items-center gap-2 cursor-pointer",onClick:z=>{z.stopPropagation(),s({...C,edit:!0})},children:[t.jsx(E.PencilIcon,{className:"size-3"}),ae.EDIT]})}),t.jsx(Ge,{permissions:[je.UNPUBLISH_PAGE],children:(C==null?void 0:C.online)&&t.jsxs(o.DropdownMenuItem,{className:"flex items-center gap-2 cursor-pointer",onClick:z=>{z.stopPropagation(),y(C)},children:[t.jsx(E.Power,{className:"size-3"}),ae.UNPUBLISH]})}),t.jsx(Ge,{permissions:[je.DELETE_PAGE],children:t.jsxs(o.DropdownMenuItem,{className:"flex items-center gap-2 cursor-pointer",onClick:z=>{z.stopPropagation(),g(C)},children:[t.jsx(E.TrashIcon,{className:"size-3"}),ae.DELETE]})})]})]})})})]},C.id),t.jsx("div",{className:"h-1 w-full border-b"})]})})}),t.jsx(Ge,{permissions:[je.ADD_PAGE],children:t.jsx("div",{className:"flex justify-center w-full",children:t.jsx(o.Button,{variant:"default",size:"sm",disabled:m.isEmpty(N),onClick:()=>{s({name:c==null?void 0:c.name,pageType:c==null?void 0:c.pageType,lang:"",slug:"",edit:!1})},children:ae.ADD_NEW_LANGUAGE})})}),e&&t.jsx(Kn,{languages:N,langProps:e,onClose:()=>s(null)}),h&&t.jsx(Xs,{page:h,onClose:()=>g(null)}),b&&t.jsx(bs,{page:b,onClose:()=>y(null)}),p&&t.jsx(Wr,{page:p,onClose:()=>w(null)})]})};function Zr({value:e,onChange:s,placeholder:n="Enter custom slug part",dynamicPattern:a,onValidationChange:r}){const[i,l]=f.useState(null),c=f.useRef(null),[u,d]=f.useState(a+e);f.useEffect(()=>{d(a+e)},[e,a]);const h=y=>{const p=y.target.value;if(!p.startsWith(a)){const S=p.replace(a,""),P=a+S;d(P),s(S);return}const v=p.substring(a.length).replace(/\//g,"").replace(/\s+/g,"-").replace(/[^a-zA-Z0-9-_.]/g,"-").replace(/-+/g,"-").replace(/^-+/,"").toLowerCase(),N=(v.match(/\./g)||[]).length,C=N<=1;N>1?l("Invalid slug. Only one dot (.) is allowed in the slug"):l(null),r&&r(C);const B=a+v;d(B),s(v)},g=()=>{if(c.current){const y=c.current;setTimeout(()=>{const p=a.length;y.setSelectionRange(p,p)},0)}},b=y=>{const p=y.currentTarget;(p.selectionStart||0)<=a.length&&setTimeout(()=>{const v=a.length;p.setSelectionRange(v,v)},0)};return t.jsx("div",{children:t.jsxs("div",{className:"relative",children:[t.jsxs("p",{className:"text-gray-500 text-xs mb-2",children:[`${a}`," is a dynamic segment of slug"]}),t.jsx(o.Input,{ref:c,value:u,onChange:h,onFocus:g,onClick:b,placeholder:n,className:i?"border-red-500":""}),i&&t.jsx("div",{className:"text-red-500 text-xs mt-1",children:i})]})})}const cs=({children:e,onWheel:s,...n})=>{const a=r=>{try{r.preventDefault();const i=r.currentTarget;i.scrollTop+=r.deltaY}catch{r.preventDefault()}s&&s(r)};return t.jsx(o.CommandList,{...n,onWheel:a,children:e})},Ts=(...e)=>e.filter(Boolean).join(" ");function ei({pages:e,selectedParentId:s,onChange:n,className:a,id:r="parentPage"}){const[i,l]=f.useState(!1),[c,u]=f.useState(""),d=f.useMemo(()=>!e||e.length===0?[]:e.filter(v=>!m.isEmpty(v.slug)).filter(v=>v.slug!=="/").sort((v,N)=>v.slug.localeCompare(N.slug)),[e]),h=f.useMemo(()=>{if(!c.trim())return d;const w=c.toLowerCase();return d.filter(v=>v.name.toLowerCase().includes(w)||v.slug.toLowerCase().includes(w))},[d,c]),g=w=>Math.max(0,(w.match(/\//g)||[]).length-1),b=w=>" ".repeat(w),y=w=>{if(w==="/")return"/";const v=w.split("/").filter(Boolean);if(v.length<=1){const N=v[0]||"";return`/${Ve(N)}`}return`/${Ve(v[v.length-1])}`},p=()=>{if(!s||s==="none")return"None";const w=d.find(v=>v.id===s);return w?`${w.name} (${y(w.slug)})`:"None"};return t.jsxs("div",{className:"space-y-0.5",children:[t.jsx(o.Label,{htmlFor:r,className:"text-sm",children:"Parent"}),t.jsxs(o.Popover,{open:i,onOpenChange:l,children:[t.jsx(o.PopoverTrigger,{asChild:!0,children:t.jsxs(o.Button,{id:r,variant:"outline",role:"combobox",className:Ts("w-full justify-between",a),"data-testid":"parent-page-selector",children:[p(),t.jsx(E.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),t.jsx(o.PopoverContent,{className:"w-[var(--radix-popover-trigger-width)] p-0",align:"start",children:t.jsxs(o.Command,{shouldFilter:!1,children:[t.jsx("div",{className:"relative border-none py-2",children:t.jsx("div",{className:"sticky top-0 z-10 bg-white px-3 py-2",children:t.jsxs("div",{className:"relative",children:[t.jsx(E.Search,{strokeWidth:2,className:"absolute left-2 top-2 h-4 w-4 text-gray-400"}),t.jsx(o.Input,{placeholder:"Search pages...",className:"h-8 pl-8 text-xs",value:c,onChange:w=>u(w.target.value)})]})})}),t.jsxs(cs,{className:"max-h-[300px] overflow-y-auto",children:[t.jsx(o.CommandEmpty,{children:"No pages found."}),t.jsxs(o.CommandGroup,{children:[t.jsxs(o.CommandItem,{value:"none",onSelect:()=>{n(""),l(!1),u("")},className:"flex cursor-pointer items-center justify-between",children:[t.jsx("span",{children:"None"}),t.jsx(E.Check,{className:Ts("mr-2 h-4 w-4",s?"opacity-0":"opacity-100")})]}),h.map(w=>{const v=b(g(w.slug)),N=y(w.slug),C=t.jsxs("span",{className:"flex items-center text-sm",children:[v,w.name,t.jsxs("span",{className:"text-xs text-gray-500",children:[" (",N,")"]})]});return t.jsxs(o.CommandItem,{value:w.id,onSelect:()=>{n(w.id),l(!1),u("")},className:"flex cursor-pointer items-center justify-between whitespace-pre-wrap",children:[t.jsx("span",{children:C}),t.jsx(E.Check,{className:Ts("mr-2 h-4 w-4 shrink-0",s===w.id?"opacity-100":"opacity-0")})]},w.id)})]})]})]})})]})]})}const ti=(...e)=>e.filter(Boolean).join(" "),si=({templates:e,selectedTemplateId:s,onSelectTemplate:n,isLoading:a=!1})=>{const[r,i]=f.useState(""),[l,c]=f.useState(!1),[u,d]=f.useState("");if(f.useEffect(()=>{if(s){const p=e.find(w=>w.id===s);i((p==null?void 0:p.preview)||"")}else i("")},[s,e]),a)return t.jsx("div",{className:"flex h-fit items-center justify-center text-sm text-gray-500",children:"Loading templates..."});if(e.length===0)return null;const h={};e.forEach(p=>{const w=p.libraryName;h[w]||(h[w]=[]),h[w].push(p)});const g=Object.entries(h).reduce((p,[w,v])=>{const N=v.filter(C=>C.name.toLowerCase().includes(u.toLowerCase())||w.toLowerCase().includes(u.toLowerCase()));return N.length>0&&(p[w]=N),p},{}),b=e.find(p=>p.id===s),y=b?m.startCase(b.name):"No Template";return t.jsxs("div",{className:"space-y-4",children:[t.jsxs(o.Popover,{open:l,onOpenChange:c,children:[t.jsx(o.PopoverTrigger,{asChild:!0,children:t.jsxs(o.Button,{variant:"outline",role:"combobox",className:"w-full justify-between",children:[y,t.jsx(E.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),t.jsx(o.PopoverContent,{className:"w-[var(--radix-popover-trigger-width)] p-0",align:"start",children:t.jsxs(o.Command,{shouldFilter:!1,children:[t.jsx("div",{className:"sticky top-0 z-10 bg-white px-3 py-2",children:t.jsxs("div",{className:"relative",children:[t.jsx(E.Search,{strokeWidth:2,className:"absolute left-2 top-2 h-4 w-4 text-gray-400"}),t.jsx(o.Input,{placeholder:"Search templates...",className:"h-8 pl-8 text-xs",value:u,onChange:p=>d(p.target.value)})]})}),t.jsxs(cs,{className:"max-h-[300px] overflow-y-auto",children:[t.jsx(o.CommandEmpty,{children:"No templates found."}),Object.entries(g).map(([p,w])=>t.jsx(o.CommandGroup,{heading:p,children:w.map(v=>t.jsxs(o.CommandItem,{value:v.id,onSelect:()=>{n(v.id),c(!1),d("")},className:"flex cursor-pointer items-center justify-between",children:[m.startCase(v.name),t.jsx(E.Check,{className:ti("mr-2 h-4 w-4",s===v.id?"opacity-100":"opacity-0")})]},v.id))},p))]})]})})]}),r&&t.jsxs("div",{className:"mt-3 overflow-hidden rounded border",children:[t.jsx("div",{className:"max-h-[200px] overflow-auto",children:t.jsx("img",{src:r,alt:"Template Preview",className:"w-full object-contain"})}),t.jsx("div",{className:"border-t bg-gray-50 p-2 text-xs text-gray-500",children:"Template preview"})]})]})},ni=()=>{const e=re(),s=J();return D.useQuery({queryKey:[Y,L.GET_LIBRARIES],queryFn:async()=>await s(e,{action:L.GET_LIBRARIES})||[]})},ai=e=>{const s=re(),n=J();return D.useQuery({queryKey:[Y,L.GET_TEMPLATES_BY_TYPE,e],enabled:!!e,queryFn:async()=>{const a=await n(s,{action:L.GET_TEMPLATES_BY_TYPE,data:{pageType:e}});return(e?m.filter(a,{pageType:e}):a)||[]}})},ri=e=>{const{data:s=[],isLoading:n}=ai(e),{data:a=[],isLoading:r}=ni(),i=f.useMemo(()=>n||r?[]:s.map(c=>{const u=m.find(a,{id:c.library});return{...c,libraryName:(u==null?void 0:u.type)!=="shared"?"Site Library":(u==null?void 0:u.name)+" Library",libraryType:u==null?void 0:u.type}}),[s,a,n,r]),l=f.useMemo(()=>m.groupBy(i,"libraryName"),[i]);return{data:i,groupedData:l,isLoading:n||r}},en=()=>{const[,e]=_e();return f.useCallback((s,n)=>{const r=new URLSearchParams(window.location.search).get("lang"),i=new URLSearchParams({page:s});r&&i.set("lang",r),window.history.pushState({},"",`?${i.toString()}`),e(i),window.dispatchEvent(new PopStateEvent("popstate")),n==null||n()},[e])},us=(e,s)=>{const n={seo:{keyword:"",title:"",description:"",noIndex:!1,noFollow:!1,canonicalUrl:"",ogTitle:"",ogDescription:"",jsonLD:""},jsonLD:{}};e!=null&&e.defaultSeo&&(m.has(e.defaultSeo,s)&&m.isObject(e.defaultSeo[s])?n.seo={...n.seo,...e.defaultSeo[s]}:n.seo={...n.seo,...e.defaultSeo});let a={};return e!=null&&e.defaultJSONLD&&(m.has(e.defaultJSONLD,s)&&m.isObject(e.defaultJSONLD[s])?(a=e.defaultJSONLD[s],m.set(n,"seo.jsonLD",JSON.stringify(a))):(a=e.defaultJSONLD,m.set(n,"seo.jsonLD",JSON.stringify(a)))),{seo:n.seo,jsonLD:a}},tt=(...e)=>e.filter(Boolean).join(" ");function ii({addEditPage:e,additionalPageTypes:s=[],close:n,closePanel:a}){var Pt,ss;const r=en(),i=!!(e!=null&&e.id),{data:l}=Zt(),{mutate:c,isPending:u}=Hn(),{mutate:d,isPending:h}=Ws(),[g,b]=f.useState(null),[y,p]=f.useState(!0),[w,v]=f.useState((e==null?void 0:e.pageType)??"page"),{hasPermission:N}=q.usePermissions(),C=N(je.CHANGE_PAGE_TYPE),[B,S]=f.useState(!1),[P,O]=f.useState(""),{selectedLang:z,fallbackLang:$}=q.useLanguages(),se=z||$,[H,K]=f.useState(""),[te,Q]=f.useState(!1),ne=f.useMemo(()=>{const k=s.find(ue=>ue.key===w);return(k==null?void 0:k.hasSlug)===!1},[w,s]),[_,U]=f.useState((e==null?void 0:e.parent)??""),[he,ye]=f.useState((e==null?void 0:e.name)??""),[ce,j]=f.useState((e==null?void 0:e.dynamic)??!1),[x,A]=f.useState(ce?"":((e==null?void 0:e.slug)??"").split("/").pop()||""),[M,G]=f.useState((e==null?void 0:e.dynamicSlugCustom)??""),[T,W]=f.useState(!0),[F,Z]=f.useState(""),{data:de,isLoading:ve}=ri(w),oe=u||h,R=s.find(k=>k.key===w),be=k=>{if(i&&w!==k){O(k),S(!0),K(""),Q(!1);return}v(k),K(""),Q(!1)},ie=()=>{v(P),S(!1),j(!1)},Ne=k=>{j(k),k?A(""):G("")},De=k=>{if(U(k),k&&k!=="none"){const ue=l==null?void 0:l.find(Ce=>Ce.id===k),Me=(ue==null?void 0:ue.slug)||"";if(x.startsWith(Me)){const Ce=x.slice(Me.length).replace(/^\/+/,"");A(Ce)}else A(x.replace(/^\/+/,""))}else A(x?`${x}`:"")},I=k=>{Z(k)},le=()=>he.trim()?ce&&!m.isEmpty(x)?(b("Slug must be empty when using dynamic slug"),!1):ce&&!T?(b("Dynamic slug is invalid"),!1):!0:(V.toast.error("Name is required"),!1),Ee=()=>{const k={pageType:R==null?void 0:R.key,name:he,slug:"",hasSlug:!1};i?d({id:e==null?void 0:e.id,name:he},{onSuccess:()=>{V.toast.success((R==null?void 0:R.name)+" updated successfully"),n()}}):c(k,{onSuccess:ue=>{n(),r(ue.page.id,a)}})},Re=(k,ue)=>{if(!k.trim()&&!ce)return b("Child page slug is required"),!1;const Me=Ve(ue),Ce=hn(Me,k);return Object.keys(ke).some(ns=>Ce===`/${ns}`||(Ce==null?void 0:Ce.startsWith(`/${ns}/`)))?(b("Slugs cannot start with a language code for primary page"),!1):!0},Ns=(k,ue)=>{const Me=Ve(ue),Ce=hn(Me,k),Oe={pageType:w,name:he,slug:Ce.replace(/\/$/,""),parent:_,dynamic:ce,hasSlug:!0,template:F||void 0,tracking:{},seo:{},jsonLD:{}};if(ce&&(Oe.dynamicSlugCustom=M),i)d({id:e==null?void 0:e.id,...Oe},{onSuccess:()=>{V.toast.success("Page updated successfully"),n()}});else{const Fe=m.find(s,{key:w});Fe!=null&&Fe.trackingDefault&&(Oe.tracking=Fe.trackingDefault);const{seo:ns,jsonLD:Ja}=us(Fe,se);m.set(Oe,"seo",ns),m.set(Oe,"jsonLD",Ja),c(Oe,{onSuccess:Xa=>{n(),r(Xa.page.id,a)}})}},Cs=()=>{const k={pageType:w,name:he,slug:x===""?"/":`/${x.replace(/\/$/,"")}`,template:F||void 0,parent:null,tracking:{}};if(i)d({id:e==null?void 0:e.id,...k},{onSuccess:()=>{V.toast.success("Page updated successfully"),n()}});else{const ue=m.find(s,{key:w});ue!=null&&ue.trackingDefault&&(k.tracking=ue.trackingDefault);const{seo:Me,jsonLD:Ce}=us(ue,se);m.set(k,"seo",Me),m.set(k,"jsonLD",Ce),c(k,{onSuccess:Oe=>{var Fe;(Fe=Oe==null?void 0:Oe.page)!=null&&Fe.id&&r(Oe.page.id,a),n()}})}},ts=k=>{if(k.preventDefault(),b(null),!!le()){if(!(R!=null&&R.hasSlug)){Ee();return}if(_&&_!=="none"){const ue=l==null?void 0:l.find(Ce=>Ce.id===_),Me=(ue==null?void 0:ue.slug)||"";if(!Re(x,Me))return;Ns(x,Me)}else Cs()}},{pagesType:rt,partialsType:it}=f.useMemo(()=>{const k=ue=>H?ue.name.toLowerCase().includes(H.toLowerCase())||ue.key.toLowerCase().includes(H.toLowerCase()):!0;return{pagesType:s.filter(ue=>ue.hasSlug!==!1&&k(ue)),partialsType:s.filter(ue=>ue.hasSlug===!1&&k(ue))}},[s,H]);return i&&!(R!=null&&R.hasSlug)?t.jsxs("form",{onSubmit:ts,className:"mx-auto w-full max-w-md space-y-4",children:[t.jsxs("div",{className:"space-y-0.5",children:[t.jsx(o.Label,{htmlFor:"pageType",className:"text-sm",children:"Type"}),t.jsxs(o.Popover,{open:te,onOpenChange:Q,children:[t.jsx(o.PopoverTrigger,{asChild:!0,children:t.jsxs(o.Button,{variant:"outline",role:"combobox",disabled:i&&!C,className:tt("w-full justify-between",i&&!C?"cursor-not-allowed text-gray-500":""),children:[(R==null?void 0:R.name)||"Select page type",t.jsx(E.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),t.jsx(o.PopoverContent,{className:"w-[var(--radix-popover-trigger-width)] p-0",align:"start",children:t.jsxs(o.Command,{shouldFilter:!1,children:[t.jsx("div",{className:"sticky top-0 z-10 bg-white px-3 py-2",children:t.jsxs("div",{className:"relative",children:[t.jsx(E.Search,{strokeWidth:2,className:"absolute left-2 top-2 h-4 w-4 text-gray-400"}),t.jsx(o.Input,{placeholder:"Search page types...",className:"h-8 pl-8 text-xs",value:H,onChange:k=>K(k.target.value)})]})}),t.jsxs(cs,{className:"max-h-[200px] overflow-y-auto",children:[t.jsx(o.CommandEmpty,{children:"No page type found."}),t.jsx(o.CommandGroup,{heading:"Partials",children:it.map(k=>t.jsxs(o.CommandItem,{value:k.key,onSelect:()=>{be(k.key),Q(!1)},className:"flex cursor-pointer items-center justify-between",children:[k.name,t.jsx(E.Check,{className:tt("mr-2 h-4 w-4",w===k.key?"opacity-100":"opacity-0")})]},k.key))})]})]})})]}),B&&t.jsxs("div",{className:"mt-2 rounded-md border border-yellow-200 bg-yellow-50 p-3",children:[t.jsx("p",{className:"text-sm text-yellow-800",children:"Changing the page type may impact the page data. Are you sure you want to proceed?"}),t.jsxs("div",{className:"mt-2 flex gap-2",children:[t.jsx(o.Button,{variant:"outline",size:"sm",onClick:()=>S(!1),children:"Cancel"}),t.jsx(o.Button,{variant:"default",size:"sm",onClick:ie,children:"Confirm"})]})]}),t.jsx("p",{className:"text-xs text-gray-500",children:(Pt=s.find(k=>k.key===w))==null?void 0:Pt.helpText})]}),t.jsxs("div",{className:"space-y-0.5",children:[t.jsx(o.Label,{htmlFor:"name",className:"text-sm",children:"Name"}),t.jsx(o.Input,{id:"name",value:he,onChange:k=>ye(k.target.value),required:!0,"aria-required":"true"})]}),t.jsx(o.Button,{disabled:oe,type:"submit",className:"w-full",children:i?oe?"Updating...":"Update "+(R==null?void 0:R.name):oe?"Creating...":"Create "+(R==null?void 0:R.name)})]}):t.jsxs("form",{onSubmit:ts,className:"mx-auto w-full max-w-md space-y-4",children:[t.jsxs("div",{className:"space-y-0.5",children:[t.jsx(o.Label,{htmlFor:"pageType",className:"text-sm",children:"Type"}),t.jsxs(o.Popover,{open:te,onOpenChange:Q,children:[t.jsx(o.PopoverTrigger,{asChild:!0,children:t.jsxs(o.Button,{variant:"outline",role:"combobox",disabled:i&&!C,className:tt("w-full justify-between",i&&!C?"cursor-not-allowed text-gray-500":""),children:[(R==null?void 0:R.name)||"Select page type",t.jsx(E.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),t.jsx(o.PopoverContent,{className:"w-[var(--radix-popover-trigger-width)] p-0",align:"start",children:t.jsxs(o.Command,{shouldFilter:!1,children:[t.jsx("div",{className:"sticky top-0 z-10 bg-white px-3 py-2",children:t.jsxs("div",{className:"relative",children:[t.jsx(E.Search,{strokeWidth:2,className:"absolute left-2 top-2 h-4 w-4 text-gray-400"}),t.jsx(o.Input,{placeholder:"Search page types...",className:"h-8 pl-8 text-xs",value:H,onChange:k=>K(k.target.value)})]})}),t.jsxs(cs,{className:"overflow-y-auto",children:[t.jsx(o.CommandEmpty,{children:"No page type found."}),i?ne?t.jsx(o.CommandGroup,{heading:"Partials",children:it.map(k=>t.jsxs(o.CommandItem,{value:k.key,onSelect:()=>be(k.key),className:"flex cursor-pointer items-center justify-between",children:[k.name,t.jsx(E.Check,{className:tt("mr-2 h-4 w-4",w===k.key?"opacity-100":"opacity-0")})]},k.key))}):t.jsx(o.CommandGroup,{heading:"Pages",children:rt.map(k=>t.jsxs(o.CommandItem,{value:k.key,onSelect:()=>be(k.key),className:"flex cursor-pointer items-center justify-between",children:[k.name,t.jsx(E.Check,{className:tt("mr-2 h-4 w-4",w===k.key?"opacity-100":"opacity-0")})]},k.key))}):t.jsxs(t.Fragment,{children:[rt.length>0&&t.jsx(o.CommandGroup,{heading:"Pages",children:rt.map(k=>t.jsxs(o.CommandItem,{value:k.key,onSelect:()=>be(k.key),className:"flex cursor-pointer items-center justify-between",children:[k.name,t.jsx(E.Check,{className:tt("mr-2 h-4 w-4",w===k.key?"opacity-100":"opacity-0")})]},k.key))}),it.length>0&&t.jsx(o.CommandGroup,{heading:"Partials",children:it.map(k=>t.jsxs(o.CommandItem,{value:k.key,onSelect:()=>be(k.key),className:"flex cursor-pointer items-center justify-between",children:[k.name,t.jsx(E.Check,{className:tt("mr-2 h-4 w-4",w===k.key?"opacity-100":"opacity-0")})]},k.key))})]})]})]})})]}),B&&t.jsxs("div",{className:"mt-2 rounded-md border border-yellow-200 bg-yellow-50 p-3",children:[t.jsx("p",{className:"text-sm text-yellow-800",children:"Changing the page type may impact the page data. Are you sure you want to proceed?"}),t.jsxs("div",{className:"mt-2 flex gap-2",children:[t.jsx(o.Button,{variant:"outline",size:"sm",onClick:()=>S(!1),children:"Cancel"}),t.jsx(o.Button,{variant:"default",size:"sm",onClick:ie,children:"Confirm"})]})]})]}),!i&&(R==null?void 0:R.hasSlug)&&de.length>0&&t.jsxs("div",{className:"space-y-1",children:[t.jsx(o.Label,{className:"mb-1 block text-sm",children:"Template"}),t.jsx(si,{templates:de,selectedTemplateId:F,onSelectTemplate:I,isLoading:ve})]}),t.jsx(ei,{pages:l,selectedParentId:_,onChange:De}),t.jsxs("div",{className:"space-y-0.5",children:[t.jsx(o.Label,{htmlFor:"name",className:"text-sm",children:"Name"}),t.jsx(o.Input,{id:"name",value:he,onChange:k=>ye(k.target.value),required:!0,"aria-required":"true",placeholder:"Enter page name"})]}),(R==null?void 0:R.dynamicSegments)&&_&&_!=="none"&&t.jsxs("div",{className:"space-y-2",children:[t.jsxs("div",{className:"flex items-center space-x-2",children:[t.jsx("input",{type:"checkbox",id:"useDynamicSlug",checked:ce,onChange:k=>Ne(k.target.checked),className:"rounded border-gray-300"}),t.jsx(o.Label,{htmlFor:"useDynamicSlug",className:"text-sm",children:"Use Dynamic Slug"})]}),ce&&t.jsx("div",{className:"space-y-2",children:t.jsx("div",{className:"space-y-0.5",children:t.jsx(Zr,{value:M,onChange:G,dynamicPattern:(R==null?void 0:R.dynamicSlug)||"{{id}}",placeholder:"Enter custom slug part (optional)",onValidationChange:W})})})]}),(!(R!=null&&R.dynamicSegments)||!ce)&&t.jsxs("div",{className:"space-y-0.5",children:[t.jsx(o.Label,{htmlFor:"slug",className:"text-sm",children:"Slug"}),t.jsx(Zs,{value:x,onChange:A,placeholder:_&&_!=="none"?"Enter page slug":w==="page"?"Leave empty for home page":"Required - e.g. your-slug",parentSlug:_&&_!=="none"?(ss=l==null?void 0:l.find(k=>k.id===_))==null?void 0:ss.slug:void 0,onValidationChange:p}),g&&t.jsx("p",{className:"text-xs text-red-500",children:g})]}),t.jsx(o.Button,{disabled:oe||!y&&(!(R!=null&&R.dynamicSegments)||!ce)||ce&&!T,type:"submit",className:"w-full",children:i?oe?"Updating...":"Update page":oe?"Creating...":"Create Page"})]})}const Qn=({addEditPage:e,setAddEditPage:s,closePanel:n})=>{const{data:a}=Pe(),r=!!(e!=null&&e.id);return t.jsx(o.Dialog,{open:!!e,onOpenChange:()=>s(void 0),children:t.jsxs(o.DialogContent,{className:"sm:max-w-[425px]",children:[t.jsxs(o.DialogHeader,{children:[t.jsxs(o.DialogTitle,{children:[r?"Edit":"Add New"," "]}),t.jsx(o.DialogDescription,{children:r?"Update your page name":"Enter details to create a new page"})]}),t.jsx(ii,{closePanel:n,addEditPage:e,close:()=>s(void 0),additionalPageTypes:a??[]})]})})},li=()=>{const e=re(),s=D.useQueryClient(),n=J();return D.useMutation({mutationFn:async({pageId:a,name:r,slug:i})=>{const l={pageId:a,name:r};return i&&(l.slug=i),await n(e,{action:"DUPLICATE_PAGE",data:l})},onSuccess:()=>{s.invalidateQueries({queryKey:[Y,L.GET_WEBSITE_PAGES]}),V.toast.success("Page duplicated successfully")},onError:a=>{V.toast.error("Failed to duplicate page",{description:a.message||"An error occurred while duplicating the page"})}})},Wn=({page:e,onClose:s})=>{const{mutate:n,isPending:a}=li(),[r,i]=f.useState(null),[l,c]=f.useState(`${e.name} (Copy)`),u=m.isEmpty(e.slug),[d,h]=f.useState(u?"":`${e.slug.split("/").pop()}-copy`),g=u?"":m.initial(e.slug.split("/")).join("/"),[b,y]=f.useState(!1),p=w=>{if(w.preventDefault(),!l.trim()){i("Name is required");return}if(!u&&!d.trim()){i("Slug is required");return}i(null),y(!0);const v={pageId:e.id,name:l};u||(v.slug=`${g}/${d}`),n(v,{onSuccess:()=>{y(!1),s()},onError:N=>{y(!1),N.code==="SLUG_EXISTS"?i("A page with this slug already exists. Please choose a different slug."):N.code==="INVALID_SLUG"?i("The slug format is invalid. Please use only lowercase letters, numbers, and hyphens."):N.code==="PERMISSION_DENIED"?i("You don't have permission to duplicate this page."):i(N.message||"Failed to duplicate page. Please try again later.")}})};return t.jsx(o.Dialog,{open:!!e,onOpenChange:s,children:t.jsxs(o.DialogContent,{className:"sm:max-w-[425px]",children:[t.jsxs(o.DialogHeader,{children:[t.jsx(o.DialogTitle,{children:"Duplicate Page"}),t.jsx(o.DialogDescription,{children:"Create a copy of the page with a new name and slug"})]}),t.jsxs("div",{className:"bg-gray-50 p-3 rounded-md mb-4",children:[t.jsx("h3",{className:"text-sm font-medium mb-1",children:"Duplicating:"}),t.jsxs("div",{className:"text-sm text-gray-700 flex flex-col gap-1",children:[t.jsxs("div",{children:[t.jsx("span",{className:"font-medium",children:"Name:"})," ",e.name]}),!u&&t.jsxs("div",{children:[t.jsx("span",{className:"font-medium",children:"Slug:"})," ",e.slug]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-medium",children:"Type:"})," ",e.pageType]})]})]}),t.jsxs("form",{onSubmit:p,className:"space-y-4",children:[t.jsxs("div",{className:"space-y-2",children:[t.jsx(o.Label,{htmlFor:"name",className:"text-sm",children:"Name"}),t.jsx(o.Input,{id:"name",value:l,onChange:w=>c(w.target.value),required:!0})]}),!u&&t.jsxs("div",{className:"space-y-2",children:[t.jsx(o.Label,{htmlFor:"slug",className:"text-sm",children:"Slug"}),t.jsx(Zs,{value:d,onChange:w=>h(w),parentSlug:g,onValidationChange:w=>{i(w?null:"Invalid slug")}})]}),r&&t.jsxs(o.Alert,{variant:"destructive",className:"py-2",children:[t.jsx(E.AlertCircle,{className:"h-4 w-4"}),t.jsx("span",{className:"text-sm",children:r})]}),t.jsxs("div",{className:"flex justify-end gap-2",children:[t.jsx(o.Button,{type:"button",variant:"outline",onClick:s,disabled:a,children:"Cancel"}),t.jsx(o.Button,{type:"submit",disabled:!l.trim()||!u&&!d.trim()||a||b,children:a||b?"Duplicating...":"Duplicate"})]})]})]})})},oi=1*1024*1024,Yn=({page:e,onClose:s})=>{const[n,a]=f.useState(!1),[r,i]=f.useState(""),[l,c]=f.useState(""),[u,d]=f.useState(!1),h=f.useRef(null),g=qr(),{data:b}=Pe(),y=b==null?void 0:b.find(B=>B.key===e.pageType),p=(y==null?void 0:y.name)||m.startCase(e.pageType),w=f.useCallback(B=>{var P;const S=(P=B.target.files)==null?void 0:P[0];if(S){if(S.size>oi){V.toast.error("File too large",{description:`Maximum file size is 1MB. Selected file is ${(S.size/1024).toFixed(2)}KB.`}),h.current&&(h.current.value="");return}try{d(!0);const O=new FileReader;O.onloadend=()=>{c(O.result),d(!1)},O.readAsDataURL(S)}catch(O){console.error("Error reading file:",O),d(!1),V.toast.error("Failed to process image",{description:O instanceof Error?O.message:"Unknown error"})}}},[]),v=()=>{c(""),h.current&&(h.current.value="")},N=()=>{var B;(B=h.current)==null||B.click()},C=()=>{a(!0),g.mutate({page:e,name:e.name,description:r.trim()||void 0,pageType:e.pageType,...l?{previewImage:l}:{}},{onSuccess:()=>{a(!1),s()},onError:()=>{a(!1)}})};return t.jsx(o.Dialog,{open:!0,onOpenChange:s,children:t.jsxs(o.DialogContent,{children:[t.jsxs(o.DialogHeader,{children:[t.jsx(o.DialogTitle,{children:"Mark as template"}),t.jsxs(o.DialogDescription,{className:"py-4 text-slate-500 space-y-1 text-xs",children:["Are you sure you want to mark this page as a template?",t.jsx("br",{}),"Templates can be used to create new pages with the same content."]})]}),t.jsxs("div",{className:"space-y-4 mb-4 text-xs",children:[t.jsxs("div",{className:"p-4 border rounded bg-slate-50 space-y-3",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(E.Tag,{className:"w-4 h-4 text-slate-500"}),t.jsx("span",{className:"font-medium text-slate-500",children:"Page Name:"}),t.jsx("span",{className:"font-semibold",children:m.startCase(e.name)})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(E.File,{className:"w-4 h-4 text-slate-500"}),t.jsx("span",{className:"font-medium text-slate-500",children:"Type:"}),t.jsx("span",{className:"font-semibold",children:p})]})]}),t.jsxs("div",{children:[t.jsx(o.Label,{htmlFor:"description",className:"text-xs font-medium",children:"Description (Optional)"}),t.jsx(o.Textarea,{id:"description",placeholder:"Describe this template's purpose",className:"text-xs resize-none h-24 mt-1",value:r,onChange:B=>i(B.target.value)})]}),t.jsxs("div",{className:"space-y-2",children:[t.jsx(o.Label,{htmlFor:"previewImage",className:"text-xs font-medium",children:"Preview Image (Optional)"}),t.jsxs("div",{className:"space-y-2",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(o.Input,{type:"file",id:"previewImage",ref:h,onChange:w,accept:"image/*",className:"hidden"}),t.jsx(o.Button,{type:"button",variant:"outline",onClick:N,disabled:u,className:"w-full",children:u?t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsx("div",{className:"animate-spin h-4 w-4 border-2 border-current border-t-transparent rounded-full"}),"Uploading..."]}):t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsx(E.ImageIcon,{className:"h-4 w-4"}),"Select image"]})}),l&&t.jsx(o.Button,{type:"button",variant:"outline",size:"icon",onClick:v,children:t.jsx(E.X,{className:"h-4 w-4"})})]}),l&&t.jsx("div",{className:"rounded-md overflow-hidden border aspect-video",children:t.jsx("img",{src:l,alt:"Preview",className:"w-full h-full max-h-[200px] object-contain"})}),t.jsx("p",{className:"text-xs text-muted-foreground",children:"max 1mb"})]})]})]}),t.jsxs(o.DialogFooter,{className:n?"opacity-75 pointer-events-none":"",children:[t.jsx(o.Button,{variant:"outline",onClick:B=>{B.stopPropagation(),s()},children:"Cancel"}),t.jsx(o.Button,{variant:"default",disabled:n,onClick:C,children:"Mark as template"})]})]})})},Jn=({page:e,setDuplicatePage:s,setAddEditPage:n,setUnpublishPage:a,setDeletePage:r,setMarkAsTemplate:i,setUnmarkAsTemplate:l,children:c})=>{const{hasPermission:u}=q.usePermissions(),{data:d}=Pe(),h=f.useMemo(()=>m.find(d,{key:e.pageType}),[d,e.pageType]),g=f.useMemo(()=>!!e.isTemplate,[e.isTemplate]),b=f.useMemo(()=>!!(h!=null&&h.hasSlug),[h==null?void 0:h.hasSlug]);return!u(je.EDIT_PAGE)&&!u(je.DELETE_PAGE)&&!u(je.UNPUBLISH_PAGE)||!e?null:t.jsxs(o.DropdownMenu,{children:[t.jsx(o.DropdownMenuTrigger,{asChild:!0,onClick:p=>p.stopPropagation(),children:c}),t.jsxs(o.DropdownMenuContent,{align:"center",className:"text-sm",children:[u(je.ADD_PAGE)&&t.jsxs(o.DropdownMenuItem,{className:"flex items-center gap-2 cursor-pointer",onClick:p=>{p.stopPropagation(),s(e)},children:[t.jsx(E.CopyPlusIcon,{className:"size-3"}),"Duplicate page"]}),u(je.EDIT_PAGE)&&t.jsxs(o.DropdownMenuItem,{className:"flex items-center gap-2 cursor-pointer",onClick:p=>{p.stopPropagation(),n({...e,global:!(h!=null&&h.hasSlug)})},children:[t.jsx(E.Pencil,{className:"size-3"}),"Edit"]}),(e==null?void 0:e.online)&&u(je.UNPUBLISH_PAGE)&&t.jsxs(o.DropdownMenuItem,{className:"flex items-center gap-2 cursor-pointer",onClick:p=>{p.stopPropagation(),a(e)},children:[t.jsx(E.Power,{className:"size-3"}),ae.UNPUBLISH]}),u(je.DELETE_PAGE)&&t.jsxs(o.DropdownMenuItem,{className:"flex items-center gap-2 cursor-pointer",onClick:p=>{p.stopPropagation(),r(e)},children:[t.jsx(E.Trash,{className:"size-3"}),ae.DELETE]}),u(je.MARK_AS_TEMPLATE)&&b&&t.jsx(t.Fragment,{children:g?t.jsxs(o.DropdownMenuItem,{className:"flex items-center gap-2 cursor-pointer",onClick:p=>{p.stopPropagation(),l(e)},children:[t.jsx(E.SquareLibrary,{className:"size-3"}),ae.UNMARK_AS_TEMPLATE]}):t.jsxs(o.DropdownMenuItem,{className:"flex items-center gap-2 cursor-pointer",onClick:p=>{p.stopPropagation(),i(e)},children:[t.jsx(E.SquareLibrary,{className:"size-3"}),ae.MARK_AS_TEMPLATE]})})]})]})},Xn=({page:e,onClose:s})=>{const[n,a]=f.useState(!1),r=zr(),i=()=>{a(!0),r.mutate(e,{onSuccess:()=>{a(!1),s()},onError:()=>{a(!1)}})};return t.jsx(o.Dialog,{open:!0,onOpenChange:s,children:t.jsxs(o.DialogContent,{children:[t.jsxs(o.DialogHeader,{children:[t.jsx(o.DialogTitle,{children:"Unmark as template"}),t.jsx(o.DialogDescription,{className:"py-4 text-slate-500 space-y-1 text-xs",children:"Are you sure you want to unmark this page as a template?"})]}),t.jsxs(o.DialogFooter,{className:n?"opacity-75 pointer-events-none":"",children:[t.jsx(o.Button,{variant:"outline",onClick:l=>{l.stopPropagation(),s()},children:"Cancel"}),t.jsx(o.Button,{variant:"default",disabled:n,onClick:i,children:"Unmark as template"})]})]})})},ci=_n("expandedPagesState",[]),tn=e=>m.flatMap(e,s=>[s,...s.children?tn(s.children):[]]),ui=(e,s)=>{const n=(a,r=[])=>{for(const i of a){const l=[...r,i.id];if(i.id===s)return l;if(i.children&&i.children.length>0){const c=n(i.children,l);if(c)return c}}return null};return n(e)||[]},Zn=(e,s)=>{if(!s)return[];const n=tn(e),a=m.find(n,r=>r.id===s);if(a){if(a.parent)return[...Zn(e,a.parent),s];const r=ui(e,s);if(!m.isEmpty(r))return r}return[s]},di=e=>{const s=new Set,n=(a,r=[])=>{a.forEach(i=>{const l=[...r,i.id];i.shouldExpandOnSearch&&l.forEach(c=>s.add(c)),i.children&&!m.isEmpty(i.children)&&n(i.children,l)})};return n(e),Array.from(s)},ea=e=>{const[s,n]=Ie.useAtom(ci),a=e?m.includes(s,e):!1,r=f.useCallback(()=>{n(d=>a?m.filter(d,h=>h!==e):[...d,e])},[n,a,e]),i=f.useCallback((d,h)=>{if(!h||m.isEmpty(d))return;const g=tn(d),b=Zn(g,h);if(!Array.isArray(b)||m.isEmpty(b))return;const y=b.slice(0,-1);m.isEmpty(y)||n(p=>m.uniq([...p,...y]))},[n]),l=f.useCallback(d=>{if(m.isEmpty(d))return;const h=di(d);m.isEmpty(h)||n(g=>m.union(g,h))},[n]),c=f.useCallback(d=>{if(m.isEmpty(d))return;const h=m.flatMap(d,g=>{const b=y=>[y.id,...y.children?m.flatMap(y.children,b):[]];return b(g)});n(h)},[n]),u=f.useCallback(()=>{n([])},[n]);return{isExpanded:a,toggleExpanded:r,updateForSelectedPage:i,expandedPages:s,expandPagesOnSearch:l,setExpandedPages:n,expandAll:c,collapseAll:u}},fn=(e,s)=>!e||!Array.isArray(e)?[]:m.isEmpty(s)?e:m.compact(m.filter(e,n=>{const a=m.toLower(s);return m.includes(m.toLower((n==null?void 0:n.name)||""),a)||m.includes(m.toLower((n==null?void 0:n.slug)||""),a)})),mi=(e,s)=>{const n=new Set,a=m.keyBy(e,"id");return s.forEach(r=>{let i=r;for(;i.parent&&a[i.parent];)n.add(i.parent),i=a[i.parent]}),Array.from(n).map(r=>a[r])},_s=(e,s,n)=>m.isEmpty(s)?e:e.map(a=>{if(!n(a.pageType))return{...a,shouldExpandOnSearch:!0,children:a.children?_s(a.children,s,n):[]};const r=a.children&&a.children.some(i=>m.includes(m.toLower(i.name||""),m.toLower(s))||m.includes(m.toLower(i.slug||""),m.toLower(s)));return{...a,shouldExpandOnSearch:r,children:a.children?_s(a.children,s,n):[]}}),hi=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},ta=e=>!e||!e.length?[]:[...e].sort((n,a)=>(n.name||"").localeCompare(a.name||"")).map(n=>({...n,children:n.children?ta(n.children):[]})),fi=(e,s,n,a)=>{if(!e||!e.length)return[];let r=e;if(n!=="all"&&(r=m.compact(m.filter(e,{pageType:n}))),m.isEmpty(s))r=fn(r,s);else{const h=fn(r,s),g=mi(e,h);r=m.uniqBy([...h,...g],"id")}const i=ta(hi(r)),l=_s(i,s,a),c=m.filter(l,h=>a(h.pageType)).sort((h,g)=>(h.name||"").localeCompare(g.name||"")),u=m.keyBy(m.filter(l,h=>!a(h.pageType)),"pageType"),d=Object.values(m.mapValues(u,(h,g)=>({...h,name:m.startCase(g),isPartialGroup:!0,children:l.filter(b=>b.pageType===g)})));return[...c,...d]},gi=({parentSlug:e,page:s,active:n,closePanel:a,setUnpublishPage:r,setDeletePage:i,setAddEditPage:l,setMarkAsTemplate:c,setUnmarkAsTemplate:u,setDuplicatePage:d,hasChildren:h,isExpanded:g,onToggleExpand:b})=>{const y=en(),{data:p}=Pe(),[,w]=q.useSidebarActivePanel(),v=f.useMemo(()=>m.find(p,{key:s.pageType}),[p,s.pageType]),N=f.useMemo(()=>{const P=m.get(s,"slug",""),O=e?Ve(e):"",z=O?P.replace(O,""):P;return z||"/"},[s,e]),C=f.useMemo(()=>!!s.isTemplate,[s.isTemplate]),B=f.useCallback(()=>{w("outline"),y(m.get(s,"id"),a)},[y,a,s,w]),S=f.useCallback(P=>{P.stopPropagation(),b()},[b]);return t.jsxs("div",{onClick:B,className:`rounded flex p-1.5 items-center justify-between leading-none cursor-pointer px-3 py-1.5 ${n?"bg-gray-200":"hover:bg-gray-100"}`,children:[t.jsxs("div",{className:"flex items-center gap-x-2",children:[t.jsx("button",{onClick:S,disabled:!h,className:`flex items-center justify-center w-4 h-5 text-gray-400 hover:text-gray-500 transition-colors ${h?"hover:text-blue-400":"opacity-0"}`,children:t.jsx(E.ChevronRight,{size:16,className:`w-4 h-5 transition-transform duration-200 ${g?"rotate-90":""}`})}),s.dynamic?t.jsx("div",{className:"w-4 h-4 text-slate-500 stroke-[1]",children:t.jsx(E.StarsIcon,{className:"w-4 h-4 text-yellow-400"})}):v!=null&&v.icon?t.jsx("div",{className:"w-4 h-4 text-slate-500 stroke-[1]",dangerouslySetInnerHTML:{__html:v.icon}}):v!=null&&v.hasSlug?t.jsx(E.File,{className:"w-4 h-4 text-slate-500 stroke-[1]"}):t.jsx(E.Globe,{className:"w-4 h-4 text-slate-500 stroke-[1]"}),!s.isPartialGroup&&t.jsx("div",{className:`w-2.5 h-2.5 rounded-full ${s.online?"bg-green-300":"bg-gray-300"}`}),t.jsx("span",{className:"font-light leading-none truncate text-slate-800",children:s.name}),v!=null&&v.hasSlug?t.jsxs(o.Badge,{variant:"outline",className:`ml-2 text-xs max-w-full leading-tight py-px font-normal rounded-full text-gray-400 border ${n?"border-gray-300":"border-gray-200"}`,children:[N,s.dynamic&&t.jsxs("span",{className:"text-xs font-light leading-none text-slate-500",children:[m.endsWith(N,"/")?`${v==null?void 0:v.dynamicSlug}`:`/${v==null?void 0:v.dynamicSlug}`,s.dynamicSlugCustom]})]}):s.isPartialGroup?null:t.jsx(o.Badge,{variant:"outline",className:`ml-2 text-xs max-w-full leading-tight py-px font-normal rounded-full text-gray-400 border ${n?"border-gray-300":"border-gray-200"}`,children:v==null?void 0:v.name}),C&&t.jsx(o.Badge,{variant:"outline",className:"ml-2 text-xs py-0 font-normal text-blue-500 border border-blue-200 bg-blue-50",children:"Template"})]}),!s.isPartialGroup&&t.jsxs("div",{className:"flex items-center space-x-4",children:[t.jsx(Sr,{currentEditor:s.currentEditor}),t.jsx(Jn,{page:s,setDuplicatePage:d,setAddEditPage:l,setUnpublishPage:r,setDeletePage:i,setMarkAsTemplate:c,setUnmarkAsTemplate:u,children:t.jsx("div",{className:"p-0.5 m-0 hover:bg-white rounded duration-100 cursor-pointer",children:t.jsx(E.MoreHorizontal,{className:"w-4 h-4",onClick:P=>P.stopPropagation()})})})]})]})},xi=({close:e,isOpen:s})=>{const[,n]=f.useState([]),[a,r]=f.useState(null),[i,l]=f.useState(""),[c,u]=f.useState(""),[d,h]=f.useState(null),g=T=>c?String(m.get(T,"name","")).toLowerCase().includes(c.toLowerCase())||String(m.get(T,"key","")).toLowerCase().includes(c.toLowerCase()):!0,[b,y]=f.useState(null),[p,w]=f.useState(null),[v,N]=f.useState(null),[C,B]=f.useState(null),{data:S,isFetching:P,refetch:O}=Zt(),[z,$]=f.useState(""),{hasPermission:se}=q.usePermissions(),{updateForSelectedPage:H,expandPagesOnSearch:K,expandAll:te,collapseAll:Q}=ea(null),[ne,_]=_e(),U=ne.get("page"),he=f.useRef(null),{data:ye}=Pe(),ce=f.useCallback(T=>{var W;return(W=m.find(ye,{key:T}))==null?void 0:W.hasSlug},[ye]);f.useEffect(()=>{s&&O()},[s,O]),f.useEffect(()=>{if(!m.isEmpty(z))return;const T=sessionStorage.getItem("pageTypeFilter")||"all";!m.isEmpty(ye)&&T&&(m.find(ye,{key:T})?$(T):$("all"))},[ye,z]);const j=T=>{$(T),sessionStorage.setItem("pageTypeFilter",T),u("")},x=f.useCallback(T=>{const F=new URLSearchParams(window.location.search).get("lang"),Z=new URLSearchParams({page:T});F&&Z.set("lang",F),window.history.pushState({},"",`?${Z.toString()}`),_(Z),window.dispatchEvent(new PopStateEvent("popstate")),e()},[_,e]);f.useEffect(()=>{if(U&&!P){const T=m.find(S,{id:U});T&&(T!=null&&T.pageType)?n(W=>[...W,T==null?void 0:T.pageType]):(window.history.replaceState(null,"","/"),_(new URLSearchParams({})),window.dispatchEvent(new PopStateEvent("popstate")))}},[S,U,P,_]);const A=f.useMemo(()=>S?fi(S,i,z,ce):[],[S,i,z,ce]);f.useEffect(()=>{U&&!P&&!m.isEmpty(A)&&(H(A,U),he.current&&he.current.scrollIntoView({behavior:"smooth",block:"end"}))},[U,P,A,H]),f.useEffect(()=>{!m.isEmpty(i)&&!m.isEmpty(A)&&K(A)},[i,A,K]);const M=f.useCallback(()=>{te(A)},[te,A]),G=f.useCallback(()=>{Q()},[Q]);return t.jsxs("div",{className:"flex flex-col justify-between h-full",children:[t.jsxs("div",{className:"flex flex-col h-full space-y-6",children:[t.jsxs("div",{className:"flex gap-1 items-center justify-between",children:[t.jsxs("div",{className:"relative flex item-center gap-x-4 flex-1",children:[t.jsx(E.Search,{strokeWidth:2.5,className:"absolute left-3 top-2.5 h-4 w-4 text-gray-400"}),t.jsx(o.Input,{placeholder:"Search pages...",className:"text-xs font-medium leading-none text-gray-700 pl-9 pr-24 placeholder:text-gray-400",value:i,onChange:T=>l(T.target.value)}),!m.isEmpty(z)&&t.jsxs(o.Select,{value:z,onValueChange:j,children:[t.jsx(o.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(o.SelectValue,{placeholder:"Select page type"})}),t.jsxs(o.SelectContent,{align:"end",children:[t.jsx("div",{className:"px-3 py-2 sticky top-0 bg-white z-10",children:t.jsxs("div",{className:"relative",children:[t.jsx(E.Search,{strokeWidth:2,className:"absolute left-2 top-2 h-4 w-4 text-gray-400"}),t.jsx(o.Input,{placeholder:"Search page types...",className:"pl-8 h-8 text-xs",value:c,onChange:T=>u(T.target.value),onKeyDown:T=>T.stopPropagation()})]})}),t.jsx(o.SelectItem,{value:"all",children:"All"},"all"),!m.isEmpty(m.filter(ye,T=>T.hasSlug&&g(T)))&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"px-2 py-1.5 text-xs font-semibold text-gray-500 mt-2 border-t pt-2",children:"Pages"}),m.map([...m.filter(ye,T=>T.hasSlug&&g(T))].sort((T,W)=>m.get(T,"name","").localeCompare(m.get(W,"name",""))),T=>t.jsx(o.SelectItem,{value:m.get(T,"key"),children:m.get(T,"name")},m.get(T,"key")))]}),!m.isEmpty(m.filter(ye,T=>!T.hasSlug&&g(T)))&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"px-2 py-1.5 text-xs font-semibold text-gray-500 mt-2 border-t pt-2",children:"Partials"}),m.map([...m.filter(ye,T=>!T.hasSlug&&g(T))].sort((T,W)=>m.get(T,"name","").localeCompare(m.get(W,"name",""))),T=>t.jsx(o.SelectItem,{value:m.get(T,"key"),children:m.get(T,"name")},m.get(T,"key")))]}),m.isEmpty(m.filter(ye,g))&&t.jsx("div",{className:"px-3 py-2 text-sm text-gray-500 text-center",children:"No matching page types found"})]})]})]}),t.jsxs("div",{className:"flex gap-1 ",children:[t.jsx(o.Button,{variant:"outline",size:"icon",onClick:M,className:"p-1 text-gray-500",children:t.jsx(E.ChevronsUpDown,{})}),t.jsx(o.Button,{variant:"outline",size:"icon",onClick:G,className:"p-1 text-gray-500",children:t.jsx(E.ChevronsDownUp,{})})]})]}),P?t.jsx("div",{className:"space-y-2",children:m.map([...Array(5).keys()],T=>t.jsx("div",{className:"w-full bg-gray-200 rounded h-9 animate-pulse"},T))}):m.isEmpty(A)?t.jsxs("div",{className:"h-[70vh] flex flex-col gap-y-1 items-center justify-center text-slate-500 text-sm font-medium",children:[t.jsx(E.File,{className:"h-6 w-6 stroke-[1]"}),"Empty List!",t.jsx("span",{className:"font-light",children:"Add new page to start"})]}):t.jsx("div",{className:"text-sm text-slate-700 space-y-2 h-[70vh] overflow-y-auto",children:m.map(A,T=>{const W=T.id===U;return t.jsx("div",{ref:W?he:null,children:t.jsx(sa,{item:T,currentPage:U,close:e,setUnpublishPage:y,setDeletePage:h,setAddEditPage:w,setMarkAsTemplate:N,setUnmarkAsTemplate:B,setDuplicatePage:r,level:0})},`page-item-${T.id}`)})})]}),se(je.ADD_PAGE)&&t.jsxs(o.Button,{className:"flex text-sm gap-x-2",onClick:()=>{w({slug:"",name:"",pageType:z==="all"?"page":z})},children:[t.jsx(E.Plus,{className:"w-4 h-4"})," Add New"]}),p&&t.jsx(Qn,{closePanel:e,editPage:x,addEditPage:p,setAddEditPage:w}),d&&t.jsx(Xs,{page:d,onClose:()=>h(null)}),b&&t.jsx(bs,{page:b,onClose:()=>y(null)}),v&&t.jsx(Yn,{page:v,onClose:()=>N(null)}),C&&t.jsx(Xn,{page:C,onClose:()=>B(null)}),a&&t.jsx(Wn,{page:a,onClose:()=>r(null)})]})},sa=({item:e,currentPage:s,close:n,setUnpublishPage:a,setDeletePage:r,setAddEditPage:i,setMarkAsTemplate:l,setUnmarkAsTemplate:c,setDuplicatePage:u,parentSlug:d,level:h=0})=>{const g=!m.isEmpty(e==null?void 0:e.children),{isExpanded:b,toggleExpanded:y}=ea(e==null?void 0:e.id);return t.jsxs("div",{className:"border-0",children:[t.jsx(gi,{closePanel:n,setUnpublishPage:a,setDeletePage:r,setAddEditPage:i,setMarkAsTemplate:l,setUnmarkAsTemplate:c,setDuplicatePage:u,active:s===e.id,page:e,parentSlug:d,hasChildren:g,isExpanded:b,onToggleExpand:y}),g&&b&&t.jsx("div",{className:"pt-2 pl-6 bg-white",children:m.map(m.get(e,"children",[]),p=>t.jsx(sa,{item:p,currentPage:s,close:n,setUnpublishPage:a,setDeletePage:r,setAddEditPage:i,setMarkAsTemplate:l,setUnmarkAsTemplate:c,setDuplicatePage:u,parentSlug:e.slug,level:h+1},p.id||`child-${h}-${p.key}`))})]},e.id||`level-${h}-${e.key}`)},pi=({isDefaultLang:e,searchQuery:s,setSearchQuery:n})=>t.jsx(o.Input,{type:"text",autoFocus:!0,value:e?s:"",onChange:a=>n(a.target.value),placeholder:e?"Search pages...":"To search select default language",disabled:!e}),yi=({dynamicPage:e,setDynamicPage:s,searchQuery:n,setSearchQuery:a,dynamicPages:r})=>{const{selectedLang:i,fallbackLang:l}=q.useLanguages(),c=(i==null?void 0:i.length)===0;return t.jsxs(o.DropdownMenu,{children:[t.jsx(o.DropdownMenuTrigger,{asChild:!0,children:t.jsxs(o.Button,{variant:"ghost",className:"w-max focus:outline-none focus:ring-0 border-[0px] rounded-md py-1 text-sm h-max border border-gray-200 hover:bg-gray-100 pl-4",children:[e?m.get(e,"name"):"Select Page",t.jsx(E.ChevronDown,{className:"ml-2 h-4 w-4"})]})}),t.jsxs(o.DropdownMenuContent,{className:"w-96 divide-y shadow-xl p-0 max-h-[75vh]",children:[t.jsx("div",{className:"p-1.5 bg-gray-50/30",children:t.jsx(pi,{isDefaultLang:c,searchQuery:n,setSearchQuery:a})}),(r==null?void 0:r.length)===0?t.jsx("div",{className:"h-24 text-xs flex items-center justify-center",children:"No pages found"}):r==null?void 0:r.map(u=>t.jsx(o.DropdownMenuItem,{onClick:()=>s(u),disabled:c?l!==u.lang:i!==u.lang,className:`flex flex-col justify-start cursor-pointer overflow-x-auto whitespace-nowrap no-scrollbar ${u.id===(e==null?void 0:e.id)?"bg-blue-50":"hover:bg-gray-50"}`,children:t.jsxs("div",{className:"w-full text-xs whitespace-nowrap p-1",children:[t.jsxs("div",{children:["Name : ",t.jsx("span",{className:"font-medium",children:u.name})]}),u.lang&&t.jsxs("div",{children:["Language : ",t.jsx("span",{className:"font-medium",children:ke[u.lang]})]}),t.jsxs("div",{children:["Slug :",t.jsxs("span",{className:"font-mono font-medium",children:[" ",u.slug]})]})]})},u.id))]})]})},ji=({children:e})=>t.jsx("div",{className:"z-[9999] fixed bottom-0 left-0 right-0 z-[20] flex items-center justify-center w-screen top-[50px] bg-black/30 backdrop-blur-sm",children:t.jsx("div",{className:"bg-white rounded-md p-4 shadow-xl min-w-[300px] max-w-[400px] flex flex-col items-center justify-center",children:e})}),vi=()=>{const{isPending:e,dynamicPage:s,dynamicPages:n,allLangPages:a,selectedLang:r,searchQuery:i,updateDynamicPage:l,updateSearchQuery:c,onChangeLanguage:u}=wr(),d=f.useRef(void 0);f.useEffect(()=>{d.current!==r&&s&&(u(),d.current=r)},[r,n]);const h=a.length>0;return t.jsxs("div",{className:"relative",children:[!e&&!s&&t.jsxs(ji,{children:[t.jsx("h1",{className:"text-lg font-medium",children:h?"Select a page":"No pages found"}),t.jsx("p",{className:"text-sm text-center text-gray-600 pt-4",children:h?"Please select a page from the list in the top header. This will enable you to edit the page.":"Please add a new page"})]}),t.jsx(yi,{dynamicPage:s,setDynamicPage:l,searchQuery:i,setSearchQuery:c,dynamicPages:a})]})},bi=({page:e})=>{const[s,n]=f.useState(null),[a,r]=f.useState(null),[i,l]=f.useState(null),[c,u]=f.useState(null),[d,h]=f.useState(null),[g,b]=f.useState(null);return e?t.jsxs(t.Fragment,{children:[t.jsx(Jn,{page:e,setDuplicatePage:y=>h(y),setAddEditPage:y=>b(y),setUnpublishPage:y=>r(y),setDeletePage:y=>n(y),setMarkAsTemplate:y=>l(y),setUnmarkAsTemplate:y=>u(y),children:t.jsx("div",{className:"p-0 m-0 w-6 h-6 p-1 absolute right-2 top-1/2 -translate-y-1/2 hover:bg-gray-200 rounded duration-100 cursor-pointer",children:t.jsx(E.MoreHorizontal,{className:"w-4 h-4",onClick:y=>y.stopPropagation()})})}),g&&t.jsx(Qn,{closePanel:()=>b(null),editPage:()=>{},addEditPage:g,setAddEditPage:b}),s&&t.jsx(Xs,{page:s,onClose:()=>n(null)}),a&&t.jsx(bs,{page:a,onClose:()=>r(null)}),i&&t.jsx(Yn,{page:i,onClose:()=>l(null)}),c&&t.jsx(Xn,{page:c,onClose:()=>u(null)}),d&&t.jsx(Wn,{page:d,onClose:()=>h(null)})]}):null},wi=()=>{const e=He("logo",null);return e?t.jsx("div",{className:"max-h-9 w-full overflow-hidden pr-2",children:f.createElement(e,{})}):null},Si=()=>{const[e]=_e(),s=e.get("page"),{data:n,isFetching:a}=Te(),[r,i]=f.useState(!1),{savePage:l}=q.useSavePage(),c=m.get(n,"dynamic",!1),u=!!s&&!m.isEmpty(n),d=!s||!a&&m.isEmpty(n)||r,h=q.useChaiFeatureFlag("dynamic-page-selector");return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex items-center gap-x-1",children:[t.jsxs("div",{className:"relative",children:[t.jsxs(o.Button,{variant:"outline",className:"flex w-full items-center space-x-2 py-1",onClick:()=>{l(),i(!0)},children:[t.jsx("div",{children:t.jsx(E.Logs,{className:"h-4 w-4"})}),t.jsxs("span",{className:"flex max-w-[200px] items-center truncate leading-tight",children:[t.jsx("span",{className:"pr-1 font-light text-slate-600",children:"Editing:"}),a?t.jsx(E.Loader,{className:"ml-2 h-4 w-4 animate-spin text-slate-400"}):m.startCase(m.get(n,"name"))??""]}),t.jsx("div",{className:`${a?"hidden":"w-2"}`})]},"template-viewer"),!a&&t.jsx(bi,{page:n})]}),c&&!a&&h&&t.jsxs(t.Fragment,{children:[t.jsx(E.ChevronRight,{size:14,className:"text-slate-500"}),t.jsx(vi,{})]})]}),t.jsx(o.Sheet,{open:d,onOpenChange:g=>!g&&u&&i(!1),children:t.jsxs(o.SheetContent,{side:"left","aria-describedby":"pages-manager-description",className:`z-50 w-full !max-w-screen-md border-border ${u?"":"sheet-hide-close-btn"}`,children:[t.jsxs(o.SheetHeader,{className:"mb-3",children:[t.jsxs(o.SheetTitle,{className:"flex items-center gap-2 text-sm font-semibold",children:[t.jsx("div",{className:"rounded-md bg-primary p-2 text-primary-foreground",children:t.jsx(E.File,{className:"h-6 w-6"})}),t.jsxs("div",{className:"flex flex-col",children:[t.jsx("span",{className:"text-sm font-semibold",children:"Pages"}),t.jsx("span",{id:"pages-manager-description",className:"text-xs text-muted-foreground",children:"Manage your site structure"})]})]}),t.jsx(o.SheetDescription,{className:"sr-only",children:"Manage your site structure"})]}),t.jsx("div",{className:"h-[calc(100vh-100px)] overflow-y-auto",children:t.jsx(xi,{isOpen:d,close:()=>i(!1)})})]})})]})},sn=({showAdd:e=!0,variant:s="ghost"})=>{const{fallbackLang:n,languages:a,selectedLang:r,setSelectedLang:i}=q.useLanguages(),l=m.isEmpty(r)?n:r,[,c]=_e();f.useEffect(()=>{const v=new URLSearchParams(window.location.search),N=v.get("lang");N&&(a.includes(N)?i(N):(v.delete("lang"),c(v),i("")))},[a,c,i]);const[u,d]=f.useState(null),{data:h}=Te(),{data:g}=Ze(),{data:b,isFetching:y}=Ke(),p=f.useMemo(()=>{const v=m.compact(m.map(m.get(g,"languages"),N=>{const C=m.find(b,{lang:N});return{key:N,value:m.get(ke,N,N),isLangPageAdded:!!C}})).filter(Boolean);return[{key:n,value:m.get(ke,n),isLangPageAdded:!0},...v]},[n,b,g]),w=v=>{i(v);const N=new URLSearchParams(window.location.search);v===n?N.delete("lang"):N.set("lang",v);const C=N.toString(),B=`${window.location.pathname}${C?`?${C}`:""}`;window.history.pushState({},"",B),c(N),window.dispatchEvent(new PopStateEvent("popstate"))};return m.isEmpty(a)||y?null:t.jsxs(t.Fragment,{children:[t.jsxs(o.DropdownMenu,{children:[t.jsx(o.DropdownMenuTrigger,{asChild:!0,className:"focus:outline-none",children:t.jsxs(o.Button,{variant:s,size:"sm",className:"ml-px h-max gap-2 py-1.5",children:[t.jsx(E.Languages,{className:"h-4 w-4"}),m.get(ke,l,l),t.jsx(E.ChevronDown,{className:"h-4 w-4"})]})}),t.jsxs(o.DropdownMenuContent,{className:"space-y-1 border-border",children:[m.map(p.filter(v=>v.isLangPageAdded),v=>t.jsxs(o.DropdownMenuItem,{className:q.mergeClasses("flex cursor-pointer items-center justify-between text-xs font-medium text-gray-800",v.key===l&&"!bg-gray-200 text-gray-700"),onClick:()=>w(v.key),children:[t.jsx("div",{className:"text-slate-600",children:v.value}),v.key===n&&t.jsxs("small",{className:"flex items-center gap-x-1 text-[9px] leading-none text-orange-500",children:[t.jsx(E.Star,{fill:"orange",className:"h-2 w-2"}),"Primary"]})]},v.value)),e&&!m.isEmpty(p.filter(v=>!v.isLangPageAdded))&&t.jsxs(t.Fragment,{children:[t.jsx(o.Separator,{}),t.jsxs(o.Button,{size:"sm",variant:"ghost",onClick:()=>{d({name:h==null?void 0:h.name,pageType:h==null?void 0:h.pageType,lang:"",slug:"",edit:!1})},className:"text-xs font-normal duration-200 hover:bg-slate-300 hover:text-slate-800",children:[t.jsx(E.Plus,{className:"mr-1 h-3 w-3"})," Add Langauge"]})]})]})]}),u&&t.jsx(Kn,{languages:a,langProps:u,onClose:()=>d(null)})]})};function Ei(){return t.jsxs("div",{className:"relative z-10 flex items-center justify-end gap-1",children:[t.jsx(wi,{}),t.jsx(Si,{})]})}function Ni(e){const s=re(),n=J();return D.useQuery({queryKey:[Y,"revisions",e],queryFn:async()=>await n(s,{action:L.GET_PAGE_REVISIONS,data:{pageId:e}}),enabled:!!e,gcTime:0,staleTime:0})}const Ci=()=>{const e=re(),s=J(),n=D.useQueryClient();return D.useMutation({mutationFn:async a=>await s(e,{action:L.DELETE_PAGE_REVISION,data:{revisionId:a}}),onSuccess:()=>{n.invalidateQueries({queryKey:[Y,"revisions"]})}})},Ai=()=>{const e=re(),s=J(),n=D.useQueryClient();return D.useMutation({mutationFn:async({revisionId:a,discardCurrent:r})=>await s(e,{action:L.RESTORE_PAGE_REVISION,data:{revisionId:a,discardCurrent:r}}),onSuccess:()=>{n.invalidateQueries({queryKey:[Y,"revisions"]})}})};function Ti(){const{data:e}=Te(),{saveState:s}=q.useSavePage(),[n]=vs();return e?t.jsx("div",{className:"flex items-start gap-3 rounded-md border p-2 hover:bg-accent/50 bg-primary/5 mb-4",children:t.jsxs("div",{className:"flex-1 space-y-1",children:[t.jsx("div",{className:"flex items-center justify-between",children:t.jsx("p",{className:"text-sm flex items-center gap-1 font-medium leading-none",children:t.jsx("span",{className:"font-bold",children:"Currently editing"})})}),t.jsx("div",{className:"flex items-center text-xs text-muted-foreground",children:!m.isEmpty(n.lastSaved)&&t.jsxs("span",{children:["Last updated"," ",Ct.formatDistanceToNow(new Date(n.lastSaved),{addSuffix:!0})]})}),t.jsxs("div",{className:"flex items-center gap-2 pt-0.5",children:[t.jsxs("div",{className:"flex items-center gap-1 rounded-full bg-amber-500/10 px-1.5 py-0.5 text-xs text-amber-600",children:[t.jsx(E.Edit,{className:"h-3 w-3"}),t.jsx("span",{children:"Draft"})]}),s==="UNSAVED"?t.jsxs("div",{className:"flex items-center gap-1 rounded-full bg-red-500/10 px-1.5 py-0.5 text-xs text-red-600",children:[t.jsx(E.Save,{className:"h-3 w-3"}),t.jsx("span",{children:" Unsaved changes"})]}):null]})]})}):null}function Pi(){const[e,s]=we.useState(!1),[n,a]=we.useState(null),[r,i]=we.useState(!1),[l,c]=we.useState(!1),{data:u}=Te(),{data:d,isFetching:h,error:g,refetch:b}=Ni(u==null?void 0:u.id),{mutate:y,isPending:p}=Ci(),{mutate:w,isPending:v}=Ai(),N=D.useQueryClient(),C=O=>{n&&w({revisionId:n.uid,discardCurrent:O},{onSuccess:()=>{i(!1),a(null),N.invalidateQueries({queryKey:[Y,L.GET_DRAFT_PAGE]})}})},B=O=>{a(O),i(!0)},S=O=>{a(O),c(!0)},P=()=>{n&&y(n.uid,{onSuccess:()=>{c(!1),a(null)}})};return f.useEffect(()=>{e&&b()},[e,b]),t.jsxs(t.Fragment,{children:[t.jsx(o.TooltipProvider,{children:t.jsxs(o.Tooltip,{children:[t.jsxs(o.Sheet,{open:e,onOpenChange:s,children:[t.jsx(o.SheetTrigger,{asChild:!0,children:t.jsx(o.TooltipTrigger,{asChild:!0,children:t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsxs(o.Button,{variant:"ghost",size:"icon",className:"h-8 w-8",children:[t.jsx(E.History,{className:"h-4 w-4"}),t.jsx("span",{className:"sr-only",children:"View revision history"})]}),t.jsx("div",{className:"w-px h-4 bg-gray-200 dark:bg-gray-700"})]})})}),t.jsxs(o.SheetContent,{className:"sm:max-w-md p-4",children:[t.jsxs(o.SheetHeader,{className:"pb-2",children:[t.jsxs(o.SheetTitle,{className:"flex items-center gap-2",children:[t.jsx(E.History,{className:"h-5 w-5"}),"Revision History"]}),(u==null?void 0:u.createdAt)&&t.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Page created on"," ",Ct.format(new Date(u.createdAt),"MMM d, yyyy 'at' h:mm a")]})]}),t.jsx(o.ScrollArea,{className:"h-[calc(100vh-6rem)] pr-2",children:h?t.jsx(ki,{}):g?t.jsx("div",{className:"p-4 text-center text-sm text-muted-foreground",children:"Failed to load revisions. Please try again."}):t.jsxs("div",{className:"mt-2 space-y-2",children:[t.jsx(Ti,{}),d==null?void 0:d.map(O=>t.jsx(Li,{revision:O,isLatest:O.uid==="current",onRestore:()=>B(O),onDelete:()=>S(O)},O.uid))]})})]})]}),t.jsx(o.TooltipContent,{side:"bottom",children:t.jsx("p",{children:"Revision history"})})]})}),t.jsx(_i,{open:r,onOpenChange:i,revision:n,onRestore:C,isRestoring:v}),t.jsx(Di,{open:l,onOpenChange:c,revision:n,onDelete:P,isDeleting:p})]})}function ki(){return t.jsx("div",{className:"space-y-2 mt-2",children:Array.from({length:5}).map((e,s)=>t.jsxs("div",{className:"flex items-start gap-3 rounded-md border p-2",children:[t.jsxs("div",{className:"flex-1 space-y-1",children:[t.jsx(o.Skeleton,{className:"h-4 w-3/4"}),t.jsx(o.Skeleton,{className:"h-3 w-1/2"}),t.jsx(o.Skeleton,{className:"h-5 w-20 mt-1"})]}),t.jsx(o.Skeleton,{className:"h-8 w-8 rounded-full"})]},s))})}function Li({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:Ct.format(e.createdAt,"MMM d, h:mm a")})}),t.jsx("div",{className:"flex items-center gap-2 pt-0.5",children:e.type==="published"?t.jsxs("div",{className:"flex items-center gap-1 rounded-full bg-green-500/10 px-1.5 py-0.5 text-xs text-green-600",children:[t.jsx(E.ArrowUpRight,{className:"h-3 w-3"}),t.jsx("span",{children:"Published"})]}):t.jsxs("div",{className:"flex items-center gap-1 rounded-full bg-amber-500/10 px-1.5 py-0.5 text-xs text-amber-600",children:[t.jsx(E.Clock,{className:"h-3 w-3"}),t.jsx("span",{children:"Draft"})]})})]}),t.jsx(Ge,{permissions:[je.RESTORE_REVISION,je.DELETE_REVISION],children:e.uid!=="current"&&t.jsx(Ii,{revision:e,onRestore:n,onDelete:a})})]})}function Ii({revision:e,onRestore:s,onDelete:n}){return t.jsxs(o.DropdownMenu,{children:[t.jsx(o.DropdownMenuTrigger,{asChild:!0,children:t.jsxs(o.Button,{variant:"ghost",size:"icon",className:"h-7 w-7 -mr-1",children:[t.jsx(E.MoreHorizontal,{className:"h-4 w-4"}),t.jsx("span",{className:"sr-only",children:"More options"})]})}),t.jsxs(o.DropdownMenuContent,{align:"end",className:"text-xs",children:[t.jsx(Ge,{permission:je.RESTORE_REVISION,children:t.jsxs(o.DropdownMenuItem,{onClick:s,className:"cursor-pointer",children:[t.jsx(E.Undo2,{className:"mr-2 h-4 w-4"}),t.jsx("span",{children:"Restore this version"})]})}),t.jsx(Ge,{permission:je.DELETE_REVISION,children:e.uid!=="current"&&t.jsxs(t.Fragment,{children:[t.jsx(o.DropdownMenuSeparator,{}),t.jsxs(o.DropdownMenuItem,{onClick:n,className:"cursor-pointer text-destructive",children:[t.jsx(E.Trash,{className:"mr-2 h-4 w-4"}),t.jsx("span",{children:"Delete this version"})]})]})})]})]})}function _i({open:e,onOpenChange:s,revision:n,onRestore:a,isRestoring:r}){const{data:i}=et((n==null?void 0:n.currentEditor)||""),l=(i==null?void 0:i.name)||"Unknown";return n?t.jsx(o.Dialog,{open:e,onOpenChange:c=>{r||s(c)},children:t.jsxs(o.DialogContent,{className:"sm:max-w-md",children:[t.jsxs(o.DialogHeader,{children:[t.jsx(o.DialogTitle,{children:"Restore Revision"}),t.jsxs(o.DialogDescription,{children:["You are about to restore to revision ",n.uid.substring(0,8)," ","from ",Ct.format(n.createdAt,"MMM d, yyyy 'at' h:mm a")," by"," ",l]})]}),t.jsx("div",{className:"py-2",children:t.jsx("p",{className:"text-sm text-muted-foreground",children:"How would you like to handle your current edits?"})}),t.jsxs(o.DialogFooter,{className:"flex flex-col sm:flex-row gap-2",children:[t.jsx(o.Button,{variant:"outline",className:"sm:flex-1",onClick:()=>a(!1),disabled:r,children:r?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mr-2 h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent"}),"Saving as draft..."]}):t.jsxs(t.Fragment,{children:[t.jsx(E.CloudOff,{className:"mr-2 h-4 w-4"}),"Save as draft"]})}),t.jsx(o.Button,{variant:"default",className:"sm:flex-1",onClick:()=>a(!0),disabled:r,children:r?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mr-2 h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent"}),"Discarding current..."]}):t.jsxs(t.Fragment,{children:[t.jsx(E.Undo2,{className:"mr-2 h-4 w-4"}),"Discard current"]})})]})]})}):null}function Di({open:e,onOpenChange:s,revision:n,onDelete:a,isDeleting:r}){const{data:i}=et((n==null?void 0:n.currentEditor)||""),l=(i==null?void 0:i.name)||"Unknown";return n?t.jsx(o.Dialog,{open:e,onOpenChange:c=>{r||s(c)},children:t.jsxs(o.DialogContent,{className:"sm:max-w-md",children:[t.jsxs(o.DialogHeader,{children:[t.jsx(o.DialogTitle,{children:"Delete Revision"}),t.jsxs(o.DialogDescription,{children:["You are about to delete revision ",n.uid.substring(0,8)," from"," ",Ct.format(n.createdAt,"MMM d, yyyy 'at' h:mm a")," by"," ",l]})]}),t.jsx("div",{className:"py-2",children:t.jsx("p",{className:"text-sm text-muted-foreground",children:"This action cannot be undone. Are you sure you want to proceed?"})}),t.jsxs(o.DialogFooter,{className:"flex flex-col sm:flex-row gap-2",children:[t.jsx(o.Button,{variant:"outline",className:"sm:flex-1",onClick:()=>s(!1),disabled:r,children:"Cancel"}),t.jsx(o.Button,{variant:"destructive",className:"sm:flex-1",onClick:a,disabled:r,children:r?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mr-2 h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent"}),"Deleting..."]}):t.jsxs(t.Fragment,{children:[t.jsx(E.Trash,{className:"mr-2 h-4 w-4"}),"Delete Revision"]})})]})]})}):null}const Bi=()=>{const e=re(),s=J();return D.useQuery({queryKey:[Y,L.GET_CHANGES],queryFn:async()=>s(e,{action:L.GET_CHANGES})})},Mi=({currentEditor:e})=>{const{data:s}=et(e);return s==null?void 0:s.name};function Oi({showModal:e=!1,onClose:s=()=>console.log("Cancelled")}){const[n,a]=f.useState([]),{data:r,isFetching:i}=Bi(),{data:l}=Pe(),c=f.useCallback(S=>{var P;return(P=m.find(l,{key:S}))==null?void 0:P.hasSlug},[l]),u=f.useMemo(()=>m.filter(l,S=>!c(S.key)).map(S=>S.key),[c,l]),d=f.useMemo(()=>m.filter(r,S=>!u.includes(S.pageType)),[r,u]),h=f.useMemo(()=>m.filter(r,S=>u.includes(S.pageType)),[r,u]),g=f.useMemo(()=>m.find(r,{pageType:"theme",id:"THEME"}),[r]),{mutate:b,isPending:y}=Ys();f.useEffect(()=>{const S=m.map(m.filter(r,{online:!0}),"id");g&&S.push(g==null?void 0:g.id),a(S)},[r,g]);const p=n.length===(r==null?void 0:r.length),w=S=>{a(P=>m.includes(P,S)?m.filter(P,O=>O!==S):m.concat(P,S))},v=()=>{a(p?[]:m.map(r,"id"))},N=()=>{b({ids:m.uniq(n)},{onSuccess:()=>{s(),Dt("CENTER_CENTER")}})},C=S=>{if(S==="theme")return"Theme";const P=m.find(l,{key:S});return P?P==null?void 0:P.name:S},B=f.useMemo(()=>{const S=[{label:"Updated",top:"pt-2"},...m.orderBy(m.filter(d,{online:!0}),"pageType"),...m.orderBy(m.filter(h,{online:!0}),"pageType")].filter(z=>z.pageType!=="theme"),P=[{label:"Offline",top:"pt-6"},...m.orderBy(m.filter(d,{online:!1}),"pageType"),...m.orderBy(m.filter(h,{online:!1}),"pageType")],O=g?[{label:"Theme",top:"pt-6"},g]:[];return[...S,...O,...P]},[d,h,g]);return t.jsx(o.Dialog,{open:e,onOpenChange:y?()=>{}:s,children:t.jsxs(o.DialogContent,{className:"max-w-4xl max-h-[80%] flex flex-col",children:[t.jsxs(o.DialogHeader,{children:[t.jsx(o.DialogTitle,{children:"Publish changes"}),t.jsx(o.DialogDescription,{className:"text-xs",children:"Select the pages you want to publish. Click publish when you're done."})]}),t.jsx("div",{className:"relative h-full max-h-full -mx-4 overflow-y-auto no-scrollbar",children:i?t.jsxs("div",{className:"px-1 space-y-2",children:[t.jsx("div",{className:"w-full h-6 mt-2 bg-gray-200 rounded animate-pulse"}),t.jsx("div",{className:"w-full h-6 bg-gray-200 rounded animate-pulse"}),t.jsx("div",{className:"w-full h-6 bg-gray-200 rounded animate-pulse"}),t.jsx("div",{className:"w-full h-6 bg-gray-200 rounded animate-pulse"})]}):t.jsxs("table",{className:"w-full text-xs text-left text-gray-500 rtl:text-right dark:text-gray-400",children:[t.jsx("thead",{className:"text-gray-700 border-b bg-gray-50 dark:bg-gray-700 dark:text-gray-400",children:t.jsxs("tr",{children:[t.jsxs("th",{scope:"col",className:"px-6 py-3 flex items-center gap-x-2 w-[1 50px]",children:[t.jsx("input",{checked:p,onClick:S=>{S.stopPropagation(),v()},type:"checkbox",className:"mt-1 rounded cursor-pointer focus:outline-none focus:ring-0"}),"Name"]}),t.jsx("th",{scope:"col",className:"px-2 py-3 w-[100px]",children:"Language"}),t.jsx("th",{scope:"col",className:"px-2 py-3 w-[100px]",children:"Type"}),t.jsx("th",{scope:"col",className:"px-4 py-3 w-[150px] text-right",children:"Status"})]})}),t.jsx("tbody",{children:m.map(B,S=>S.label?t.jsx("tr",{children:t.jsxs("td",{colSpan:4,className:`px-6 py-2 text-xs font-medium text-gray-800 relative ${S.top}`,children:[t.jsx("div",{className:"absolute inset-0 flex items-center left-6",children:t.jsx("div",{className:"w-full order-gray-300"})}),t.jsx("div",{className:"relative flex justify-start",children:t.jsx("span",{className:"pr-2 bg-gray-50",children:S.label})})]})},"separator"):t.jsxs("tr",{className:"border-b group hover:bg-gray-50 last:border-b-0",children:[t.jsxs("td",{scope:"row",className:"flex items-center px-6 py-2 text-gray-900 whitespace-nowrap dark:text-white gap-x-1",children:[t.jsx("input",{checked:m.includes(n,S==null?void 0:S.id),onClick:P=>{P.stopPropagation(),w(S==null?void 0:S.id)},type:"checkbox",className:"rounded cursor-pointer focus:outline-none focus:ring-0"})," ",c(S.pageType)?t.jsx(E.File,{className:"w-4 h-4"}):t.jsx(E.GlobeIcon,{className:"w-4 h-4"}),S.name,S.slug&&t.jsxs("span",{className:"text-xs text-gray-500",children:["(",S.slug,")"]}),S.currentEditor&&t.jsx("div",{className:"flex items-center gap-x-1",children:t.jsxs("span",{className:"flex text-xs font-bold text-gray-500",children:[" ","-"," ",t.jsx(Mi,{currentEditor:S.currentEditor})," ","is editing"]})})]}),t.jsx("td",{className:"px-2",children:S.lang}),t.jsx("td",{className:"px-2",children:C(S==null?void 0:S.pageType)}),t.jsx("td",{className:"px-4 text-right",children:m.first(S.changes)||""})]},S==null?void 0:S.id))})]})}),t.jsxs(o.DialogFooter,{className:"mt-10",children:[t.jsx(o.Button,{disabled:y,variant:"outline",onClick:s,children:"Cancel"}),t.jsx(o.Button,{disabled:y||i||m.isEmpty(r),onClick:N,children:y?"Publishing...":"Publish"})]})]})})}const Gi=()=>{const e=J(),s=re();return D.useQuery({queryKey:[L.GET_WEBSITE_DATA],staleTime:1e3*60*5,queryFn:async()=>e(s,{action:L.GET_WEBSITE_DATA,data:{draft:!0}})})};function Ri({onClose:e}){const{data:s,isFetching:n}=Gi(),{mutateAsync:a,isPending:r}=mr(),i=He("settingComponent",null),l=m.debounce(async c=>(await a({data:c}),!0),300);return i?t.jsx(o.Dialog,{open:!0,onOpenChange:e,children:t.jsxs(o.DialogContent,{className:"w-full",children:[t.jsx(o.DialogHeader,{children:t.jsx(o.DialogTitle,{children:"Website Settings"})}),n?t.jsxs("div",{className:"w-full space-y-3 py-4",children:[t.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"}),t.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"}),t.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"}),t.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"}),t.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"}),t.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"})]}):t.jsx("div",{children:f.createElement(i,{data:s||{},onSave:r?()=>{}:l,cancel:r?()=>{}:e})})]})}):null}function na({children:e,content:s}){return t.jsx(o.TooltipProvider,{children:t.jsxs(o.Tooltip,{children:[t.jsx(o.TooltipTrigger,{asChild:!0,children:e}),t.jsx(o.TooltipContent,{side:"bottom",sideOffset:10,children:t.jsx("p",{children:s})})]})})}const Ui=()=>{const{selectedLang:e,fallbackLang:s}=q.useLanguages(),n=He("getPreviewUrl",async g=>g),[a,r]=f.useState(""),{data:i}=Te(),{data:l}=Ke(),{data:c}=Pe(),u=f.useMemo(()=>{var g;return(g=l==null?void 0:l.find(b=>(b==null?void 0:b.lang)===e))==null?void 0:g.slug},[e,l]),d=f.useCallback(g=>{var b;return(b=m.find(c,{key:g}))==null?void 0:b.hasSlug},[c]),h=e===s?"":e;return f.useEffect(()=>{(async()=>{if(typeof n=="function"){const g=!d(i==null?void 0:i.pageType),b=await n(g?`${h!==""?h+"/":""}${i==null?void 0:i.id}`:u||"");r(b)}else r("")})()},[n,u,i==null?void 0:i.pageType,d,i==null?void 0:i.id,h]),t.jsx(t.Fragment,{children:t.jsx("a",{href:a,target:"_blank",rel:"noopener noreferrer",children:t.jsxs(o.Button,{variant:"ghost",size:"sm",className:"gap-2",children:[t.jsx(E.Eye,{className:"h-4 w-4"})," ",ae.PREVIEW]})})})},Fi=()=>{const[e,s]=q.useRightPanel();return t.jsxs(t.Fragment,{children:[t.jsx(na,{content:ae.THEME,children:t.jsx(o.Button,{variant:e==="theme"?"outline":"ghost",size:"icon",className:"gap-2",onClick:()=>s(e==="theme"?"block":"theme"),children:t.jsx(E.Palette,{className:"h-4 w-4"})})}),t.jsx("div",{className:"h-4 w-px bg-gray-200 dark:bg-gray-700"})]})},qi=()=>{const[e,s]=f.useState(!1),{isLocked:n}=es(),{savePage:a,saveState:r}=q.useSavePage();f.useEffect(()=>{const h=g=>{r==="UNSAVED"&&(g.preventDefault(),g.returnValue=!1)};return r==="UNSAVED"&&window.addEventListener("beforeunload",h),()=>{window.removeEventListener("beforeunload",h)}},[r]);const i=f.useCallback(async()=>{s(!0),await a(!1)},[a]);f.useEffect(()=>{r==="SAVED"&&s(!1)},[r]);const l=f.useMemo(()=>{if(r==="SAVED"||r==="UNSAVED")return r;if(r==="SAVING")return e?r:"SAVED"},[e,r]),{buttonIcon:c,buttonClass:u,tooltipContent:d}=f.useMemo(()=>{switch(l){case"UNSAVED":return{tooltipContent:ae.SAVEDRAFT,buttonIcon:t.jsx(E.Save,{className:"h-4 w-4"}),buttonClass:"flex items-center gap-x-1 leading-tight"};case"SAVING":return{tooltipContent:ae.SAVING,buttonIcon:t.jsx(E.Loader,{className:"h-4 w-4 animate-spin"}),buttonClass:"flex items-center gap-x-1 leading-tight"};case"SAVED":return{tooltipContent:ae.SAVED,buttonIcon:t.jsx(E.CheckCircle,{className:"h-4 w-4"}),buttonClass:"text-green-500 flex items-center gap-x-1 leading-tight"}}},[l]);return n?null:t.jsxs(o.Button,{size:"sm",variant:"ghost",onClick:i,className:u,children:[c," ",d]})},zi=()=>{const{selectedLang:e}=q.useLanguages(),{data:s}=At(),{data:n}=Ke(),[a,r]=f.useState(!1),[i,l]=f.useState(!1),[c,u]=f.useState(null),{data:d}=Te(),{mutate:h,isPending:g}=Ys(),{buttonText:b,buttonClassName:y,isPublished:p}=f.useMemo(()=>{const N=d&&(d==null?void 0:d.online);return{buttonClassName:N?"hover:bg-green-600 bg-green-500":"",isPublished:N,buttonText:N?ae.PUBLISHED:ae.PUBLISH}},[d]),w=async()=>{const N=[s==null?void 0:s.id,s==null?void 0:s.primaryPage];h({ids:m.compact(N)},{onSuccess:()=>Dt("TOP_RIGHT")})},v=f.useMemo(()=>m.map(n??[],"id"),[n]);return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex",children:[t.jsxs(o.Button,{size:"sm",onClick:w,disabled:g||!(d!=null&&d.id),className:`relative flex items-center gap-1 overflow-hidden rounded-r-none text-white transition-all duration-300 ease-in-out ${y}`,onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),children:[t.jsx("span",{className:`flex items-center transition-transform duration-300 ease-in-out ${i?"-translate-y-10":""}`,children:p?t.jsx(E.Send,{className:"h-4 w-4"}):t.jsx(E.Rocket,{className:"h-4 w-4"})}),t.jsx("span",{className:`absolute inset-0 left-3 flex items-center transition-transform duration-300 ease-in-out ${i?"":"translate-y-10"}`,children:p?t.jsx(E.Rocket,{className:"h-4 w-4"}):t.jsx(E.Send,{className:"h-4 w-4"})}),t.jsx("span",{children:b}),e?`(${m.upperCase(e)})`:""]}),t.jsxs(o.DropdownMenu,{children:[t.jsx(o.DropdownMenuTrigger,{asChild:!0,children:t.jsx(o.Button,{size:"sm",disabled:g||!(d!=null&&d.id),className:`rounded-l-none border-l border-white/50 px-2 text-white ${y}`,children:t.jsx(E.ChevronDown,{className:"h-4 w-4"})})}),t.jsxs(o.DropdownMenuContent,{align:"end",className:"w-52",children:[t.jsxs(o.DropdownMenuItem,{disabled:g,className:"cursor-pointer text-xs",onClick:()=>h({ids:v},{onSuccess:()=>Dt("TOP_RIGHT")}),children:[ae.PUBLISH," with translation pages"]}),!p&&t.jsxs(o.DropdownMenuItem,{disabled:g,className:"cursor-pointer text-xs",onClick:()=>h({ids:[d==null?void 0:d.id]},{onSuccess:()=>Dt("TOP_RIGHT")}),children:[ae.PUBLISH," page"]}),t.jsxs(o.DropdownMenuItem,{onClick:()=>r(!0),className:"cursor-pointer text-xs",children:[ae.OPEN," publish menu"]}),p&&t.jsxs(o.DropdownMenuItem,{onClick:()=>u(s),className:"cursor-pointer text-xs",children:[ae.UNPUBLISH," page ",e?`(${m.upperCase(e)})`:""]})]})]})]}),t.jsx(Oi,{showModal:a,onClose:()=>r(!1)}),c&&t.jsx(bs,{page:c,onClose:()=>u(null)})]})},$i=()=>{const e=He("settingComponent",null),[s,n]=f.useState(!1);return e?t.jsxs(t.Fragment,{children:[t.jsx(na,{content:ae.WEBSITEDATA,children:t.jsx(o.Button,{variant:"ghost",size:"icon",className:"gap-2",onClick:()=>n(!0),children:t.jsx(E.Settings,{className:"h-4 w-4"})})}),s&&t.jsx(Ri,{onClose:()=>n(!1)}),t.jsx("div",{className:"h-4 w-px bg-gray-200 dark:bg-gray-700"})]}):null};function Vi(){const{isLocked:e}=es(),[s]=_e(),n=s.get("lang"),a=Rn(n);return e||!a?null:t.jsxs("div",{className:"flex items-center justify-end gap-1",children:[t.jsx(Pi,{}),t.jsx(Ge,{permission:je.EDIT_THEME,children:t.jsx(Fi,{})}),t.jsx(Ge,{permission:je.EDIT_SETTINGS,children:t.jsx($i,{})}),t.jsx(Ui,{}),t.jsx(Ge,{permission:je.SAVE_PAGE,children:t.jsx(qi,{})}),t.jsx(Ge,{permission:je.PUBLISH_PAGE,children:t.jsx(zi,{})})]})}function Hi(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 Ki=()=>{const{data:e}=At(),s=zn(),n=e==null?void 0:e.slug,a=!n;let r=window.location.origin+(n?n.endsWith("/")?n.slice(0,-1):n:"");s&&(r+=s);const l=(a?`Partial: ${e==null?void 0:e.name} `:Hi(s?`${n}${s}`:n)).replace(window.location.host,"");return t.jsxs("div",{className:"flex h-8 w-auto max-w-[600px] items-center rounded-md border border-gray-200 bg-white shadow-sm dark:border-gray-700 dark:bg-gray-800"+(a?" pr-2":""),children:[t.jsx(sn,{}),t.jsx("div",{className:"flex w-full items-center overflow-hidden",children:t.jsx("div",{className:`w-full overflow-hidden overflow-ellipsis whitespace-nowrap pl-1 font-mono text-xs ${a?"italic text-gray-400":"text-gray-500"}`,children:l===""?"/(Homepage)":l})}),!a&&t.jsx("a",{href:r,target:"_blank",rel:"noopener noreferrer",children:t.jsx("div",{className:"ml-2 mr-px flex-shrink-0 rounded-sm p-1.5 text-gray-500 hover:bg-gray-100 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-300",children:t.jsx(E.ExternalLink,{className:"h-4 w-4",strokeWidth:1})})})]})},Qi=()=>t.jsxs("div",{className:"flex h-full w-full items-center justify-between px-2",children:[t.jsx(Ei,{}),t.jsx(Ki,{}),t.jsx(Vi,{})]}),Wi=()=>{const e=re(),{aiContext:s}=Vs(),n=J();return f.useCallback(async(a,r,i,l)=>n(e,{action:L.ASK_AI,data:{type:a,prompt:r,blocks:i,context:s,lang:l}}),[e,s,n])},Yi=(e,s)=>s.map(n=>{if(m.has(e,n._type)){const a=In.getDefaultBlockProps(n._type);return{...a,...m.pick(n,[...m.keys(a),"_type","_id","_name","_parent","_bindings"]),...m.pickBy(n,(r,i)=>m.endsWith(i,"_attrs")),...n}}return n}),Ji=e=>{const s=In.useRegisteredChaiBlocks();return f.useMemo(()=>{if(!e||m.isEmpty(e))return{blocks:[]};const n=m.filter(e,a=>!m.includes(a==null?void 0:a._type,"@chai/"));return{blocks:Yi(s,n)}},[e,s])},gn={async getUILibraryBlock(e,s,n){const a=await s(n,{action:"GET_LIBRARY_ITEM",data:{id:e.id}}),r=m.get(a,"html",""),i=m.get(a,"blocks",[]);return m.isArray(i)?i:q.getBlocksFromHTML(r)},async getUILibraryBlocks(e,s,n){try{return(await s(n,{action:"GET_LIBRARY_ITEMS",data:{id:e.id}})).map(r=>({...r}))}catch(a){return console.error(a),[]}}},Xi=()=>{const e=re(),s=J();return D.useQuery({queryKey:[Y,"uiLibraries"],initialData:[],queryFn:async()=>{const a=(await s(e,{action:"GET_LIBRARIES"})).map(r=>({...r}));return a.forEach(r=>{q.registerChaiLibrary(r.id,{name:r.name,description:r.description,getBlocksList:i=>gn.getUILibraryBlocks(i,s,e),getBlock:({block:i})=>gn.getUILibraryBlock(i,s,e)})}),a}})},aa=()=>{const e=js(),s=J(),{user:n}=Ue(),a=n==null?void 0:n.id;return D.useQuery({queryKey:[Y,"permissions",a],queryFn:()=>s(e,{action:L.GET_ROLE_AND_PERMISSIONS,data:{userId:a}}),enabled:!!a})},Zi=()=>{const e=re(),s=J(),{setCurrentEditor:n}=es(),[,a]=vs();return{onSave:async({page:i,blocks:l})=>{try{const c=await s(e,{action:"UPDATE_PAGE",data:{id:i,blocks:l}});return c.code==="PAGE_LOCKED"?(n(c.editor),!0):(a(u=>({...u,lastSaved:new Date().toISOString()})),c)}catch(c){return console.error(c),new Error("Failed to save blocks")}}}},el=()=>{const{data:e}=Zt(),s=re(),n=J();return{getPartialBlocks:f.useCallback(async()=>{const a={};for(const r of e??[])m.isEmpty(r==null?void 0:r.slug)&&(a[r.id]={type:r.pageType,name:m.startCase(r.name??r.slug),description:""});return a},[e]),getPartialBlockBlocks:f.useCallback(async a=>{if(!a)return[];try{const r=await n(s,{action:"GET_DRAFT_PAGE",data:{id:a,draft:!0,editor:!1}});return m.filter(r.blocks,i=>m.has(i,"_id"))}catch(r){return console.error(r),[]}},[n,s])}},xn=ls.z.object({email:ls.z.string().email({message:"Please enter a valid email address"}),password:ls.z.string().min(6,{message:"Password must be at least 6 characters"})}),tl=()=>{const{setUser:e,logout:s}=Ue(),n=js(),[a,r]=f.useState(""),[i,l]=f.useState(""),[c,u]=f.useState({}),[d,h]=f.useState(!1),[g,b]=f.useState(""),y=D.useMutation({mutationFn:async v=>{b("");const N=await $s(n,{action:"LOGIN",data:v});if(!N.ok){const B=await N.json();throw new Error(B.error||"Login failed")}const C=await N.json();if(m.has(C,"id")&&m.has(C,"email")&&m.has(C,"accessToken")&&m.has(C,"refreshToken"))e(C);else throw s(),new Error("Something went wrong. Please try again.");return C},onSuccess:()=>{u({}),b("")},onError:v=>{u({email:" ",password:" "}),b(v.message||"Something went wrong")}}),p=async v=>{v.preventDefault(),u({});const N={email:a,password:i};try{const C=xn.parse(N);y.mutate(C)}catch(C){if(C instanceof ls.z.ZodError){const B=C.errors.reduce((S,P)=>{const O=P.path[0];return S[O]=P.message,S},{});u(B)}}},w=xn.safeParse({email:a,password:i}).success;return t.jsx("div",{className:"flex justify-center items-center min-h-screen bg-slate-50",children:t.jsxs(o.Card,{className:"w-full max-w-md",children:[t.jsxs(o.CardHeader,{children:[t.jsx(o.CardTitle,{className:"text-2xl",children:"Sign in"}),t.jsx(o.CardDescription,{children:"Enter your credentials to sign in to visual builder"})]}),t.jsx(o.CardContent,{children:t.jsxs("form",{onSubmit:p,className:"space-y-4",children:[t.jsxs("div",{className:"space-y-1",children:[t.jsx(o.Label,{htmlFor:"email",children:"Email"}),t.jsx(o.Input,{id:"email",placeholder:"you@example.com",type:"email",value:a,onChange:v=>r(v.target.value),className:c.email?"border-destructive":""}),c.email&&t.jsx("p",{className:"text-sm text-destructive",children:c.email})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsx(o.Label,{htmlFor:"password",children:"Password"}),t.jsxs("div",{className:"relative",children:[t.jsx(o.Input,{id:"password",placeholder:"Enter your password",type:d?"text":"password",value:i,onChange:v=>l(v.target.value),className:c.password?"border-destructive":""}),t.jsx("button",{type:"button",className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground",onClick:()=>h(!d),children:d?t.jsx(E.EyeOff,{className:"h-4 w-4"}):t.jsx(E.Eye,{className:"h-4 w-4"})})]}),c.password&&t.jsx("p",{className:"text-sm text-destructive",children:c.password})]}),t.jsx("div",{children:t.jsx("p",{className:"text-sm text-destructive",children:g})}),t.jsx(o.Button,{type:"submit",className:"w-full",disabled:!w||y.isPending,children:y.isPending?t.jsxs(t.Fragment,{children:[t.jsx(E.Loader2,{className:"mr-2 h-4 w-4 animate-spin"}),"Logging in..."]}):"Login"})]})}),t.jsxs(o.CardFooter,{className:"flex flex-col justify-center",children:[t.jsxs("p",{className:"text-sm text-muted-foreground",children:["Forgot your password?"," ",t.jsx("a",{target:"_blank",href:"https://chaibuilder.com/forgot-password",className:"text-primary hover:underline",children:"Reset password"})]}),t.jsx("br",{}),t.jsx("br",{}),t.jsxs("div",{className:"flex items-center border-t pt-2 px-10 gap-2",children:["Powered by"," ",t.jsxs("a",{target:"_blank",href:"https://chaibuilder.com",className:"text-primary hover:underline flex items-center gap-1",children:[t.jsx("img",{src:"https://ucarecdn.com/a82e256c-1cf2-4755-b65c-5d85e7652daa/-/preview/400x400",alt:"Chai Builder",className:"w-4 h-4 rounded uppercase font-bold"}),"Chai Builder"]})]})]})]})})};let Ds=tl;const sl=()=>f.useMemo(()=>Ds,[Ds]),nl=e=>{Ds=e},al=()=>{const e=sl();return t.jsx(f.Suspense,{fallback:t.jsx("div",{children:"Loading..."}),children:t.jsx(e,{})})},rl=({isActive:e,show:s})=>{const{data:n}=Ze();return!m.has(n,"languages")||!m.get(n,"languages",[]).length?null:t.jsx(o.Button,{size:"sm",onClick:s,variant:e?"default":"ghost",children:t.jsx(E.LanguagesIcon,{className:"w-4 h-4"})})},ra="lang",il={id:ra,label:"Languages",position:"top",panel:Xr,button:rl,view:"modal",width:400};function We({data:e,onSelect:s,dataType:n="value",disabled:a=!1}){const[r,i]=we.useState(!1),[l,c]=we.useState([]),[u,d]=we.useState(e);we.useEffect(()=>{r||c([]),d(e)},[e,r]);const h=p=>Array.isArray(p)?"array":typeof p=="object"&&p!==null?"object":"value",g=we.useCallback(p=>{const w=v=>n==="value"?v==="value"||v==="object":n==="array"?v==="array":v===n;p.type==="object"?(c(v=>[...v,p.key]),d(p.value)):w(p.type)&&(s([...l,p.key].join(".")),i(!1))},[l,s,n]),b=we.useCallback(()=>{if(l.length>0){const p=l.slice(0,-1);c(p),d(p.reduce((w,v)=>w[v],e))}},[l,e]),y=we.useMemo(()=>Object.entries(u).map(([p,w])=>({key:p,value:w,type:h(w)})).filter(p=>n==="value"?p.type==="value"||p.type==="object":n==="array"?p.type==="array"||p.type==="object":n==="object"?p.type==="object":!0),[u,n]);return t.jsxs(o.Popover,{open:r,onOpenChange:i,children:[t.jsxs(o.Tooltip,{children:[t.jsx(o.TooltipTrigger,{asChild:!0,children:t.jsx(o.PopoverTrigger,{asChild:!0,children:t.jsx(o.Button,{size:"sm",variant:"outline",className:"h-6 w-6 px-1 py-0 text-[9px] text-muted-foreground",role:"combobox","aria-expanded":r,disabled:a,children:t.jsx(E.DatabaseIcon,{className:"h-3 w-3"})})})}),t.jsx(o.TooltipContent,{children:"Add field"})]}),t.jsx(o.PopoverContent,{className:"w-[200px] z-[9999] p-0",children:t.jsxs(o.Command,{children:[t.jsx(o.CommandInput,{className:"border-none",placeholder:"Search..."}),t.jsxs(o.CommandList,{onWheel:p=>{try{p.preventDefault();const w=p.currentTarget;w.scrollTop+=p.deltaY}catch{p.preventDefault()}},children:[t.jsx(o.CommandEmpty,{children:"No option found."}),t.jsxs(o.CommandGroup,{children:[l.length>0&&t.jsxs(o.CommandItem,{onSelect:b,className:"flex items-center text-sm",children:[t.jsx(E.ChevronLeft,{className:"w-4 h-4 mr-2"}),"Back"]}),y.map(p=>t.jsxs(o.CommandItem,{onSelect:()=>g(p),className:"flex items-center justify-between",children:[t.jsx("span",{children:p.key}),t.jsxs("div",{className:"flex items-center gap-2",children:[n==="object"&&p.type==="object"&&t.jsx(o.Button,{size:"sm",variant:"ghost",className:"h-6 px-2 hover:bg-primary hover:text-primary-foreground",onClick:w=>{w.stopPropagation(),s([...l,p.key].join(".")),i(!1)},children:"Select"}),(p.type==="object"||p.type==="array")&&t.jsx("div",{className:"p-1 rounded hover:bg-muted cursor-pointer",children:t.jsx(E.ChevronRight,{className:"w-4 h-4 opacity-50"})})]})]},p.key))]})]})]})})]})}const ll=()=>{const{selectedLang:e}=q.useLanguages(),{data:s,isFetching:n}=Ke();return{data:f.useMemo(()=>m.find(s,{lang:e||""})||{},[s,e]),isFetching:n}},ol=()=>{var l;const s=(l=document.getElementById("canvas-iframe").contentDocument)==null?void 0:l.body.innerHTML;if(!s)return null;const a=new DOMParser().parseFromString(s,"text/html");a.querySelectorAll("style, script, link, svg").forEach(c=>c.remove()),a.querySelectorAll("*").forEach(c=>{Array.from(c.attributes).forEach(u=>c.removeAttribute(u.name))});const r=a.querySelectorAll("h1, h2, h3, h4, h5, h6, p");return Array.from(r).map(c=>`<${c.tagName.toLowerCase()}>${c.innerHTML}</${c.tagName.toLowerCase()}>`).join(" ").replace(/<p>Partial block. Double click to edit.<\/p>/,"")},kt=({keyword:e,onComplete:s,field:n})=>{const a=J(),r=re(),{selectedLang:i,fallbackLang:l}=q.useLanguages(),c=q.useBuilderProp("aiContext",""),{mutate:u,isPending:d}=D.useMutation({mutationFn:async()=>{const h=ol();return await a(r,{action:L.GENERATE_SEO_FIELD,data:{pageContext:c,dynamic:!1,field:n,lang:i||l,pageContent:h,keyword:e}})},onSuccess:h=>{s({fieldValue:h.field})},onError:h=>{s({fieldValue:null,error:h.message})}});return t.jsx(o.Button,{disabled:d,type:"button",className:"h-5 w-5",variant:"ghost",size:"sm",onClick:()=>u(),children:d?t.jsx(E.Loader2,{className:"h-3 w-3 animate-spin text-yellow-500"}):t.jsx(E.Sparkle,{className:"text-yellow-500"})})},cl=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),pn=e=>{if(!e.trim())return{isValid:!1,parsed:null,placeholders:[],error:{message:"JSON is empty"}};try{return{isValid:!0,parsed:JSON.parse(e),error:null,placeholders:[]}}catch{}const s=/{{([^{}]+)}}/g,n=[];let a=e,r;for(;(r=s.exec(e))!==null;){const i=r[0],l=r.index,c=`"__placeholder_${n.length}__"`;n.push({original:i,replaced:c,position:l}),a=a.replace(i,c)}try{return{isValid:!0,parsed:JSON.parse(a),error:null,placeholders:n}}catch(i){const l=i,c=l.message.match(/position (\d+)/),u=c?parseInt(c[1]):void 0;let d,h;if(u!==void 0){const g=a.substring(0,u).split(`
|
|
3
|
-
`);d=g.length,h=g[g.length-1].length+1}return{isValid:!1,parsed:null,placeholders:n,error:{message:l.message,line:d,column:h,position:u}}}},
|
|
1
|
+
"use strict";var er=Object.defineProperty;var cn=e=>{throw TypeError(e)};var tr=(e,s,n)=>s in e?er(e,s,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[s]=n;var As=(e,s,n)=>tr(e,typeof s!="symbol"?s+"":s,n),un=(e,s,n)=>s.has(e)||cn("Cannot "+n);var X=(e,s,n)=>(un(e,s,"read from private field"),n?n.call(e):s.get(e)),ge=(e,s,n)=>s.has(e)?cn("Cannot add the same private member more than once"):s instanceof WeakSet?s.add(e):s.set(e,n),fe=(e,s,n,a)=>(un(e,s,"write to private field"),a?a.call(e,n):s.set(e,n),n);const t=require("react/jsx-runtime"),m=require("lodash-es"),f=require("react"),Ie=require("jotai"),D=require("@tanstack/react-query"),V=require("sonner"),q=require("@chaibuilder/sdk"),o=require("@chaibuilder/sdk/ui"),Ct=require("date-fns"),E=require("lucide-react"),In=require("@chaibuilder/runtime"),ls=require("zod"),sr=require("react-dropzone"),nr=require("@chaibuilder/sdk/web-blocks");function ar(e){const s=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const n in e)if(n!=="default"){const a=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(s,n,a.get?a:{enumerable:!0,get:()=>e[n]})}}return s.default=e,Object.freeze(s)}const we=ar(f),ke={ab:"Abkhazian",aa:"Afar",af:"Afrikaans",ak:"Akan",sq:"Albanian",am:"Amharic",ar:"Arabic",an:"Aragonese",hy:"Armenian",as:"Assamese",av:"Avaric",ae:"Avestan",ay:"Aymara",az:"Azerbaijani",bm:"Bambara",ba:"Bashkir",eu:"Basque",be:"Belarusian",bn:"Bengali",bh:"Bihari",bi:"Bislama",bs:"Bosnian",br:"Breton",bg:"Bulgarian",my:"Burmese",ca:"Catalan",ch:"Chamorro",ce:"Chechen",ny:"Chichewa",zh:"Chinese","zh-Hans":"Chinese (Simplified)","zh-Hant":"Chinese (Traditional)",cv:"Chuvash",kw:"Cornish",co:"Corsican",cr:"Cree",hr:"Croatian",cs:"Czech",da:"Danish",dv:"Maldivian",nl:"Dutch",dz:"Dzongkha",en:"English",eo:"Esperanto",et:"Estonian",ee:"Ewe",fo:"Faroese",fj:"Fijian",fi:"Finnish",fr:"French",ff:"Fula, Pular",gl:"Galician",gd:"Gaelic (Scottish)",gv:"Manx",ka:"Georgian",de:"German",el:"Greek",kl:"Kalaallisut",gn:"Guarani",gu:"Gujarati",ht:"Haitian Creole",ha:"Hausa",he:"Hebrew",hz:"Herero",hi:"Hindi",ho:"Hiri Motu",hu:"Hungarian",is:"Icelandic",io:"Ido",ig:"Igbo",id:"Indonesian",ia:"Interlingua",ie:"Interlingue",iu:"Inuktitut",ik:"Inupiak",ga:"Irish",it:"Italian",ja:"Japanese",jv:"Javanese",kn:"Kannada",kr:"Kanuri",ks:"Kashmiri",kk:"Kazakh",km:"Khmer",ki:"Kikuyu",rw:"Kinyarwanda",rn:"Kirundi",ky:"Kyrgyz",kv:"Komi",kg:"Kongo",ko:"Korean",ku:"Kurdish",kj:"Kwanyama",lo:"Lao",la:"Latin",lv:"Latvian",li:"Limburgish",ln:"Lingala",lt:"Lithuanian",lu:"Luga-Katanga",lg:"Luganda, Ganda",lb:"Luxembourgish",mk:"Macedonian",mg:"Malagasy",ms:"Malay",ml:"Malayalam",mt:"Maltese",mi:"Maori",mr:"Marathi",mh:"Marshallese",mo:"Moldavian",mn:"Mongolian",na:"Nauru",nv:"Navajo",ng:"Ndonga",nd:"Northern Ndebele",ne:"Nepali",no:"Norwegian",nb:"Norwegian bokmål",nn:"Norwegian nynorsk",ii:"Sichuan Yi",oc:"Occitan",oj:"Ojibwe",cu:"Old Church Slavonic",or:"Oriya",om:"Oromo",os:"Ossetian",pi:"Pāli",ps:"Pashto, Pushto",fa:"Persian (Farsi)",pl:"Polish",pt:"Portuguese",pa:"Punjabi (Eastern)",qu:"Quechua",rm:"Romansh",ro:"Romanian",ru:"Russian",se:"Sami",sm:"Samoan",sg:"Sango",sa:"Sanskrit",sr:"Serbian",sh:"Serbo-Croatian",st:"Sesotho",tn:"Setswana",sn:"Shona",sd:"Sindhi",si:"Sinhalese",ss:"Swati",sk:"Slovak",sl:"Slovenian",so:"Somali",nr:"Southern Ndebele",es:"Spanish",su:"Sundanese",sw:"Swahili (Kiswahili)",sv:"Swedish",tl:"Tagalog",ty:"Tahitian",tg:"Tajik",ta:"Tamil",tt:"Tatar",te:"Telugu",th:"Thai",bo:"Tibetan",ti:"Tigrinya",to:"Tonga",ts:"Tsonga",tr:"Turkish",tk:"Turkmen",tw:"Twi",ug:"Uyghur",uk:"Ukrainian",ur:"Urdu",uz:"Uzbek",ve:"Venda",vi:"Vietnamese",vo:"Volapük",wa:"Wallon",cy:"Welsh",wo:"Wolof",fy:"Western Frisian",xh:"Xhosa",yi:"Yiddish",yo:"Yoruba",za:"Zhuang, Chuang",zu:"Zulu"},L={GENERATE_SEO_FIELD:"GENERATE_SEO_FIELD",UPDATE_PAGE_METADATA:"UPDATE_PAGE_METADATA",GET_BLOCK_ASYNC_PROPS:"GET_BLOCK_ASYNC_PROPS",ASK_AI:"ASK_AI",GET_DRAFT_PAGE:"GET_DRAFT_PAGE",CREATE_PAGE:"CREATE_PAGE",UPDATE_PAGE:"UPDATE_PAGE",DELETE_PAGE:"DELETE_PAGE",DUPLICATE_PAGE:"DUPLICATE_PAGE",CHANGE_SLUG:"CHANGE_SLUG",TAKE_OFFLINE:"TAKE_OFFLINE",PUBLISH_PAGE:"PUBLISH_PAGE",PUBLISH_CHANGES:"PUBLISH_CHANGES",ADD_NEW_LANGUAGE:"ADD_NEW_LANGUAGE",EDIT_LANGUAGE:"EDIT_LANGUAGE",DELETE_LANGUAGE:"DELETE_LANGUAGE",GET_CHANGES:"GET_CHANGES",GET_SERVER_BLOCK:"GET_SERVER_BLOCK",GET_LANGUAGE_PAGES:"GET_LANGUAGE_PAGES",GET_PROJECT_PAGES:"GET_PROJECT_PAGES",GET_WEBSITE_PAGES:"GET_WEBSITE_PAGES",UPDATE_WEBSITE_SETTINGS:"UPDATE_WEBSITE_SETTINGS",GET_COLLECTIONS:"GET_COLLECTIONS",GET_PAGE_TYPES:"GET_PAGE_TYPES",SEARCH_PAGES:"SEARCH_PAGES",GET_WEBSITE_DRAFT_SETTINGS:"GET_WEBSITE_DRAFT_SETTINGS",AI_CONTEXT:"AI_CONTEXT",GET_WEBSITE_DATA:"GET_WEBSITE_DATA",UPDATE_WEBSITE_DATA:"UPDATE_WEBSITE_DATA",GET_CHAI_USER:"GET_CHAI_USER",RELEASE_LOCK:"RELEASE_LOCK",GET_SEO_FIELDS:"GET_SEO_FIELDS",GET_BUILDER_PAGE_DATA:"GET_BUILDER_PAGE_DATA",GET_PAGE_REVISIONS:"GET_PAGE_REVISIONS",DELETE_PAGE_REVISION:"DELETE_PAGE_REVISION",RESTORE_PAGE_REVISION:"RESTORE_PAGE_REVISION",GET_ROLE_AND_PERMISSIONS:"GET_ROLE_AND_PERMISSIONS",UPSERT_LIBRARY_ITEM:"UPSERT_LIBRARY_ITEM",GET_LIBRARIES:"GET_LIBRARIES",GET_LIBRARY_ITEM:"GET_LIBRARY_ITEM",GET_LIBRARY_ITEMS:"GET_LIBRARY_ITEMS",DELETE_LIBRARY_ITEM:"DELETE_LIBRARY_ITEM",MARK_AS_TEMPLATE:"MARK_AS_TEMPLATE",UNMARK_AS_TEMPLATE:"UNMARK_AS_TEMPLATE",GET_TEMPLATES_BY_TYPE:"GET_TEMPLATES_BY_TYPE",GET_DYNAMIC_PAGES:"GET_DYNAMIC_PAGES",UPLOAD_ASSET:"UPLOAD_ASSET",DELETE_ASSET:"DELETE_ASSET",UPDATE_ASSET:"UPDATE_ASSET",GET_ASSETS:"GET_ASSETS",GET_ASSET:"GET_ASSET"},Y="chaibuilder";let rr=0;function dn(e,s){const n=`atom${++rr}`,a={toString(){return n}};return typeof e=="function"?a.read=e:(a.init=e,a.read=ir,a.write=lr),s&&(a.write=s),a}function ir(e){return e(this)}function lr(e,s,n){return s(this,typeof n=="function"?n(e(this)):n)}const or=Symbol(""),cr=e=>typeof(e==null?void 0:e.then)=="function";function ur(e=()=>{try{return window.localStorage}catch{return}},s){var n;let a,r;const i={getItem:(u,d)=>{var h,g;const b=p=>{if(p=p||"",a!==p){try{r=JSON.parse(p,s==null?void 0:s.reviver)}catch{return d}a=p}return r},y=(g=(h=e())==null?void 0:h.getItem(u))!=null?g:null;return cr(y)?y.then(b):b(y)},setItem:(u,d)=>{var h;return(h=e())==null?void 0:h.setItem(u,JSON.stringify(d,void 0))},removeItem:u=>{var d;return(d=e())==null?void 0:d.removeItem(u)}},l=u=>(d,h,g)=>u(d,b=>{let y;try{y=JSON.parse(b||"")}catch{y=g}h(y)});let c;try{c=(n=e())==null?void 0:n.subscribe}catch{}return!c&&typeof window<"u"&&typeof window.addEventListener=="function"&&window.Storage&&(c=(u,d)=>{if(!(e()instanceof window.Storage))return()=>{};const h=g=>{g.storageArea===e()&&g.key===u&&d(g.newValue)};return window.addEventListener("storage",h),()=>{window.removeEventListener("storage",h)}}),c&&(i.subscribe=l(c)),i}const dr=ur();function _n(e,s,n=dr,a){const r=dn(s);return r.onMount=l=>{l(n.getItem(e,s));let c;return n.subscribe&&(c=n.subscribe(e,l,s)),c},dn(l=>l(r),(l,c,u)=>{const d=typeof u=="function"?u(l(r)):u;return d===or?(c(r,s),n.removeItem(e)):d instanceof Promise?d.then(h=>(c(r,h),n.setItem(e,h))):(c(r,d),n.setItem(e,d))})}localStorage.removeItem("_chai_user");localStorage.removeItem("__chai__user");const Dn="__logged_in_user",mr=_n(Dn,null),Ue=()=>{const[e,s]=Ie.useAtom(mr),n=f.useCallback(()=>{s(null),localStorage.removeItem(Dn)},[s]),a=f.useMemo(()=>{if(!(e!=null&&e.expiresAt))return!1;if(!e||!(e!=null&&e.refreshToken))return!0;const r=Math.floor(Date.now()/1e3);return e.expiresAt-r<=0},[e]);return{isLoggedIn:!!e,isSessionExpired:a,user:e,setUser:s,logout:n}},$s=async(e,s,n={})=>await fetch(e,{method:"POST",headers:{"Content-Type":"application/json",...n},body:JSON.stringify(s)}),J=()=>{const{user:e,logout:s}=Ue(),n=D.useQueryClient(),a=e==null?void 0:e.accessToken;return f.useCallback(async(r,i,l={})=>{if(!a)return null;try{const c=m.get(i,"action","").toLowerCase(),u=await $s(r+(c?`?action=${c}`:""),i,{...l,Authorization:`Bearer ${a}`});if(u.status===401)return console.log("401 Response",u),n.invalidateQueries({queryKey:[Y]}),s(),null;if(!u.ok){const d=await u.json();throw console.error(`API Error (${u.status}):`,d),{status:u.status,statusText:u.statusText,...d,message:d.error||d.message||`Server error: ${u.status}`}}return await u.json()}catch(c){throw console.error("API request failed:",i,c),c}},[a,s,n])},Bn=()=>{const e=re(),s=D.useQueryClient(),n=J();return D.useMutation({mutationFn:async a=>n(e,{action:L.RELEASE_LOCK,data:a}),onSuccess:()=>{s.invalidateQueries({queryKey:[Y,L.GET_DRAFT_PAGE]})}})},Mn=()=>{const e=re(),s=D.useQueryClient(),n=J();return D.useMutation({mutationFn:async a=>n(e,{action:L.UPDATE_WEBSITE_SETTINGS,data:a}),onSuccess:(a,r)=>{var i;s.invalidateQueries({queryKey:[Y,L.GET_WEBSITE_DRAFT_SETTINGS]}),(i=r==null?void 0:r.settings)!=null&&i.theme||V.toast.success("Website settings updated successfully.")},onError:a=>{V.toast.error("Failed to update website settings",{description:a.message})}})},hr=()=>{const e=re(),s=D.useQueryClient(),n=J();return D.useMutation({mutationFn:async a=>n(e,{action:L.UPDATE_WEBSITE_DATA,data:a}),onSuccess:()=>{s.invalidateQueries({queryKey:[Y,L.GET_WEBSITE_DATA]}),V.toast.success("Website data updated successfully.")},onError:a=>{V.toast.error("Failed to update website data",{description:a.message})}})};function _e(){const[e,s]=f.useState(new URLSearchParams(window.location.search));return f.useEffect(()=>{const n=()=>{s(new URLSearchParams(window.location.search))};return window.addEventListener("popstate",n),()=>{window.removeEventListener("popstate",n)}},[]),[e,s]}const fr=Ie.atom({}),On=()=>Ie.useAtom(fr),gr=()=>{const[e]=_e(),s=e.get("page"),n=f.useRef(""),{mutate:a}=Bn();f.useEffect(()=>{!m.isEmpty(n.current)&&s!==n.current&&a({id:n.current}),n.current=s},[s,a,n])},He=(e,s)=>{const[n]=On();return f.useMemo(()=>m.get(n,e,s),[n,e,s])},re=()=>He("apiUrl","/chai/api"),js=()=>He("usersApiUrl","/chai/users"),Xt=()=>He("assetsApiUrl","/chai/assets"),Gn=()=>He("realtimeInstance",null),Ke=e=>{const s=re(),[n]=_e(),a=e??n.get("page"),r=J();return D.useQuery({queryKey:[Y,L.GET_LANGUAGE_PAGES,a],initialData:[],queryFn:async()=>{if(!a)return null;const i=await r(s,{action:L.GET_LANGUAGE_PAGES,data:{id:a}});return m.reverse(m.sortBy(i,"primaryPage"))},enabled:!!a})},Ze=()=>{const e=re(),s=J();return D.useQuery({queryKey:[Y,L.GET_WEBSITE_DRAFT_SETTINGS],initialData:{theme:{},fallbackLang:"en",languages:[]},queryFn:async()=>s(e,{action:L.GET_WEBSITE_DRAFT_SETTINGS,data:{draft:!0}})})},Rn=e=>{const{fallbackLang:s}=q.useLanguages(),{data:n}=Ze(),{data:a,isFetching:r}=Ke(),i=f.useMemo(()=>{const l={[s]:!0};return m.each(m.get(n,"languages"),c=>{const u=m.find(a,{lang:c});l[c]=!!u}),l},[s,a,n]);return r||m.isEmpty(e)||e&&i[e]},Vs=()=>{const e=D.useQueryClient(),{data:s}=D.useQuery({queryKey:[Y,L.AI_CONTEXT],initialData:"",queryFn:()=>"",staleTime:0});return{setAiContext:f.useCallback(a=>{e.setQueryData([Y,L.AI_CONTEXT],a)},[e]),aiContext:s}},Zt=()=>{const e=J(),s=re();return D.useQuery({queryKey:[Y,L.GET_WEBSITE_PAGES],staleTime:1e3*60*5,queryFn:async()=>e(s,{action:L.GET_WEBSITE_PAGES})||[],placeholderData:n=>n})},xr=Ie.atom({lastSaved:void 0}),vs=()=>Ie.useAtom(xr),Te=()=>{const[e]=_e(),s=e.get("page"),[n]=Un(),{data:a,isFetching:r}=Zt();return{data:f.useMemo(()=>({...m.find(a,{id:s})||{},metadata:n}),[a,s,n]),isFetching:r}},At=()=>{const[e]=_e(),s=e.get("lang")??"",{data:n,isFetching:a}=Ke();return{data:f.useMemo(()=>m.find(n,{lang:s})||{},[n,s]),isFetching:a}},pr=Ie.atom({}),Un=()=>Ie.useAtom(pr),et=e=>{const s=js(),n=J();return D.useQuery({queryKey:[Y,"chaiUserInfo",e],queryFn:async()=>await n(s,{action:L.GET_CHAI_USER,data:{userId:e}}),enabled:!m.isEmpty(e)})},yr=Ie.atom(void 0),Hs=Ie.atom({status:"checking",requestedBy:"",isTakeOverRequested:!1}),es=()=>{const[e]=_e(),s=e.get("page"),{user:n}=Ue(),[a,r]=Ie.useAtom(yr),[i]=Ie.useAtom(Hs),l=q.useChaiFeatureFlag("realtime-page-lock");return f.useMemo(()=>({isLocked:l?s&&i.status==="locked":s&&(n==null?void 0:n.id)!==a,currentEditor:a,setCurrentEditor:c=>r(c)}),[l,s,i.status,n==null?void 0:n.id,a,r])},jr=()=>{const e=Gn(),{data:s}=Te(),{user:n}=Ue(),a=s==null?void 0:s.id,[r,i]=Ie.useAtom(Hs),l=f.useRef(!1),c=q.useChaiFeatureFlag("realtime-page-lock");return f.useEffect(()=>{r.status==="locked"||!a||!(n!=null&&n.id)||!e||!c||l.current||setTimeout(()=>{l.current||(l.current=!0,e==null||e.listenEvent("TAKE_OVER_REQUESTED",u=>{(u==null?void 0:u.requesterUserId)!==(n==null?void 0:n.id)&&i({...r,requestedBy:u==null?void 0:u.requesterUserId})}))},1e3)},[r,e,i,a,c,n==null?void 0:n.id]),f.useEffect(()=>{if(!c||!e||!a||!(n!=null&&n.id))return;async function u(){const d=await(e==null?void 0:e.joinPage(a,n==null?void 0:n.id));i({...r,status:d?"editing":"locked",requestedBy:""})}return u(),()=>{e==null||e.leavePage(a,n==null?void 0:n.id)}},[a,c]),{}},Fn=()=>{const e=Gn(),{data:s}=Te(),{user:n}=Ue(),a=s==null?void 0:s.id,[r,i]=Ie.useAtom(Hs),{saveState:l,savePage:c}=q.useSavePage(),u=D.useQueryClient(),d=f.useCallback(()=>{!e||!a||!(n!=null&&n.id)||(i({...r,isTakeOverRequested:!0}),e==null||e.requestTakeOver(a,n==null?void 0:n.id),e==null||e.listenEvent("TAKE_OVER_REQUEST_ACCEPTED",()=>{V.toast.success("Your Page Take Over Request Accepted",{position:"top-center"}),i({status:"editing",requestedBy:"",isTakeOverRequested:!1}),u.invalidateQueries({queryKey:[Y,L.GET_DRAFT_PAGE]})}),e==null||e.listenEvent("TAKE_OVER_REQUEST_REJECTED",()=>{i({...r,isTakeOverRequested:!1}),V.toast.warning("Your Page Take Over Request Rejected",{position:"top-center",closeButton:!0,duration:1/0})}))},[e,a,n==null?void 0:n.id,i,r,u]),h=f.useCallback(async()=>{!e||!a||!(n!=null&&n.id)||(l!=="SAVED"&&(c(),await new Promise(b=>setTimeout(b,1500))),e==null||e.acceptTakeOver(a,n==null?void 0:n.id),i({status:"locked",requestedBy:"",isTakeOverRequested:!1}))},[a,e,n==null?void 0:n.id,i,c,l]),g=f.useCallback(()=>{!e||!a||!(n!=null&&n.id)||(e==null||e.rejectTakeOver(a,n==null?void 0:n.id),i({status:"editing",requestedBy:"",isTakeOverRequested:!1}))},[a,e,n==null?void 0:n.id,i]);return{pageLock:r,requestTakeOver:d,acceptTakeOver:h,rejectTakeOver:g}},Ks=()=>{const{data:e}=Ze();return f.useMemo(()=>(e==null?void 0:e.fallbackLang)||"en",[e])},vr=Ie.atom(null),qn=()=>Ie.useAtom(vr),zn=()=>{const[e]=qn();return(e==null?void 0:e.slug)||""};function br(e,s){const[n,a]=f.useState(e);return f.useEffect(()=>{const r=setTimeout(()=>a(e),s);return()=>clearTimeout(r)},[e,s]),n}const wr=({query:e,uuid:s})=>{const{selectedLang:n,fallbackLang:a}=q.useLanguages(),{data:r}=Te(),i=r==null?void 0:r.pageType,l=re(),c=J(),{data:u,isFetching:d}=D.useQuery({queryKey:[L.GET_DYNAMIC_PAGES,e,i,s],initialData:[],queryFn:async()=>await c(l,{action:L.GET_DYNAMIC_PAGES,data:{query:e,pageType:i,uuid:s}})||[]}),h=f.useMemo(()=>n===""?u.filter(g=>g.lang===""||g.lang===a):u.filter(g=>g.lang===n),[n,a,u]);return{allLangPages:u,data:h,isFetching:d}},Sr=()=>{const{selectedLang:e,fallbackLang:s}=q.useLanguages(),[n,a]=qn(),[r,i]=f.useState(""),l=br(r,500),{allLangPages:c,data:u,isFetching:d}=wr({query:l}),h=f.useCallback(y=>a(y),[a]),g=f.useCallback(y=>i(y),[i]),b=f.useCallback(()=>{if(!n)return;const y=!(n!=null&&n.primaryPage),p=e.length===0,w=y?n==null?void 0:n.id:n==null?void 0:n.primaryPage,N=c.filter(C=>(C==null?void 0:C.primaryPage)===w||C.id===w).find(C=>p?C.lang===e||C.lang===s:C.lang===e);a(N||n)},[n,e,c,a,s]);return{isPending:d,dynamicPage:n,searchQuery:r,selectedLang:e,dynamicPages:u,allLangPages:c,updateDynamicPage:h,updateSearchQuery:g,onChangeLanguage:b}},$n=()=>{const[e]=_e(),s=e.get("page"),n=re(),{setAiContext:a}=Vs(),{setCurrentEditor:r}=es(),[,i]=vs(),[,l]=Un(),c=J();return D.useQuery({queryKey:[Y,L.GET_DRAFT_PAGE,s],staleTime:1/0,gcTime:1/0,queryFn:async()=>{r("");const u=await c(n,{action:L.GET_DRAFT_PAGE,data:{id:s,draft:!0}});r(u.currentEditor);const d=u.blocks??[],h=m.find(d,{_type:"@chai/ai-context"});return a(m.get(h,"_value","")||""),i(g=>({...g,lastSaved:u.lastSaved})),l(m.get(u,"metadata",{})),d},enabled:!!s})},Qs=()=>{const{data:e}=Te(),{data:s}=At(),n=re(),a=J(),r=Ks(),i=zn();return D.useQuery({queryKey:[Y,L.GET_BUILDER_PAGE_DATA,s==null?void 0:s.id,i],initialData:{},queryFn:async()=>a(n,{action:L.GET_BUILDER_PAGE_DATA,data:{pageType:e==null?void 0:e.pageType,lang:(s==null?void 0:s.lang)||r,dynamic:e==null?void 0:e.dynamic,pageProps:{slug:(s==null?void 0:s.slug)+i,searchParams:{},pageType:s==null?void 0:s.pageType,fallbackLang:r,lastSaved:s.lastSaved,pageId:e.id,primaryPageId:s.primaryPage||e.id,pageBaseSlug:s==null?void 0:s.slug,dynamic:e==null?void 0:e.dynamic,languagePageId:s.id}}}),enabled:!!(s!=null&&s.pageType)})},Er=({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 flex items-center gap-1 text-xs font-light text-gray-500",children:t.jsxs(o.Tooltip,{children:[t.jsx(o.TooltipTrigger,{children:t.jsx(E.LockIcon,{className:"h-3 w-3"})}),t.jsx(o.TooltipContent,{children:t.jsxs("p",{children:[n.name," is editing"]})})]})})},mn=({userId:e})=>{const{data:s}=et(e);return(s==null?void 0:s.name)||"Unknown"};function Nr({avatar:e,name:s,email:n,lastSaved:a,onTakeOver:r,pageLock:i,realtimePageLockEnabled:l}){const[c,u]=f.useState(!1),d=()=>{u(!1),r()};return t.jsx("div",{className:"fixed bottom-0 left-0 right-0 top-[50px] z-[20] flex w-screen items-center justify-center bg-black/30 backdrop-blur-sm",children:t.jsxs(o.Card,{className:"mx-auto w-full max-w-md",children:[t.jsx(o.CardHeader,{className:"space-y-1",children:t.jsxs(o.CardTitle,{className:"flex items-center gap-2 text-2xl",children:[t.jsx(E.LockIcon,{className:"h-6 w-6 text-yellow-500"}),"Page locked for editing"]})}),t.jsx(o.CardContent,{className:"grid gap-4",children:t.jsxs("div",{children:[t.jsxs("div",{className:"flex items-center space-x-4",children:[e?t.jsx("img",{src:e,alt:s,className:"h-12 w-12 rounded-full border border-gray-300"}):t.jsx(E.UserIcon,{className:"h-12 w-12 rounded-full border border-gray-300 p-2"}),t.jsxs("div",{className:"space-y-1",children:[t.jsx("h3",{className:"font-semibold",children:s}),n&&t.jsx("p",{className:"text-sm text-muted-foreground",children:n}),a&&t.jsxs("p",{className:"text-sm text-muted-foreground",children:["Last saved:"," ",Ct.formatDistanceToNow(new Date(a),{addSuffix:!0})]})]})]}),t.jsx("div",{className:"mt-4 text-sm",children:t.jsx("p",{children:"This user is currently editing the page. You cannot make changes."})})]})}),t.jsx(o.CardFooter,{children:l?t.jsx(o.Button,{disabled:i.isTakeOverRequested,onClick:d,className:"w-full",variant:"destructive",children:i.isTakeOverRequested?"Page take is requested.":"Request take over"}):t.jsxs(o.AlertDialog,{open:c,onOpenChange:u,children:[t.jsx(o.AlertDialogTrigger,{asChild:!0,children:t.jsxs("span",{className:"flex flex-col items-center",children:[t.jsx(o.Button,{className:"w-full",variant:"destructive",children:"Take over"}),t.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:"If you need to edit, you can take over the lock, but be aware that the other user might lose unsaved changes."})]})}),t.jsxs(o.AlertDialogContent,{className:"z-[99]",children:[t.jsxs(o.AlertDialogHeader,{children:[t.jsx(o.AlertDialogTitle,{children:"Are you sure you want to take over?"}),t.jsxs(o.AlertDialogDescription,{children:[t.jsxs("span",{className:"flex items-center space-x-2 text-yellow-500",children:[t.jsx(E.AlertTriangleIcon,{className:"h-5 w-5"}),t.jsx("span",{children:"This action might cause the other user to lose unsaved changes."})]}),t.jsx("br",{}),t.jsxs("span",{className:"mt-2",children:["By taking over, you will become the active editor of this page, and ",s," will lose their editing access."]})]})]}),t.jsxs(o.AlertDialogFooter,{children:[t.jsx(o.AlertDialogCancel,{children:"Cancel"}),t.jsx(o.AlertDialogAction,{onClick:d,children:"Yes, Take Over"})]})]})]})})]})})}const Cr=()=>{const{pageLock:e,acceptTakeOver:s,rejectTakeOver:n}=Fn();return t.jsx("div",{className:"fixed bottom-0 left-0 right-0 top-[50px] z-[20] flex w-screen items-center justify-center bg-black/30 backdrop-blur-sm",children:t.jsxs(o.Card,{className:"mx-auto w-full max-w-md",children:[t.jsx(o.CardHeader,{className:"space-y-1",children:t.jsxs(o.CardTitle,{className:"flex items-center gap-2 text-2xl",children:[t.jsx(E.AccessibilityIcon,{className:"h-6 w-6 text-yellow-500"}),t.jsx(mn,{userId:e==null?void 0:e.requestedBy})," has requested to take over this page"]})}),t.jsx(o.CardContent,{className:"grid gap-4",children:t.jsx("div",{children:t.jsx("div",{className:"mt-4 text-sm",children:t.jsxs("p",{children:[t.jsx(mn,{userId:e==null?void 0:e.requestedBy})," has requested to take over this page. Do you want to accept the request?"]})})})}),t.jsxs(o.CardFooter,{className:"flex items-center justify-end gap-2",children:[t.jsx(o.Button,{onClick:s,children:"Yes"}),t.jsx(o.Button,{variant:"outline",onClick:n,children:"No"})]})]})})},Ar=()=>{const{isLocked:e,currentEditor:s}=es(),{data:n}=et(s),[a]=_e(),r=a.get("page"),{mutate:i}=Bn(),{isFetching:l}=$n(),[c]=vs(),{pageLock:u,requestTakeOver:d}=Fn(),h=q.useChaiFeatureFlag("realtime-page-lock"),g=f.useCallback(()=>{h?d():i({id:r})},[r,i,d,h]);return h&&(u!=null&&u.requestedBy)?t.jsx(Cr,{}):(h?u.status!=="locked":!e||l)?t.jsx("div",{className:""}):t.jsx(Nr,{...n,name:(n==null?void 0:n.name)||"Unknown User",email:(n==null?void 0:n.email)||"",lastSaved:(c==null?void 0:c.lastSaved)||"",onTakeOver:g,pageLock:u,realtimePageLockEnabled:h})},Tr=()=>{const[e,s]=_e(),n=e.get("lang"),a=Rn(n),{setSelectedLang:r}=q.useLanguages(),i=()=>{const c=new URLSearchParams(window.location.search);c.delete("lang");const u=c.toString(),d=`${window.location.pathname}${u?`?${u}`:""}`;window.history.pushState({},"",d),s(c),r(""),window.dispatchEvent(new PopStateEvent("popstate"))};if(a)return null;const l=m.get(ke,n);return t.jsx("div",{className:"fixed bottom-0 left-0 right-0 top-12 z-[20] flex w-screen items-center justify-center bg-black/30 backdrop-blur-sm",children:t.jsxs(o.Card,{className:"mx-auto w-full max-w-md",children:[t.jsx(o.CardHeader,{className:"space-y-1",children:t.jsxs(o.CardTitle,{className:"flex items-center gap-2 text-2xl",children:[t.jsx(E.LockIcon,{className:"h-6 w-6 text-yellow-500"}),'Page missing for "',l,'" language.']})}),t.jsx(o.CardContent,{className:"grid gap-4",children:t.jsxs("div",{children:['Page is not available in the "',l,'" language. Either create the page in the "',l,'" language or switch to the base language.']})}),t.jsx(o.CardFooter,{children:t.jsx(o.Button,{onClick:i,className:"w-full",variant:"destructive",children:"Switch to default language"})})]})})},Pr=e=>{const s=re(),n=J();return D.useMutation({mutationFn:async a=>n(s,{action:L.UPSERT_LIBRARY_ITEM,data:a}),onSuccess:a=>{e(a)},onError:a=>{console.error("Error saving block:",a),V.toast.error("Failed to save block",{description:a instanceof Error?a.message:"Unknown error"})}})},kr=e=>{const s=re(),n=J();return D.useQuery({queryKey:[Y,"uiBlockDetails",e],enabled:!!e,queryFn:async()=>{if(!e)return null;try{return await n(s,{action:L.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})},Lr=e=>{const s=re(),n=J();return D.useMutation({mutationFn:async a=>n(s,{action:L.DELETE_LIBRARY_ITEM,data:{id:a}}),onSuccess:()=>{e()},onError:a=>{console.error("Error deleting block:",a),V.toast.error("Failed to delete block",{description:a instanceof Error?a.message:"Unknown error"})}})},Ir=({blockId:e,libBlockId:s,isOpen:n,onClose:a,blockName:r,trigger:i})=>{const[l,c]=f.useState(!1),u=q.useUpdateBlocksPropsRealtime(),d=Lr(()=>{u([e],{_libBlockId:void 0}),V.toast.success("Block deleted successfully"),c(!1),a()}),h=()=>{c(!0),d.mutate(s)},g=t.jsxs(o.Button,{type:"button",variant:"destructive",size:"sm",onClick:b=>b.preventDefault(),disabled:l,children:[t.jsx(E.Trash2,{className:"h-4 w-4 mr-2"}),"Delete"]});return t.jsxs(o.Popover,{open:n,onOpenChange:b=>!b&&a(),children:[t.jsx(o.PopoverTrigger,{asChild:!0,children:i||g}),t.jsx(o.PopoverContent,{className:"w-72 p-4 z-[9999]",sideOffset:5,align:"center",children:t.jsxs("div",{className:"space-y-3",children:[t.jsx("h4",{className:"font-medium",children:"Delete Block"}),t.jsxs("p",{className:"text-sm",children:["Are you sure you want to delete the block",t.jsxs("span",{className:"font-medium",children:[' "',r,'"']}),"?"]}),t.jsx("p",{className:"text-xs text-muted-foreground",children:"This block will be permanently removed from the library. This action cannot be undone."}),t.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[t.jsx(o.Button,{type:"button",variant:"outline",size:"sm",onClick:a,disabled:l,children:"Cancel"}),t.jsx(o.Button,{type:"button",variant:"destructive",size:"sm",onClick:h,disabled:l,children:l?"Deleting...":"Delete"})]})]})})]})},_r=({blockId:e,libBlockId:s,blockName:n,size:a="sm",className:r="",close:i})=>{const[l,c]=f.useState(!1);return t.jsx(Ir,{blockId:e,libBlockId:s,isOpen:l,onClose:()=>{c(!1),i()},blockName:n,trigger:t.jsxs(o.Button,{type:"button",variant:"destructive",size:a,className:r,onClick:()=>c(!0),children:[t.jsx(E.Trash2,{className:"h-4 w-4 mr-2"}),"Delete"]})})},Dr=()=>{const e=re(),s=J(),n=D.useQueryClient(),{data:a=[],isLoading:r,error:i}=D.useQuery({queryKey:[Y,"library-groups"],queryFn:async()=>{try{return await s(e,{action:"GET_LIBRARY_GROUPS"})||[]}catch(u){return console.error("Error fetching library groups:",u),[]}},initialData:[]}),{mutateAsync:l,isPending:c}=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:[Y,"library-groups"]}),V.toast.success("Group created successfully")},onError:u=>{console.error("Error creating group:",u),V.toast.error("Failed to create group",{description:u instanceof Error?u.message:"Unknown error"})}});return{groups:a,isLoading:r,error:i,createGroup:l,isCreating:c}},Br=({value:e,onChange:s})=>{const[n,a]=f.useState(!1),[r,i]=f.useState(""),l=f.useRef(null),{groups:c}=Dr(),[u,d]=f.useState([{id:"hero",name:"Hero"},{id:"feature",name:"Feature"},{id:"footer",name:"Footer"},{id:"content",name:"Content"},{id:"testimonial",name:"Testimonial"},{id:"pricing",name:"Pricing"},{id:"login",name:"Login"},{id:"logos",name:"Logos"},{id:"about",name:"About"},{id:"banner",name:"Banner"},{id:"blog",name:"Blog"},{id:"careers",name:"Careers"},{id:"casestudy",name:"Casestudy"},{id:"changelog",name:"Changelog"},{id:"compare",name:"Compare"},{id:"contact",name:"Contact"},{id:"cta",name:"Cta"},{id:"faq",name:"Faq"},{id:"gallery",name:"Gallery"},{id:"integration",name:"Integration"},{id:"list",name:"List"},{id:"navbar",name:"Navbar"},{id:"product",name:"Product"},{id:"signup",name:"Signup"},{id:"stats",name:"Stats"},{id:"team",name:"Team"},{id:"timeline",name:"Timeline"}]),h=f.useMemo(()=>[...c,...u.filter(y=>!c.some(p=>p.id===y.id))],[c,u]),g=()=>{const y=r.trim();if(!y)return;const p={id:y,name:y};d(w=>[...w,p]),s(p.id),i(""),a(!1)};f.useEffect(()=>{n&&l.current&&l.current.focus()},[n]);const b=y=>{y.key==="Enter"&&(y.preventDefault(),g())};return f.useEffect(()=>{e&&!h.some(y=>y.id===e)&&s("")},[e,h,s]),n?t.jsxs("div",{className:"space-y-2",children:[t.jsx(o.Input,{ref:l,placeholder:"Enter new group name",value:r,onChange:y=>i(y.target.value),onKeyDown:b}),t.jsxs("div",{className:"flex justify-end gap-2",children:[t.jsx(o.Button,{variant:"outline",size:"sm",onClick:()=>a(!1),children:"Cancel"}),t.jsx(o.Button,{size:"sm",onClick:g,children:"Create"})]})]}):t.jsxs("div",{className:"flex gap-2",children:[t.jsxs("select",{className:"w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",value:e,onChange:y=>s(y.target.value),children:[t.jsx("option",{value:"",children:"Select a group"}),c.length>0&&t.jsx("optgroup",{label:"Library Groups",children:c.map(y=>t.jsx("option",{value:y.id,children:y.name},`lib-${y.id}`))}),u.length>0&&t.jsx("optgroup",{label:"Predefined Groups",children:u.filter(y=>!c.some(p=>p.id===y.id)).map(y=>t.jsx("option",{value:y.id,children:y.name},`local-${y.id}`))})]}),t.jsx(o.Button,{type:"button",size:"icon",variant:"outline",onClick:()=>a(!0),children:t.jsx(E.Plus,{className:"h-4 w-4"})})]})},Mr=10*1024*1024,Or=({value:e,onChange:s})=>{const[n,a]=f.useState(!1),r=f.useRef(null),i=f.useCallback(u=>{var h;const d=(h=u.target.files)==null?void 0:h[0];if(d){if(d.size>Mr){V.toast.error("File too large",{description:`Maximum file size is 10mb. Selected file is ${(d.size/1024/1024).toFixed(2)}MB.`}),r.current&&(r.current.value="");return}try{a(!0);const g=new FileReader;g.onloadend=()=>{s(g.result),a(!1)},g.readAsDataURL(d)}catch(g){console.error("Error reading file:",g),a(!1),V.toast.error("Failed to process image",{description:g instanceof Error?g.message:"Unknown error"})}}},[s]),l=()=>{s(""),r.current&&(r.current.value="")},c=()=>{var u;(u=r.current)==null||u.click()};return t.jsxs("div",{className:"space-y-2",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(o.Input,{type:"file",ref:r,onChange:i,accept:"image/*",className:"hidden"}),t.jsx(o.Button,{type:"button",variant:"outline",onClick:c,disabled:n,className:"w-full",children:n?t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsx("div",{className:"animate-spin h-4 w-4 border-2 border-current border-t-transparent rounded-full"}),"Uploading..."]}):t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsx(E.ImageIcon,{className:"h-4 w-4"}),"Select image"]})}),e&&t.jsx(o.Button,{type:"button",variant:"outline",size:"icon",onClick:l,children:t.jsx(E.X,{className:"h-4 w-4"})})]}),e&&t.jsx("div",{className:"rounded-md max-h-[200px] h-[200px] overflow-hidden border aspect-video",children:t.jsx("img",{src:e,alt:"Preview",className:"w-full h-full object-contain"})})]})},je={...q.PERMISSIONS,ADD_PAGE:"add_page",EDIT_PAGE:"edit_page",EDIT_SLUG:"edit_slug",DELETE_PAGE:"delete_page",CHANGE_PAGE_TYPE:"change_page_type",PUBLISH_PAGE:"publish_page",UNPUBLISH_PAGE:"unpublish_page",MARK_AS_TEMPLATE:"mark_as_template",UNMARK_AS_TEMPLATE:"unmark_as_template",ADD_PARTIAL:"add_partial",EDIT_PARTIAL:"edit_partial",DELETE_PARTIAL:"delete_partial",PUBLISH_PARTIAL:"publish_partial",UNPUBLISH_PARTIAL:"unpublish_partial",EDIT_SEO:"edit_seo",RESTORE_REVISION:"restore_revision",DELETE_REVISION:"delete_revision",PUBLISH_THEME:"publish_theme",EDIT_SETTINGS:"edit_settings",ADD_LIBRARY_BLOCK:"create_library_block",ADD_LIBRARY_TEMPLATE:"add_library_template",EDIT_LIBRARY_BLOCK:"edit_library_block",EDIT_LIBRARY_TEMPLATE:"edit_library_template",DELETE_LIBRARY_BLOCK:"delete_library_block",DELETE_LIBRARY_TEMPLATE:"delete_library_template",ADD_MEDIA:"add_media",EDIT_MEDIA:"edit_media",DELETE_MEDIA:"delete_media"},Gr=e=>{const{blocks:s,close:n,blockId:a}=e,{getPartailBlocks:r}=q.usePartailBlocksStore(),i=s.find(A=>A._id===a),l=i==null?void 0:i._libBlockId,c=!!l,u=f.useMemo(()=>s.some(A=>A._type==="PartialBlock"||A._type==="GlobalBlock"),[s]),d=f.useMemo(()=>{let A=[];for(const M of s)if(M._type==="PartialBlock"||M._type==="GlobalBlock"){let G=r(M.partialBlockId);M._parent&&(G==null?void 0:G.length)>0&&(G=G.map(T=>(m.isEmpty(T._parent)&&m.set(T,"_parent",M._parent),T))),A=[...A,...G]}else A.push(M);return A},[s,r]),[h,g]=f.useState(""),[b,y]=f.useState(""),[p,w]=f.useState(""),[v,N]=f.useState(""),[C,B]=f.useState({}),[S,P]=f.useState(!1),[O,z]=f.useState(c),[$,se]=f.useState(!1),{hasPermission:H}=q.usePermissions(),K=H(je.DELETE_LIBRARY_BLOCK),te=q.useUpdateBlocksPropsRealtime(),Q=()=>{te([a],{_libBlockId:void 0}),V.toast.success("Block delinked from library"),n()},{data:ne,isLoading:_,isError:U}=kr(l);f.useEffect(()=>{U&&c&&(se(!0),z(!1))},[U,c]),f.useEffect(()=>{ne&&!_&&(g(ne.name||""),y(ne.group||""),w(ne.description||""),N(ne.preview||""),z(!1))},[ne,_]),f.useEffect(()=>{const A=h.trim().length>=2,M=b.trim()!=="";P(A&&M)},[h,b]);const he=()=>{const A={};return h.trim()?h.length<2&&(A.name="Name must be at least 2 characters"):A.name="Name is required",b||(A.group="Group is required"),B(A),Object.keys(A).length===0},{resetLibrary:ye}=q.useLibraryBlocks({id:""}),ce=Pr(A=>{c||te([a],{_libBlockId:A.id}),V.toast.success(`Block ${c?"updated":"saved"} successfully`),ye(A.library),n()}),j=async A=>{if(A.preventDefault(),!he())return;const M=d.map(G=>(m.has(G,"_libBlockId")&&delete G._libBlockId,G));ce.mutate({name:h.trim(),group:b,blocks:M,description:p.trim(),...v&&v.startsWith("data:")?{previewImage:v}:{},...c?{id:l}:{}})},x=ce.isPending;return O||_?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"})}):$?t.jsxs("div",{className:"p-6 space-y-4",children:[t.jsx("div",{className:"text-destructive font-medium",children:"Block Not Found"}),t.jsx("p",{className:"text-sm text-muted-foreground",children:"This block could not be found on the server. It may have been deleted."}),t.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[t.jsx(o.Button,{type:"button",variant:"outline",onClick:n,children:"Cancel"}),t.jsx(o.Button,{onClick:Q,variant:"destructive",children:"Delink Block"})]})]}):t.jsxs("div",{children:[u&&t.jsxs("div",{className:"mb-4 p-3 border border-destructive/50 bg-destructive/10 text-destructive rounded-md flex items-start gap-2",children:[t.jsx(E.AlertCircle,{className:"h-5 w-5 flex-shrink-0 mt-0.5"}),t.jsxs("div",{children:[t.jsx("p",{className:"font-medium",children:"Partial Blocks Detected"}),t.jsx("p",{className:"text-xs mt-1",children:"This block contains one or more Partial Blocks. Partial blocks will be merged into the library block"})]})]}),t.jsxs("form",{onSubmit:j,className:"space-y-4",children:[t.jsxs("div",{className:"space-y-2",children:[t.jsx(o.Label,{htmlFor:"name",className:C.name?"text-destructive":"",children:"Name"}),t.jsx(o.Input,{id:"name",placeholder:"Enter block name",value:h,onChange:A=>g(A.target.value),className:C.name?"border-destructive":""}),C.name&&t.jsx("p",{className:"text-xs text-destructive",children:C.name})]}),t.jsxs("div",{className:"space-y-2",children:[t.jsx(o.Label,{htmlFor:"group",className:C.group?"text-destructive":"",children:"Group"}),t.jsx(Br,{value:b,onChange:y}),C.group&&t.jsx("p",{className:"text-xs text-destructive",children:C.group})]}),t.jsxs("div",{className:"space-y-2",children:[t.jsx(o.Label,{htmlFor:"description",children:"Description (optional)"}),t.jsx(o.Input,{id:"description",placeholder:"Enter a brief description",className:"resize-none",value:p,onChange:A=>w(A.target.value)})]}),t.jsxs("div",{className:"space-y-2",children:[t.jsx(o.Label,{htmlFor:"previewImage",children:"Preview Image (optional)"}),t.jsx(Or,{value:v,onChange:N})]}),t.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[c&&K&&t.jsx(_r,{blockId:a,libBlockId:l,blockName:h,className:"mr-auto",close:n}),t.jsx(o.Button,{type:"button",variant:"outline",onClick:n,disabled:x,children:"Cancel"}),t.jsx(o.Button,{type:"submit",disabled:x||!S,children:x?"Saving...":c?"Update Block":"Save Block"})]})]})]})},ae={PREVIEW:"Preview",THEME:"Theme",SAVEDRAFT:"Save draft",SAVING:"Saving",SAVED:"Saved",PUBLISHED:"Published",PUBLISH:"Publish",UNPUBLISH:"Unpublish",WEBSITEDATA:"Website data",OPEN:"Open",EDIT_LANGUAGE:"Edit language",ADD_NEW_LANGUAGE:"Add new language page",ENTER_LANGUAGE_DETAILS:"Enter the details for the language",LANGUAGE:"Language",PAGE_NAME:"Page Name",SLUG:"Slug",UPDATE:"Update",UPDATING:"Updating...",ADDING:"Adding...",CHOOSE_LANGUAGE:"Choose language",ALL_AVAILABLE_LANGUAGE_PAGE:"All available language page is created.",TO_UPDATE_SLUG:"To update slug use 'Change slug' action",SLUG_SHOULD_START_WITH:" (Slug should start with /{lang})",CHOOSE_LANGUAGE_TO_ADD_SLUG:"Choose language to add slug",ENTER_PAGE_SLUG:"Enter page slug",ENTER_PAGE_NAME:"Enter page name",DELETE:"Delete",CHANGE_SLUG:"Change slug",PRIMARY:"Primary",SLUG_MUST_START_WITH:"Slug must start with /",EDIT:"Edit",UNPUBLISH_MSG:"Are you sure you want to unpublish",MARK_AS_TEMPLATE:"Mark as template",UNMARK_AS_TEMPLATE:"Unmark as template",PAGE_ADD_SUCCESS:"New page added successfully.",GLOBAL_BLOCK_ADD_SUCCESS:"New global block added successfully.",SEO_SETTINGS_UPDATE_SUCCESS:"SEO Settings updated successfully.",PAGE_UPDATE_SUCCESS:"Page updated successfully.",GLOBAL_BLOCK_UPDATE_SUCCESS:"Global block updated successfully.",PAGE_DELETE_SUCCESS:"Page deleted successfully.",GLOBAL_BLOCK_DELETE_SUCCESS:"Global block deleted successfully.",PAGE_UNPUBLISH_SUCCESS:"Page unpublished successfully.",GLOBAL_BLOCK_UNPUBLISH_SUCCESS:"Global block unpublished successfully.",PAGE_PUBLISH_SUCCESS:"Page published successfully.",GLOBAL_BLOCK_PUBLISH_SUCCESS:"Global block published successfully.",PAGES_PUBLISH_SUCCESS:"Your changes have been published successfully.",SLUG_CHANGE_SUCCESS:"Slug changed successfully."},Rr={SLUG_ALREADY_USED:"This slug is already in use. Please choose a different one."},Pe=()=>{const e=re(),s=J();return D.useQuery({queryKey:[Y,L.GET_PAGE_TYPES],initialData:[],queryFn:async()=>s(e,{action:L.GET_PAGE_TYPES})})},Vn=e=>{const{data:s}=Pe();return f.useMemo(()=>s==null?void 0:s.find(n=>n.key===e),[s,e])},Ur=()=>{const e=re(),s=J();return D.useMutation({mutationFn:async({pageType:n,query:a})=>{try{return s(e,{action:L.SEARCH_PAGES,data:{pageType:n,query:Array.isArray(a)&&a.length>0?a[0]:a}})||[]}catch(r){return console.error(r),[]}}})},Hn=()=>{const e=re(),s=D.useQueryClient(),n=J(),{data:a}=Pe();return D.useMutation({mutationFn:async r=>await n(e,{action:L.CREATE_PAGE,data:r}),onSuccess:(r,i)=>{var c;i&&(i!=null&&i.primaryPage)?s.invalidateQueries({queryKey:[Y,L.GET_LANGUAGE_PAGES,i==null?void 0:i.primaryPage]}):s.invalidateQueries({queryKey:[Y,L.GET_WEBSITE_PAGES]});const l=i.template?`Page created from "${i.template.name}" template`:i.hasSlug===!1?"New "+((c=m.find(a,{key:i.pageType}))==null?void 0:c.name)+" added successfully":"New page added successfully";V.toast.success(l)},onError:(r,i)=>{const l=m.find(a,{key:i.pageType});V.toast.error(`Failed to add new ${l!=null&&l.hasSlug?"page":l.name}.`,{description:m.get(Rr,r.message,r.message)})}})},Ws=()=>{const e=re(),s=D.useQueryClient(),n=J(),{data:a}=Pe();return D.useMutation({mutationFn:async r=>await n(e,{action:L.UPDATE_PAGE,data:r}),onSuccess:(r,i)=>{i&&(i!=null&&i.primaryPage||i!=null&&i.seo)?s.invalidateQueries({queryKey:[Y,L.GET_LANGUAGE_PAGES,i==null?void 0:i.primaryPage]}):s.invalidateQueries({queryKey:[Y,L.GET_WEBSITE_PAGES]})},onError:(r,i)=>{const l=m.find(a,{key:i.pageType});V.toast.error(`Failed to update ${l!=null&&l.hasSlug?"page":l.name}.`,{description:r.message})}})},Fr=()=>{const e=re(),s=D.useQueryClient(),n=J(),{data:a}=Pe();return D.useMutation({mutationFn:async r=>n(e,{action:L.DELETE_PAGE,data:{id:r==null?void 0:r.id}}),onSuccess:(r,i)=>{if(r.code==="PAGE_LOCKED"){V.toast.error("Delete not allowed",{description:"Page is currently being edited by another user."});return}i&&(i!=null&&i.primaryPage)?s.invalidateQueries({queryKey:[Y,L.GET_LANGUAGE_PAGES,i==null?void 0:i.primaryPage]}):s.invalidateQueries({queryKey:[Y,L.GET_WEBSITE_PAGES]})},onError:(r,i)=>{const l=m.find(a,{key:i.pageType});V.toast.error(`Failed to delete ${l!=null&&l.hasSlug?"page":l.name}.`,{description:r.message})}})},qr=()=>{const e=re(),s=D.useQueryClient(),n=J(),{data:a}=Pe();return D.useMutation({mutationFn:async r=>n(e,{action:L.TAKE_OFFLINE,data:{id:r==null?void 0:r.id}}),onSuccess:(r,i)=>{i&&(i!=null&&i.primaryPage)?s.invalidateQueries({queryKey:[Y,L.GET_LANGUAGE_PAGES,i==null?void 0:i.primaryPage]}):s.invalidateQueries({queryKey:[Y,L.GET_WEBSITE_PAGES]});const l=m.find(a,{key:i.pageType});V.toast.success(l!=null&&l.hasSlug?ae.PAGE_UNPUBLISH_SUCCESS:"New "+l.name+" added successfully.")},onError:(r,i)=>{const l=m.find(a,{key:i.pageType});V.toast.error(`Failed to take offline ${l!=null&&l.hasSlug?"page":l.name}.`,{description:r.message})}})},Ys=()=>{const e=re(),s=J(),n=D.useQueryClient(),{data:a}=Te();return D.useMutation({mutationFn:async({ids:r})=>s(e,{action:L.PUBLISH_CHANGES,data:{ids:r}}),onSuccess:()=>{n.invalidateQueries({queryKey:[Y,L.GET_CHANGES]}),n.invalidateQueries({queryKey:[Y,L.GET_WEBSITE_PAGES]}),n.invalidateQueries({queryKey:[Y,L.GET_LANGUAGE_PAGES,a==null?void 0:a.id]})},onError:()=>{V.toast.error("Failed to publish pages.")}})},zr=()=>{const e=re(),s=J(),n=D.useQueryClient();return D.useMutation({mutationFn:async a=>{var r;return s(e,{action:L.MARK_AS_TEMPLATE,data:{id:(r=a.page)==null?void 0:r.id,name:a.name,description:a.description,pageType:a.pageType,previewImage:a.previewImage}})},onSuccess:()=>{n.invalidateQueries({queryKey:[Y,L.GET_WEBSITE_PAGES]}),V.toast.success("Page marked as template successfully.")},onError:()=>{V.toast.error("Failed to mark page as template.")}})},$r=()=>{const e=re(),s=J(),n=D.useQueryClient();return D.useMutation({mutationFn:async a=>s(e,{action:L.UNMARK_AS_TEMPLATE,data:{id:a==null?void 0:a.id}}),onSuccess:()=>{n.invalidateQueries({queryKey:[Y,L.GET_WEBSITE_PAGES]}),V.toast.success("Page unmarked as template successfully.")},onError:()=>{V.toast.error("Failed to unmark page as template.")}})},Vr=()=>{const e=re(),s=J(),n=D.useQueryClient();return D.useMutation({mutationFn:async({id:a,slug:r})=>s(e,{action:L.CHANGE_SLUG,data:{id:a,slug:r}}),onSuccess:(a,{primaryPage:r})=>{V.toast.success(ae.SLUG_CHANGE_SUCCESS),r?n.invalidateQueries({queryKey:[Y,L.GET_LANGUAGE_PAGES,r]}):n.invalidateQueries({queryKey:[Y,L.GET_WEBSITE_PAGES]})},onError:()=>{V.toast.error("Failed to change slug")}})};var Js={};(function e(s,n,a,r){var i=!!(s.Worker&&s.Blob&&s.Promise&&s.OffscreenCanvas&&s.OffscreenCanvasRenderingContext2D&&s.HTMLCanvasElement&&s.HTMLCanvasElement.prototype.transferControlToOffscreen&&s.URL&&s.URL.createObjectURL),l=typeof Path2D=="function"&&typeof DOMMatrix=="function",c=function(){if(!s.OffscreenCanvas)return!1;var j=new OffscreenCanvas(1,1),x=j.getContext("2d");x.fillRect(0,0,1,1);var A=j.transferToImageBitmap();try{x.createPattern(A,"no-repeat")}catch{return!1}return!0}();function u(){}function d(j){var x=n.exports.Promise,A=x!==void 0?x:s.Promise;return typeof A=="function"?new A(j):(j(u,u),null)}var h=function(j,x){return{transform:function(A){if(j)return A;if(x.has(A))return x.get(A);var M=new OffscreenCanvas(A.width,A.height),G=M.getContext("2d");return G.drawImage(A,0,0),x.set(A,M),M},clear:function(){x.clear()}}}(c,new Map),g=function(){var j=Math.floor(16.666666666666668),x,A,M={},G=0;return typeof requestAnimationFrame=="function"&&typeof cancelAnimationFrame=="function"?(x=function(T){var W=Math.random();return M[W]=requestAnimationFrame(function F(Z){G===Z||G+j-1<Z?(G=Z,delete M[W],T()):M[W]=requestAnimationFrame(F)}),W},A=function(T){M[T]&&cancelAnimationFrame(M[T])}):(x=function(T){return setTimeout(T,j)},A=function(T){return clearTimeout(T)}),{frame:x,cancel:A}}(),b=function(){var j,x,A={};function M(G){function T(W,F){G.postMessage({options:W||{},callback:F})}G.init=function(F){var Z=F.transferControlToOffscreen();G.postMessage({canvas:Z},[Z])},G.fire=function(F,Z,de){if(x)return T(F,null),x;var ve=Math.random().toString(36).slice(2);return x=d(function(oe){function R(be){be.data.callback===ve&&(delete A[ve],G.removeEventListener("message",R),x=null,h.clear(),de(),oe())}G.addEventListener("message",R),T(F,ve),A[ve]=R.bind(null,{data:{callback:ve}})}),x},G.reset=function(){G.postMessage({reset:!0});for(var F in A)A[F](),delete A[F]}}return function(){if(j)return j;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{j=new Worker(URL.createObjectURL(new Blob([G])))}catch(T){return typeof console!==void 0&&typeof console.warn=="function"&&console.warn("🎊 Could not load worker",T),null}M(j)}return j}}(),y={particleCount:50,angle:90,spread:45,startVelocity:45,decay:.9,gravity:1,drift:0,ticks:200,x:.5,y:.5,shapes:["square","circle"],zIndex:100,colors:["#26ccff","#a25afd","#ff5e7e","#88ff5a","#fcff42","#ffa62d","#ff36ff"],disableForReducedMotion:!1,scalar:1};function p(j,x){return x?x(j):j}function w(j){return j!=null}function v(j,x,A){return p(j&&w(j[x])?j[x]:y[x],A)}function N(j){return j<0?0:Math.floor(j)}function C(j,x){return Math.floor(Math.random()*(x-j))+j}function B(j){return parseInt(j,16)}function S(j){return j.map(P)}function P(j){var x=String(j).replace(/[^0-9a-f]/gi,"");return x.length<6&&(x=x[0]+x[0]+x[1]+x[1]+x[2]+x[2]),{r:B(x.substring(0,2)),g:B(x.substring(2,4)),b:B(x.substring(4,6))}}function O(j){var x=v(j,"origin",Object);return x.x=v(x,"x",Number),x.y=v(x,"y",Number),x}function z(j){j.width=document.documentElement.clientWidth,j.height=document.documentElement.clientHeight}function $(j){var x=j.getBoundingClientRect();j.width=x.width,j.height=x.height}function se(j){var x=document.createElement("canvas");return x.style.position="fixed",x.style.top="0px",x.style.left="0px",x.style.pointerEvents="none",x.style.zIndex=j,x}function H(j,x,A,M,G,T,W,F,Z){j.save(),j.translate(x,A),j.rotate(T),j.scale(M,G),j.arc(0,0,1,W,F,Z),j.restore()}function K(j){var x=j.angle*(Math.PI/180),A=j.spread*(Math.PI/180);return{x:j.x,y:j.y,wobble:Math.random()*10,wobbleSpeed:Math.min(.11,Math.random()*.1+.05),velocity:j.startVelocity*.5+Math.random()*j.startVelocity,angle2D:-x+(.5*A-Math.random()*A),tiltAngle:(Math.random()*(.75-.25)+.25)*Math.PI,color:j.color,shape:j.shape,tick:0,totalTicks:j.ticks,decay:j.decay,drift:j.drift,random:Math.random()+2,tiltSin:0,tiltCos:0,wobbleX:0,wobbleY:0,gravity:j.gravity*3,ovalScalar:.6,scalar:j.scalar,flat:j.flat}}function te(j,x){x.x+=Math.cos(x.angle2D)*x.velocity+x.drift,x.y+=Math.sin(x.angle2D)*x.velocity+x.gravity,x.velocity*=x.decay,x.flat?(x.wobble=0,x.wobbleX=x.x+10*x.scalar,x.wobbleY=x.y+10*x.scalar,x.tiltSin=0,x.tiltCos=0,x.random=1):(x.wobble+=x.wobbleSpeed,x.wobbleX=x.x+10*x.scalar*Math.cos(x.wobble),x.wobbleY=x.y+10*x.scalar*Math.sin(x.wobble),x.tiltAngle+=.1,x.tiltSin=Math.sin(x.tiltAngle),x.tiltCos=Math.cos(x.tiltAngle),x.random=Math.random()+2);var A=x.tick++/x.totalTicks,M=x.x+x.random*x.tiltCos,G=x.y+x.random*x.tiltSin,T=x.wobbleX+x.random*x.tiltCos,W=x.wobbleY+x.random*x.tiltSin;if(j.fillStyle="rgba("+x.color.r+", "+x.color.g+", "+x.color.b+", "+(1-A)+")",j.beginPath(),l&&x.shape.type==="path"&&typeof x.shape.path=="string"&&Array.isArray(x.shape.matrix))j.fill(he(x.shape.path,x.shape.matrix,x.x,x.y,Math.abs(T-M)*.1,Math.abs(W-G)*.1,Math.PI/10*x.wobble));else if(x.shape.type==="bitmap"){var F=Math.PI/10*x.wobble,Z=Math.abs(T-M)*.1,de=Math.abs(W-G)*.1,ve=x.shape.bitmap.width*x.scalar,oe=x.shape.bitmap.height*x.scalar,R=new DOMMatrix([Math.cos(F)*Z,Math.sin(F)*Z,-Math.sin(F)*de,Math.cos(F)*de,x.x,x.y]);R.multiplySelf(new DOMMatrix(x.shape.matrix));var be=j.createPattern(h.transform(x.shape.bitmap),"no-repeat");be.setTransform(R),j.globalAlpha=1-A,j.fillStyle=be,j.fillRect(x.x-ve/2,x.y-oe/2,ve,oe),j.globalAlpha=1}else if(x.shape==="circle")j.ellipse?j.ellipse(x.x,x.y,Math.abs(T-M)*x.ovalScalar,Math.abs(W-G)*x.ovalScalar,Math.PI/10*x.wobble,0,2*Math.PI):H(j,x.x,x.y,Math.abs(T-M)*x.ovalScalar,Math.abs(W-G)*x.ovalScalar,Math.PI/10*x.wobble,0,2*Math.PI);else if(x.shape==="star")for(var ie=Math.PI/2*3,Ne=4*x.scalar,De=8*x.scalar,I=x.x,le=x.y,Ee=5,Re=Math.PI/Ee;Ee--;)I=x.x+Math.cos(ie)*De,le=x.y+Math.sin(ie)*De,j.lineTo(I,le),ie+=Re,I=x.x+Math.cos(ie)*Ne,le=x.y+Math.sin(ie)*Ne,j.lineTo(I,le),ie+=Re;else j.moveTo(Math.floor(x.x),Math.floor(x.y)),j.lineTo(Math.floor(x.wobbleX),Math.floor(G)),j.lineTo(Math.floor(T),Math.floor(W)),j.lineTo(Math.floor(M),Math.floor(x.wobbleY));return j.closePath(),j.fill(),x.tick<x.totalTicks}function Q(j,x,A,M,G){var T=x.slice(),W=j.getContext("2d"),F,Z,de=d(function(ve){function oe(){F=Z=null,W.clearRect(0,0,M.width,M.height),h.clear(),G(),ve()}function R(){a&&!(M.width===r.width&&M.height===r.height)&&(M.width=j.width=r.width,M.height=j.height=r.height),!M.width&&!M.height&&(A(j),M.width=j.width,M.height=j.height),W.clearRect(0,0,M.width,M.height),T=T.filter(function(be){return te(W,be)}),T.length?F=g.frame(R):oe()}F=g.frame(R),Z=oe});return{addFettis:function(ve){return T=T.concat(ve),de},canvas:j,promise:de,reset:function(){F&&g.cancel(F),Z&&Z()}}}function ne(j,x){var A=!j,M=!!v(x||{},"resize"),G=!1,T=v(x,"disableForReducedMotion",Boolean),W=i&&!!v(x||{},"useWorker"),F=W?b():null,Z=A?z:$,de=j&&F?!!j.__confetti_initialized:!1,ve=typeof matchMedia=="function"&&matchMedia("(prefers-reduced-motion)").matches,oe;function R(ie,Ne,De){for(var I=v(ie,"particleCount",N),le=v(ie,"angle",Number),Ee=v(ie,"spread",Number),Re=v(ie,"startVelocity",Number),Ns=v(ie,"decay",Number),Cs=v(ie,"gravity",Number),ts=v(ie,"drift",Number),rt=v(ie,"colors",S),it=v(ie,"ticks",Number),Pt=v(ie,"shapes"),ss=v(ie,"scalar"),k=!!v(ie,"flat"),ue=O(ie),Me=I,Ce=[],Oe=j.width*ue.x,Fe=j.height*ue.y;Me--;)Ce.push(K({x:Oe,y:Fe,angle:le,spread:Ee,startVelocity:Re,color:rt[Me%rt.length],shape:Pt[C(0,Pt.length)],ticks:it,decay:Ns,gravity:Cs,drift:ts,scalar:ss,flat:k}));return oe?oe.addFettis(Ce):(oe=Q(j,Ce,Z,Ne,De),oe.promise)}function be(ie){var Ne=T||v(ie,"disableForReducedMotion",Boolean),De=v(ie,"zIndex",Number);if(Ne&&ve)return d(function(Re){Re()});A&&oe?j=oe.canvas:A&&!j&&(j=se(De),document.body.appendChild(j)),M&&!de&&Z(j);var I={width:j.width,height:j.height};F&&!de&&F.init(j),de=!0,F&&(j.__confetti_initialized=!0);function le(){if(F){var Re={getBoundingClientRect:function(){if(!A)return j.getBoundingClientRect()}};Z(Re),F.postMessage({resize:{width:Re.width,height:Re.height}});return}I.width=I.height=null}function Ee(){oe=null,M&&(G=!1,s.removeEventListener("resize",le)),A&&j&&(document.body.contains(j)&&document.body.removeChild(j),j=null,de=!1)}return M&&!G&&(G=!0,s.addEventListener("resize",le,!1)),F?F.fire(ie,I,Ee):R(ie,I,Ee)}return be.reset=function(){F&&F.reset(),oe&&oe.reset()},be}var _;function U(){return _||(_=ne(null,{useWorker:!0,resize:!0})),_}function he(j,x,A,M,G,T,W){var F=new Path2D(j),Z=new Path2D;Z.addPath(F,new DOMMatrix(x));var de=new Path2D;return de.addPath(Z,new DOMMatrix([Math.cos(W)*G,Math.sin(W)*G,-Math.sin(W)*T,Math.cos(W)*T,A,M])),de}function ye(j){if(!l)throw new Error("path confetti are not supported in this browser");var x,A;typeof j=="string"?x=j:(x=j.path,A=j.matrix);var M=new Path2D(x),G=document.createElement("canvas"),T=G.getContext("2d");if(!A){for(var W=1e3,F=W,Z=W,de=0,ve=0,oe,R,be=0;be<W;be+=2)for(var ie=0;ie<W;ie+=2)T.isPointInPath(M,be,ie,"nonzero")&&(F=Math.min(F,be),Z=Math.min(Z,ie),de=Math.max(de,be),ve=Math.max(ve,ie));oe=de-F,R=ve-Z;var Ne=10,De=Math.min(Ne/oe,Ne/R);A=[De,0,0,De,-Math.round(oe/2+F)*De,-Math.round(R/2+Z)*De]}return{type:"path",path:x,matrix:A}}function ce(j){var x,A=1,M="#000000",G='"Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji", "EmojiOne Color", "Android Emoji", "Twemoji Mozilla", "system emoji", sans-serif';typeof j=="string"?x=j:(x=j.text,A="scalar"in j?j.scalar:A,G="fontFamily"in j?j.fontFamily:G,M="color"in j?j.color:M);var T=10*A,W=""+T+"px "+G,F=new OffscreenCanvas(T,T),Z=F.getContext("2d");Z.font=W;var de=Z.measureText(x),ve=Math.ceil(de.actualBoundingBoxRight+de.actualBoundingBoxLeft),oe=Math.ceil(de.actualBoundingBoxAscent+de.actualBoundingBoxDescent),R=2,be=de.actualBoundingBoxLeft+R,ie=de.actualBoundingBoxAscent+R;ve+=R+R,oe+=R+R,F=new OffscreenCanvas(ve,oe),Z=F.getContext("2d"),Z.font=W,Z.fillStyle=M,Z.fillText(x,be,ie);var Ne=1/A;return{type:"bitmap",bitmap:F.transferToImageBitmap(),matrix:[Ne,0,0,Ne,-ve*Ne/2,-oe*Ne/2]}}n.exports=function(){return U().apply(this,arguments)},n.exports.reset=function(){U().reset()},n.exports.create=ne,n.exports.shapeFromPath=ye,n.exports.shapeFromText=ce})(function(){return typeof window<"u"?window:typeof self<"u"?self:this||{}}(),Js,!1);const Hr=Js.exports;Js.exports.create;const Kr={particleCount:350,spread:120,origin:{y:.6},angle:90},Qr={TOP_RIGHT:{angle:225,origin:{x:.9,y:0}},BOTTOM_RIGHT:{angle:100,origin:{x:.9,y:.9}}},Dt=e=>{let s=Qr[e];s||(s={});const n={...Kr,...s};Hr(n)},Wr=()=>{const[e]=q.useTheme(),{mutate:s,isPending:n}=Ys(),{mutateAsync:a,isPending:r}=Mn(),i=()=>{a({settings:{theme:e}})},l=()=>{s({ids:["THEME"]},{onSuccess:()=>{Dt("BOTTOM_RIGHT")}})};return t.jsxs("div",{className:"bg-white py-3 flex items-center justify-center gap-x-3 border-t",children:[t.jsx(o.Button,{size:"sm",variant:"outline",disabled:n||r,onClick:i,children:"Save draft"}),t.jsx(o.Button,{size:"sm",disabled:n||r,onClick:l,children:"Publish"})]})},Yr=({page:e,onClose:s})=>{const[n,a]=f.useState(e.slug||""),{mutate:r,isPending:i}=Vr(),{data:l}=Pe(),c=m.find(l,{key:e==null?void 0:e.pageType}),u=h=>{if(h.preventDefault(),!(e!=null&&e.primaryPage)&&Object.keys(ke).some(y=>n===`/${y}`||m.startsWith(n,`/${y}/`))){V.toast.error("Error",{description:"Slugs cannot start with a language code for primary page"});return}r({...e,slug:n},{onSuccess:s})},d=(e==null?void 0:e.lang)||"";return t.jsx(o.Dialog,{open:!!e,onOpenChange:s,children:t.jsxs(o.DialogContent,{children:[t.jsxs(o.DialogHeader,{children:[t.jsx(o.DialogTitle,{children:"Change Slug"}),t.jsx(o.DialogDescription,{className:"text-xs",children:t.jsxs(o.Alert,{variant:"destructive",className:"mt-2",children:[t.jsx(E.AlertCircle,{className:"h-4 w-4"}),"Changing the slug may have impact on your SEO. Please proceed with caution."]})})]}),t.jsxs("form",{onSubmit:u,children:[t.jsxs("div",{className:"space-y-4 py-4 text-sm ",children:[t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{children:[t.jsx("span",{children:"Type:"}),t.jsxs("span",{className:"font-medium text-gray-600",children:[" ",(c==null?void 0:c.name)||(e==null?void 0:e.pageType)]})]}),t.jsxs("div",{children:[t.jsx("span",{children:"Name:"}),t.jsxs("span",{className:"font-medium text-gray-600",children:[" ",e.name]})]})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsxs(o.Label,{htmlFor:"slug",className:"text-right",children:["Slug"," ",t.jsxs("small",{className:"font-light text-gray-500",children:["Slug should start with /",d]})]}),t.jsx(o.Input,{id:"slug",value:n,onChange:h=>{const g=h.target.value;m.startsWith(g,`/${d}`)&&a(g)},className:"col-span-3",required:!0,pattern:"^/.*",title:"Slug must start with /",placeholder:"Enter page slug"})]})]}),t.jsx(o.DialogFooter,{children:t.jsx(o.Button,{type:"submit",disabled:i||!m.startsWith(n,`/${d}`)||m.isEqual(e==null?void 0:e.slug,n),children:i?"Changing...":"Change Slug"})})]})]})})};function Xs({page:e,onClose:s}){const[,n]=_e(),{mutate:a,isPending:r}=Fr(),{data:i}=Pe(),{setSelectedLang:l,fallbackLang:c}=q.useLanguages(),[,u]=q.useSidebarActivePanel(),d=()=>{r||a(e,{onSuccess:()=>{e!=null&&e.primaryPage?(window.history.replaceState({},"",`/?page=${e.primaryPage}`),n(new URLSearchParams({page:e.primaryPage}))):(window.history.replaceState({},"","/"),n(new URLSearchParams)),window.dispatchEvent(new PopStateEvent("popstate")),l(c),u("outline"),s()}})},h=i==null?void 0:i.find(g=>g.key===(e==null?void 0:e.pageType));return t.jsx(o.Dialog,{open:!!e,onOpenChange:s,children:t.jsxs(o.DialogContent,{children:[t.jsxs(o.DialogHeader,{children:[t.jsx(o.DialogTitle,{children:"Confirm Deletion"}),t.jsxs(o.DialogDescription,{className:"py-4 text-slate-500",children:[t.jsxs("div",{children:["Are you sure you want to remove ",t.jsx("b",{children:(e==null?void 0:e.name)??(e==null?void 0:e.slug)})," ",h!=null&&h.hasSlug?(h==null?void 0:h.name)+"?":`page? ${e!=null&&e.primaryPage?"":"This will also delete all associated language pages."}`]}),e.lang&&t.jsxs("div",{className:"py-2 text-sm",children:["Language:"," ",t.jsx("span",{className:"font-medium text-gray-500",children:m.get(ke,e.lang,e.lang)})]})]})]}),t.jsxs(o.DialogFooter,{children:[t.jsx(o.Button,{variant:"outline",onClick:s,children:"Cancel"}),t.jsx(o.Button,{variant:"destructive",disabled:r,onClick:d,children:r?"Deleting...":"Delete"})]})]})})}const Ge=({permission:e,permissions:s,children:n,fallback:a=null})=>{const{hasPermission:r}=q.usePermissions();return e&&!r(e)||s&&!s.some(i=>r(i))?a:n},bs=({page:e,onClose:s})=>{const{mutate:n,isPending:a}=qr(),r=async()=>{n(e,{onSuccess:s})};return t.jsx(o.Dialog,{open:!!e,onOpenChange:s,children:t.jsxs(o.DialogContent,{children:[t.jsxs(o.DialogHeader,{children:[t.jsx(o.DialogTitle,{children:"Confirm action"}),t.jsxs(o.DialogDescription,{children:[ae.UNPUBLISH_MSG," ",t.jsx("b",{children:(e==null?void 0:e.name)??(e==null?void 0:e.slug)}),"?"]})]}),t.jsxs(o.DialogFooter,{children:[t.jsx(o.Button,{variant:"outline",onClick:s,children:"Cancel"}),t.jsx(o.Button,{variant:"destructive",disabled:a,onClick:r,children:a?ae.UPDATING:ae.UNPUBLISH})]})]})})},Jr=e=>{if(!e)return{base:e,extension:null};const s=e.lastIndexOf(".");if(s<=0)return{base:e,extension:null};const n=e.substring(s);return{base:e.substring(0,s),extension:n}},Ve=e=>{if(!e)return e;const{base:s}=Jr(e);return s},Xr=e=>e&&Ve(e),hn=(e,s)=>{const n=Ve(e||"");return!n||n==="/"?`/${s}`:`${n}/${s}`};function Zs({value:e,onChange:s,placeholder:n,parentSlug:a,onValidationChange:r,disabled:i=!1,fullSlug:l}){const[c,u]=f.useState(e),[d,h]=f.useState(null);f.useEffect(()=>{u(e)},[e]);const g=b=>{const p=b.target.value.replace(/\//g,"").replace(/\s+/g,"-").replace(/[^a-zA-Z0-9-_.]/g,"-").replace(/-+/g,"-").replace(/^-+/,"").toLowerCase(),w=(p.match(/\./g)||[]).length,v=w<=1;w>1?h("Invalid slug. Only one dot (.) is allowed in the slug"):h(null),r&&r(v),u(p),s(p)};return t.jsxs("div",{children:[a&&t.jsx("div",{className:"flex items-center mb-1",children:t.jsxs("span",{className:"text-xs text-gray-500",children:["Parent:"," ",t.jsx("span",{className:"font-mono text-gray-900",children:Xr(a)})]})}),t.jsxs("div",{className:"relative",children:[t.jsx(o.Input,{disabled:i,value:c,onChange:g,placeholder:n,className:d?"border-red-500":""}),d&&t.jsx("div",{className:"text-red-500 text-xs mt-1",children:d})]}),l&&t.jsx("div",{className:"flex items-center mt-1",children:t.jsxs("span",{className:"text-xs text-gray-500",children:["Complete Slug:"," ",t.jsx("span",{className:"font-mono text-gray-900",children:l})]})})]})}const Kn=({langProps:e,onClose:s,languages:n})=>{const{data:a}=Te(),r=a==null?void 0:a.dynamic,{data:i}=Pe(),[l,c]=f.useState(e.name||""),[u,d]=f.useState(e.edit?e.lang:""),[h,g]=f.useState(e.edit?e.slug:""),[b,y]=f.useState(!0),[p,w]=f.useState(!0),{mutate:v,isPending:N}=Hn(),{mutate:C,isPending:B}=Ws(),{data:S}=Ke(a==null?void 0:a.parent),{setSelectedLang:P,fallbackLang:O}=q.useLanguages(),[,z]=_e(),[,$]=q.useSidebarActivePanel(),se=f.useMemo(()=>i==null?void 0:i.find(j=>j.key===e.pageType),[i,e.pageType]),H=r||!(se!=null&&se.hasSlug),K=(a==null?void 0:a.slug)==="/",te=N||B,{parentSlug:Q,isRootPage:ne}=f.useMemo(()=>{if(K||!u)return{parentSlug:void 0,isRootPage:!(a!=null&&a.parent)};if(!(a!=null&&a.parent))return{parentSlug:p?`/${u}`:void 0,isRootPage:!(a!=null&&a.parent)};const j=S==null?void 0:S.find(x=>x.lang===u);return{parentSlug:j==null?void 0:j.slug,isRootPage:!1}},[a==null?void 0:a.parent,S,p,u,K]);f.useEffect(()=>{if(!e.edit)return;const x=(e.slug||"").split("/").filter(Boolean);let A="";const M=G=>w(G);if(K){const G=x.pop()||"";if(ke[G])M(!0);else{A=G;const T=x.pop()||"";M(!!ke[T])}}else if(ne){if(x.length){A=x.pop()||"";const G=x.pop()||"";M(!!ke[G])}}else x.length&&(A=x.pop()||"");g(A)},[e,K,ne]);const _=f.useMemo(()=>ne?!0:!!(S!=null&&S.find(j=>(j==null?void 0:j.lang)===u)),[u,S,ne]),U=()=>{let j="";return ne?j=`/${p?[u,h].filter(Boolean).join("/"):h}`:j=`${Ve(Q)}/${h}`,j.replace(/\/{2,}/g,"/").replace(/\/$/,"")},he=(j,x)=>{const A=new URLSearchParams(window.location.search);x&&j===x?A.delete("lang"):A.set("lang",j);const M=A.toString(),G=`${window.location.pathname}${M?`?${M}`:""}`;window.history.pushState({},"",G),z(A),window.dispatchEvent(new PopStateEvent("popstate"))},ye=j=>{j.preventDefault();const x={name:l,lang:u,primaryPage:a==null?void 0:a.id,slug:U(),pageType:a==null?void 0:a.pageType,tracking:{}};x.pageType=e.pageType,e.edit&&(x.id=e==null?void 0:e.id),e.edit?C(x,{onSuccess:s}):v(x,{onSuccess:()=>{u&&(P(u),he(u,O)),$("outline"),s()}})},ce=te||m.isEmpty(l)||m.isEmpty(u)||(H||K&&p?!1:!b||m.isEmpty(h));return t.jsx(o.Dialog,{open:!!e,onOpenChange:s,children:t.jsxs(o.DialogContent,{className:"sm:max-w-[425px] text-slate-600",children:[t.jsxs(o.DialogHeader,{children:[t.jsx(o.DialogTitle,{children:e.edit?ae.EDIT_LANGUAGE:ae.ADD_NEW_LANGUAGE}),t.jsx(o.DialogDescription,{className:"font-light",children:ae.ENTER_LANGUAGE_DETAILS})]}),t.jsxs("form",{onSubmit:ye,children:[t.jsxs("div",{className:"grid gap-4 py-4",children:[t.jsxs("div",{className:"space-y-1",children:[t.jsx(o.Label,{htmlFor:"lang",className:"text-right",children:ae.LANGUAGE}),t.jsxs("select",{value:u,disabled:e.edit||m.isEmpty(n),onChange:j=>{const x=j.target.value;d(x),!e.edit&&m.startsWith(l,e.name)&&c(`${e.name} - ${ke[x]}`)},className:"flex h-9 w-full rounded-md border border-border bg-background px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 col-span-3",children:[t.jsx("option",{value:"",disabled:!0,selected:!0,children:e.edit?m.get(ke,e.lang,e.lang):m.isEmpty(n)?ae.ALL_AVAILABLE_LANGUAGE_PAGE:ae.CHOOSE_LANGUAGE}),m.map(n,j=>t.jsx("option",{value:j,children:m.get(ke,j,j)},j))]})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsx(o.Label,{htmlFor:"slug",className:"text-right",children:ae.PAGE_NAME}),t.jsx(o.Input,{id:"name",value:u?l:"",onChange:j=>c(j.target.value),className:"col-span-3",required:!0,placeholder:u?ae.ENTER_PAGE_NAME:ae.CHOOSE_LANGUAGE_TO_ADD_SLUG,disabled:!_||!u})]}),!H&&t.jsx(t.Fragment,{children:t.jsxs("div",{className:"space-y-1",children:[ne&&u&&t.jsxs("div",{className:"flex items-center space-x-2 pb-1",children:[t.jsx("input",{type:"checkbox",id:"useLanguagePrefix",checked:p,onChange:j=>w(j.target.checked),className:"rounded border-gray-300"}),t.jsxs(o.Label,{htmlFor:"useLanguagePrefix",className:"text-sm font-normal leading-tight",children:["Add language code (",t.jsxs("span",{className:"font-mono text-gray-900",children:["/",u]}),") as slug prefix"]})]}),t.jsxs(o.Label,{htmlFor:"slug",className:"text-right",children:[ae.SLUG," "]}),t.jsx(Zs,{disabled:m.isEmpty(u)||!_,value:h,onChange:g,placeholder:m.isEmpty(u)?ae.CHOOSE_LANGUAGE_TO_ADD_SLUG:K&&p?"Leave empty for home page":ae.ENTER_PAGE_SLUG,parentSlug:Q,onValidationChange:y,fullSlug:ce?"":U()})]})}),r&&u&&_&&t.jsxs("p",{className:"text-sm pb-2",children:[t.jsx(o.Label,{children:"Dynamic Slug: "})," ",t.jsx("span",{className:"font-mono font-light",children:`${Ve(Q)}/${se==null?void 0:se.dynamicSlug}`})]})]}),t.jsx(o.DialogFooter,{children:_?t.jsx(o.Button,{type:"submit",disabled:ce,children:te?e.edit?ae.UPDATING:ae.ADDING:e.edit?ae.UPDATE:ae.ADD_NEW_LANGUAGE}):u&&t.jsx(o.Alert,{variant:"destructive",children:t.jsxs("p",{className:"text-center w-5/6 mx-auto",children:["You need to create the ",t.jsx("span",{className:"font-medium",children:ke[u]})," page in the parent to add here."]})})})]})]})})},Zr=()=>{const[e,s]=f.useState(null),{selectedLang:n,fallbackLang:a,setSelectedLang:r}=q.useLanguages(),{data:i,isFetching:l}=Ke(),{data:c}=Te(),{data:u}=Pe(),d=f.useMemo(()=>{const C=u==null?void 0:u.find(B=>B.key===(c==null?void 0:c.pageType));return C==null?void 0:C.dynamicSlug},[u,c==null?void 0:c.pageType]),[h,g]=f.useState(null),[b,y]=f.useState(null),[p,w]=f.useState(null),{data:v}=Ze(),N=m.filter(m.get(v,"languages")||["en"],C=>!m.find(i,{lang:C})&&C!==m.get(v,"fallbackLang"));return t.jsxs("div",{className:"space-y-4",children:[t.jsx("ul",{className:"space-y-2",children:l?t.jsxs("div",{className:"w-full space-y-3 py-4",children:[t.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"}),t.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"}),t.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"})]}):m.map(i,C=>{const B=C.lang,S=C.slug,P=!C.primaryPage,O=B===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 ${O?"bg-gray-200":"hover:bg-gray-100"}`,onClick:()=>r(B),children:[t.jsxs("div",{className:" flex-1 gap-x-3",children:[t.jsxs("div",{className:"text-[13px] text-slate-800 flex items-center gap-x-2",children:[t.jsx("div",{className:`w-2.5 h-2.5 rounded-full ${C.online?"bg-green-300":"bg-gray-300"}`}),m.get(ke,P?a:B,B)]}),t.jsxs("div",{children:[S&&t.jsxs("div",{className:"text-[11px] text-slate-600 font-light",children:["Slug: ",t.jsx("b",{className:"font-medium font-mono",children:d?`${S}/${d}`:S})]}),t.jsxs("div",{className:"text-[11px] text-slate-600 font-light",children:["Name:",t.jsxs("b",{className:"font-medium",children:[" ",C.name," "]})]})]})]}),P?t.jsxs("div",{className:"flex items-center text-[11px] text-orange-500 gap-x-1",children:[t.jsx(E.StarIcon,{fill:"orange",className:"w-3 h-3"}),t.jsx("b",{children:" Primary"})]}):t.jsx("div",{className:"flex items-center gap-x-3",children:t.jsx(Ge,{permissions:[je.EDIT_PAGE,je.DELETE_PAGE,je.UNPUBLISH_PAGE],children:t.jsxs(o.DropdownMenu,{children:[t.jsx(o.DropdownMenuTrigger,{asChild:!0,onClick:z=>z.stopPropagation(),children:t.jsx(o.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",children:t.jsx(E.MoreHorizontal,{className:"h-4 w-4"})})}),t.jsxs(o.DropdownMenuContent,{align:"end",className:"text-sm z-[9999]",children:[t.jsx(Ge,{permissions:[je.EDIT_PAGE],children:t.jsxs(o.DropdownMenuItem,{className:"flex items-center gap-2 cursor-pointer",onClick:z=>{z.stopPropagation(),s({...C,edit:!0})},children:[t.jsx(E.PencilIcon,{className:"size-3"}),ae.EDIT]})}),t.jsx(Ge,{permissions:[je.UNPUBLISH_PAGE],children:(C==null?void 0:C.online)&&t.jsxs(o.DropdownMenuItem,{className:"flex items-center gap-2 cursor-pointer",onClick:z=>{z.stopPropagation(),y(C)},children:[t.jsx(E.Power,{className:"size-3"}),ae.UNPUBLISH]})}),t.jsx(Ge,{permissions:[je.DELETE_PAGE],children:t.jsxs(o.DropdownMenuItem,{className:"flex items-center gap-2 cursor-pointer",onClick:z=>{z.stopPropagation(),g(C)},children:[t.jsx(E.TrashIcon,{className:"size-3"}),ae.DELETE]})})]})]})})})]},C.id),t.jsx("div",{className:"h-1 w-full border-b"})]})})}),t.jsx(Ge,{permissions:[je.ADD_PAGE],children:t.jsx("div",{className:"flex justify-center w-full",children:t.jsx(o.Button,{variant:"default",size:"sm",disabled:m.isEmpty(N),onClick:()=>{s({name:c==null?void 0:c.name,pageType:c==null?void 0:c.pageType,lang:"",slug:"",edit:!1})},children:ae.ADD_NEW_LANGUAGE})})}),e&&t.jsx(Kn,{languages:N,langProps:e,onClose:()=>s(null)}),h&&t.jsx(Xs,{page:h,onClose:()=>g(null)}),b&&t.jsx(bs,{page:b,onClose:()=>y(null)}),p&&t.jsx(Yr,{page:p,onClose:()=>w(null)})]})};function ei({value:e,onChange:s,placeholder:n="Enter custom slug part",dynamicPattern:a,onValidationChange:r}){const[i,l]=f.useState(null),c=f.useRef(null),[u,d]=f.useState(a+e);f.useEffect(()=>{d(a+e)},[e,a]);const h=y=>{const p=y.target.value;if(!p.startsWith(a)){const S=p.replace(a,""),P=a+S;d(P),s(S);return}const v=p.substring(a.length).replace(/\//g,"").replace(/\s+/g,"-").replace(/[^a-zA-Z0-9-_.]/g,"-").replace(/-+/g,"-").replace(/^-+/,"").toLowerCase(),N=(v.match(/\./g)||[]).length,C=N<=1;N>1?l("Invalid slug. Only one dot (.) is allowed in the slug"):l(null),r&&r(C);const B=a+v;d(B),s(v)},g=()=>{if(c.current){const y=c.current;setTimeout(()=>{const p=a.length;y.setSelectionRange(p,p)},0)}},b=y=>{const p=y.currentTarget;(p.selectionStart||0)<=a.length&&setTimeout(()=>{const v=a.length;p.setSelectionRange(v,v)},0)};return t.jsx("div",{children:t.jsxs("div",{className:"relative",children:[t.jsxs("p",{className:"text-gray-500 text-xs mb-2",children:[`${a}`," is a dynamic segment of slug"]}),t.jsx(o.Input,{ref:c,value:u,onChange:h,onFocus:g,onClick:b,placeholder:n,className:i?"border-red-500":""}),i&&t.jsx("div",{className:"text-red-500 text-xs mt-1",children:i})]})})}const cs=({children:e,onWheel:s,...n})=>{const a=r=>{try{r.preventDefault();const i=r.currentTarget;i.scrollTop+=r.deltaY}catch{r.preventDefault()}s&&s(r)};return t.jsx(o.CommandList,{...n,onWheel:a,children:e})},Ts=(...e)=>e.filter(Boolean).join(" ");function ti({pages:e,selectedParentId:s,onChange:n,className:a,id:r="parentPage"}){const[i,l]=f.useState(!1),[c,u]=f.useState(""),d=f.useMemo(()=>!e||e.length===0?[]:e.filter(v=>!m.isEmpty(v.slug)).filter(v=>v.slug!=="/").sort((v,N)=>v.slug.localeCompare(N.slug)),[e]),h=f.useMemo(()=>{if(!c.trim())return d;const w=c.toLowerCase();return d.filter(v=>v.name.toLowerCase().includes(w)||v.slug.toLowerCase().includes(w))},[d,c]),g=w=>Math.max(0,(w.match(/\//g)||[]).length-1),b=w=>" ".repeat(w),y=w=>{if(w==="/")return"/";const v=w.split("/").filter(Boolean);if(v.length<=1){const N=v[0]||"";return`/${Ve(N)}`}return`/${Ve(v[v.length-1])}`},p=()=>{if(!s||s==="none")return"None";const w=d.find(v=>v.id===s);return w?`${w.name} (${y(w.slug)})`:"None"};return t.jsxs("div",{className:"space-y-0.5",children:[t.jsx(o.Label,{htmlFor:r,className:"text-sm",children:"Parent"}),t.jsxs(o.Popover,{open:i,onOpenChange:l,children:[t.jsx(o.PopoverTrigger,{asChild:!0,children:t.jsxs(o.Button,{id:r,variant:"outline",role:"combobox",className:Ts("w-full justify-between",a),"data-testid":"parent-page-selector",children:[p(),t.jsx(E.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),t.jsx(o.PopoverContent,{className:"w-[var(--radix-popover-trigger-width)] p-0",align:"start",children:t.jsxs(o.Command,{shouldFilter:!1,children:[t.jsx("div",{className:"relative border-none py-2",children:t.jsx("div",{className:"sticky top-0 z-10 bg-white px-3 py-2",children:t.jsxs("div",{className:"relative",children:[t.jsx(E.Search,{strokeWidth:2,className:"absolute left-2 top-2 h-4 w-4 text-gray-400"}),t.jsx(o.Input,{placeholder:"Search pages...",className:"h-8 pl-8 text-xs",value:c,onChange:w=>u(w.target.value)})]})})}),t.jsxs(cs,{className:"max-h-[300px] overflow-y-auto",children:[t.jsx(o.CommandEmpty,{children:"No pages found."}),t.jsxs(o.CommandGroup,{children:[t.jsxs(o.CommandItem,{value:"none",onSelect:()=>{n(""),l(!1),u("")},className:"flex cursor-pointer items-center justify-between",children:[t.jsx("span",{children:"None"}),t.jsx(E.Check,{className:Ts("mr-2 h-4 w-4",s?"opacity-0":"opacity-100")})]}),h.map(w=>{const v=b(g(w.slug)),N=y(w.slug),C=t.jsxs("span",{className:"flex items-center text-sm",children:[v,w.name,t.jsxs("span",{className:"text-xs text-gray-500",children:[" (",N,")"]})]});return t.jsxs(o.CommandItem,{value:w.id,onSelect:()=>{n(w.id),l(!1),u("")},className:"flex cursor-pointer items-center justify-between whitespace-pre-wrap",children:[t.jsx("span",{children:C}),t.jsx(E.Check,{className:Ts("mr-2 h-4 w-4 shrink-0",s===w.id?"opacity-100":"opacity-0")})]},w.id)})]})]})]})})]})]})}const si=(...e)=>e.filter(Boolean).join(" "),ni=({templates:e,selectedTemplateId:s,onSelectTemplate:n,isLoading:a=!1})=>{const[r,i]=f.useState(""),[l,c]=f.useState(!1),[u,d]=f.useState("");if(f.useEffect(()=>{if(s){const p=e.find(w=>w.id===s);i((p==null?void 0:p.preview)||"")}else i("")},[s,e]),a)return t.jsx("div",{className:"flex h-fit items-center justify-center text-sm text-gray-500",children:"Loading templates..."});if(e.length===0)return null;const h={};e.forEach(p=>{const w=p.libraryName;h[w]||(h[w]=[]),h[w].push(p)});const g=Object.entries(h).reduce((p,[w,v])=>{const N=v.filter(C=>C.name.toLowerCase().includes(u.toLowerCase())||w.toLowerCase().includes(u.toLowerCase()));return N.length>0&&(p[w]=N),p},{}),b=e.find(p=>p.id===s),y=b?m.startCase(b.name):"No Template";return t.jsxs("div",{className:"space-y-4",children:[t.jsxs(o.Popover,{open:l,onOpenChange:c,children:[t.jsx(o.PopoverTrigger,{asChild:!0,children:t.jsxs(o.Button,{variant:"outline",role:"combobox",className:"w-full justify-between",children:[y,t.jsx(E.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),t.jsx(o.PopoverContent,{className:"w-[var(--radix-popover-trigger-width)] p-0",align:"start",children:t.jsxs(o.Command,{shouldFilter:!1,children:[t.jsx("div",{className:"sticky top-0 z-10 bg-white px-3 py-2",children:t.jsxs("div",{className:"relative",children:[t.jsx(E.Search,{strokeWidth:2,className:"absolute left-2 top-2 h-4 w-4 text-gray-400"}),t.jsx(o.Input,{placeholder:"Search templates...",className:"h-8 pl-8 text-xs",value:u,onChange:p=>d(p.target.value)})]})}),t.jsxs(cs,{className:"max-h-[300px] overflow-y-auto",children:[t.jsx(o.CommandEmpty,{children:"No templates found."}),Object.entries(g).map(([p,w])=>t.jsx(o.CommandGroup,{heading:p,children:w.map(v=>t.jsxs(o.CommandItem,{value:v.id,onSelect:()=>{n(v.id),c(!1),d("")},className:"flex cursor-pointer items-center justify-between",children:[m.startCase(v.name),t.jsx(E.Check,{className:si("mr-2 h-4 w-4",s===v.id?"opacity-100":"opacity-0")})]},v.id))},p))]})]})})]}),r&&t.jsxs("div",{className:"mt-3 overflow-hidden rounded border",children:[t.jsx("div",{className:"max-h-[200px] overflow-auto",children:t.jsx("img",{src:r,alt:"Template Preview",className:"w-full object-contain"})}),t.jsx("div",{className:"border-t bg-gray-50 p-2 text-xs text-gray-500",children:"Template preview"})]})]})},ai=()=>{const e=re(),s=J();return D.useQuery({queryKey:[Y,L.GET_LIBRARIES],queryFn:async()=>await s(e,{action:L.GET_LIBRARIES})||[]})},ri=e=>{const s=re(),n=J();return D.useQuery({queryKey:[Y,L.GET_TEMPLATES_BY_TYPE,e],enabled:!!e,queryFn:async()=>{const a=await n(s,{action:L.GET_TEMPLATES_BY_TYPE,data:{pageType:e}});return(e?m.filter(a,{pageType:e}):a)||[]}})},ii=e=>{const{data:s=[],isLoading:n}=ri(e),{data:a=[],isLoading:r}=ai(),i=f.useMemo(()=>n||r?[]:s.map(c=>{const u=m.find(a,{id:c.library});return{...c,libraryName:(u==null?void 0:u.type)!=="shared"?"Site Library":(u==null?void 0:u.name)+" Library",libraryType:u==null?void 0:u.type}}),[s,a,n,r]),l=f.useMemo(()=>m.groupBy(i,"libraryName"),[i]);return{data:i,groupedData:l,isLoading:n||r}},en=()=>{const[,e]=_e();return f.useCallback((s,n)=>{const r=new URLSearchParams(window.location.search).get("lang"),i=new URLSearchParams({page:s});r&&i.set("lang",r),window.history.pushState({},"",`?${i.toString()}`),e(i),window.dispatchEvent(new PopStateEvent("popstate")),n==null||n()},[e])},us=(e,s)=>{const n={seo:{keyword:"",title:"",description:"",noIndex:!1,noFollow:!1,canonicalUrl:"",ogTitle:"",ogDescription:"",jsonLD:""},jsonLD:{}};e!=null&&e.defaultSeo&&(m.has(e.defaultSeo,s)&&m.isObject(e.defaultSeo[s])?n.seo={...n.seo,...e.defaultSeo[s]}:n.seo={...n.seo,...e.defaultSeo});let a={};return e!=null&&e.defaultJSONLD&&(m.has(e.defaultJSONLD,s)&&m.isObject(e.defaultJSONLD[s])?(a=e.defaultJSONLD[s],m.set(n,"seo.jsonLD",JSON.stringify(a))):(a=e.defaultJSONLD,m.set(n,"seo.jsonLD",JSON.stringify(a)))),{seo:n.seo,jsonLD:a}},tt=(...e)=>e.filter(Boolean).join(" ");function li({addEditPage:e,additionalPageTypes:s=[],close:n,closePanel:a}){var Pt,ss;const r=en(),i=!!(e!=null&&e.id),{data:l}=Zt(),{mutate:c,isPending:u}=Hn(),{mutate:d,isPending:h}=Ws(),[g,b]=f.useState(null),[y,p]=f.useState(!0),[w,v]=f.useState((e==null?void 0:e.pageType)??"page"),{hasPermission:N}=q.usePermissions(),C=N(je.CHANGE_PAGE_TYPE),[B,S]=f.useState(!1),[P,O]=f.useState(""),{selectedLang:z,fallbackLang:$}=q.useLanguages(),se=z||$,[H,K]=f.useState(""),[te,Q]=f.useState(!1),ne=f.useMemo(()=>{const k=s.find(ue=>ue.key===w);return(k==null?void 0:k.hasSlug)===!1},[w,s]),[_,U]=f.useState((e==null?void 0:e.parent)??""),[he,ye]=f.useState((e==null?void 0:e.name)??""),[ce,j]=f.useState((e==null?void 0:e.dynamic)??!1),[x,A]=f.useState(ce?"":((e==null?void 0:e.slug)??"").split("/").pop()||""),[M,G]=f.useState((e==null?void 0:e.dynamicSlugCustom)??""),[T,W]=f.useState(!0),[F,Z]=f.useState(""),{data:de,isLoading:ve}=ii(w),oe=u||h,R=s.find(k=>k.key===w),be=k=>{if(i&&w!==k){O(k),S(!0),K(""),Q(!1);return}v(k),K(""),Q(!1)},ie=()=>{v(P),S(!1),j(!1)},Ne=k=>{j(k),k?A(""):G("")},De=k=>{if(U(k),k&&k!=="none"){const ue=l==null?void 0:l.find(Ce=>Ce.id===k),Me=(ue==null?void 0:ue.slug)||"";if(x.startsWith(Me)){const Ce=x.slice(Me.length).replace(/^\/+/,"");A(Ce)}else A(x.replace(/^\/+/,""))}else A(x?`${x}`:"")},I=k=>{Z(k)},le=()=>he.trim()?ce&&!m.isEmpty(x)?(b("Slug must be empty when using dynamic slug"),!1):ce&&!T?(b("Dynamic slug is invalid"),!1):!0:(V.toast.error("Name is required"),!1),Ee=()=>{const k={pageType:R==null?void 0:R.key,name:he,slug:"",hasSlug:!1};i?d({id:e==null?void 0:e.id,name:he},{onSuccess:()=>{V.toast.success((R==null?void 0:R.name)+" updated successfully"),n()}}):c(k,{onSuccess:ue=>{n(),r(ue.page.id,a)}})},Re=(k,ue)=>{if(!k.trim()&&!ce)return b("Child page slug is required"),!1;const Me=Ve(ue),Ce=hn(Me,k);return Object.keys(ke).some(ns=>Ce===`/${ns}`||(Ce==null?void 0:Ce.startsWith(`/${ns}/`)))?(b("Slugs cannot start with a language code for primary page"),!1):!0},Ns=(k,ue)=>{const Me=Ve(ue),Ce=hn(Me,k),Oe={pageType:w,name:he,slug:Ce.replace(/\/$/,""),parent:_,dynamic:ce,hasSlug:!0,template:F||void 0,tracking:{},seo:{},jsonLD:{}};if(ce&&(Oe.dynamicSlugCustom=M),i)d({id:e==null?void 0:e.id,...Oe},{onSuccess:()=>{V.toast.success("Page updated successfully"),n()}});else{const Fe=m.find(s,{key:w});Fe!=null&&Fe.trackingDefault&&(Oe.tracking=Fe.trackingDefault);const{seo:ns,jsonLD:Xa}=us(Fe,se);m.set(Oe,"seo",ns),m.set(Oe,"jsonLD",Xa),c(Oe,{onSuccess:Za=>{n(),r(Za.page.id,a)}})}},Cs=()=>{const k={pageType:w,name:he,slug:x===""?"/":`/${x.replace(/\/$/,"")}`,template:F||void 0,parent:null,tracking:{}};if(i)d({id:e==null?void 0:e.id,...k},{onSuccess:()=>{V.toast.success("Page updated successfully"),n()}});else{const ue=m.find(s,{key:w});ue!=null&&ue.trackingDefault&&(k.tracking=ue.trackingDefault);const{seo:Me,jsonLD:Ce}=us(ue,se);m.set(k,"seo",Me),m.set(k,"jsonLD",Ce),c(k,{onSuccess:Oe=>{var Fe;(Fe=Oe==null?void 0:Oe.page)!=null&&Fe.id&&r(Oe.page.id,a),n()}})}},ts=k=>{if(k.preventDefault(),b(null),!!le()){if(!(R!=null&&R.hasSlug)){Ee();return}if(_&&_!=="none"){const ue=l==null?void 0:l.find(Ce=>Ce.id===_),Me=(ue==null?void 0:ue.slug)||"";if(!Re(x,Me))return;Ns(x,Me)}else Cs()}},{pagesType:rt,partialsType:it}=f.useMemo(()=>{const k=ue=>H?ue.name.toLowerCase().includes(H.toLowerCase())||ue.key.toLowerCase().includes(H.toLowerCase()):!0;return{pagesType:s.filter(ue=>ue.hasSlug!==!1&&k(ue)),partialsType:s.filter(ue=>ue.hasSlug===!1&&k(ue))}},[s,H]);return i&&!(R!=null&&R.hasSlug)?t.jsxs("form",{onSubmit:ts,className:"mx-auto w-full max-w-md space-y-4",children:[t.jsxs("div",{className:"space-y-0.5",children:[t.jsx(o.Label,{htmlFor:"pageType",className:"text-sm",children:"Type"}),t.jsxs(o.Popover,{open:te,onOpenChange:Q,children:[t.jsx(o.PopoverTrigger,{asChild:!0,children:t.jsxs(o.Button,{variant:"outline",role:"combobox",disabled:i&&!C,className:tt("w-full justify-between",i&&!C?"cursor-not-allowed text-gray-500":""),children:[(R==null?void 0:R.name)||"Select page type",t.jsx(E.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),t.jsx(o.PopoverContent,{className:"w-[var(--radix-popover-trigger-width)] p-0",align:"start",children:t.jsxs(o.Command,{shouldFilter:!1,children:[t.jsx("div",{className:"sticky top-0 z-10 bg-white px-3 py-2",children:t.jsxs("div",{className:"relative",children:[t.jsx(E.Search,{strokeWidth:2,className:"absolute left-2 top-2 h-4 w-4 text-gray-400"}),t.jsx(o.Input,{placeholder:"Search page types...",className:"h-8 pl-8 text-xs",value:H,onChange:k=>K(k.target.value)})]})}),t.jsxs(cs,{className:"max-h-[200px] overflow-y-auto",children:[t.jsx(o.CommandEmpty,{children:"No page type found."}),t.jsx(o.CommandGroup,{heading:"Partials",children:it.map(k=>t.jsxs(o.CommandItem,{value:k.key,onSelect:()=>{be(k.key),Q(!1)},className:"flex cursor-pointer items-center justify-between",children:[k.name,t.jsx(E.Check,{className:tt("mr-2 h-4 w-4",w===k.key?"opacity-100":"opacity-0")})]},k.key))})]})]})})]}),B&&t.jsxs("div",{className:"mt-2 rounded-md border border-yellow-200 bg-yellow-50 p-3",children:[t.jsx("p",{className:"text-sm text-yellow-800",children:"Changing the page type may impact the page data. Are you sure you want to proceed?"}),t.jsxs("div",{className:"mt-2 flex gap-2",children:[t.jsx(o.Button,{variant:"outline",size:"sm",onClick:()=>S(!1),children:"Cancel"}),t.jsx(o.Button,{variant:"default",size:"sm",onClick:ie,children:"Confirm"})]})]}),t.jsx("p",{className:"text-xs text-gray-500",children:(Pt=s.find(k=>k.key===w))==null?void 0:Pt.helpText})]}),t.jsxs("div",{className:"space-y-0.5",children:[t.jsx(o.Label,{htmlFor:"name",className:"text-sm",children:"Name"}),t.jsx(o.Input,{id:"name",value:he,onChange:k=>ye(k.target.value),required:!0,"aria-required":"true"})]}),t.jsx(o.Button,{disabled:oe,type:"submit",className:"w-full",children:i?oe?"Updating...":"Update "+(R==null?void 0:R.name):oe?"Creating...":"Create "+(R==null?void 0:R.name)})]}):t.jsxs("form",{onSubmit:ts,className:"mx-auto w-full max-w-md space-y-4",children:[t.jsxs("div",{className:"space-y-0.5",children:[t.jsx(o.Label,{htmlFor:"pageType",className:"text-sm",children:"Type"}),t.jsxs(o.Popover,{open:te,onOpenChange:Q,children:[t.jsx(o.PopoverTrigger,{asChild:!0,children:t.jsxs(o.Button,{variant:"outline",role:"combobox",disabled:i&&!C,className:tt("w-full justify-between",i&&!C?"cursor-not-allowed text-gray-500":""),children:[(R==null?void 0:R.name)||"Select page type",t.jsx(E.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),t.jsx(o.PopoverContent,{className:"w-[var(--radix-popover-trigger-width)] p-0",align:"start",children:t.jsxs(o.Command,{shouldFilter:!1,children:[t.jsx("div",{className:"sticky top-0 z-10 bg-white px-3 py-2",children:t.jsxs("div",{className:"relative",children:[t.jsx(E.Search,{strokeWidth:2,className:"absolute left-2 top-2 h-4 w-4 text-gray-400"}),t.jsx(o.Input,{placeholder:"Search page types...",className:"h-8 pl-8 text-xs",value:H,onChange:k=>K(k.target.value)})]})}),t.jsxs(cs,{className:"overflow-y-auto",children:[t.jsx(o.CommandEmpty,{children:"No page type found."}),i?ne?t.jsx(o.CommandGroup,{heading:"Partials",children:it.map(k=>t.jsxs(o.CommandItem,{value:k.key,onSelect:()=>be(k.key),className:"flex cursor-pointer items-center justify-between",children:[k.name,t.jsx(E.Check,{className:tt("mr-2 h-4 w-4",w===k.key?"opacity-100":"opacity-0")})]},k.key))}):t.jsx(o.CommandGroup,{heading:"Pages",children:rt.map(k=>t.jsxs(o.CommandItem,{value:k.key,onSelect:()=>be(k.key),className:"flex cursor-pointer items-center justify-between",children:[k.name,t.jsx(E.Check,{className:tt("mr-2 h-4 w-4",w===k.key?"opacity-100":"opacity-0")})]},k.key))}):t.jsxs(t.Fragment,{children:[rt.length>0&&t.jsx(o.CommandGroup,{heading:"Pages",children:rt.map(k=>t.jsxs(o.CommandItem,{value:k.key,onSelect:()=>be(k.key),className:"flex cursor-pointer items-center justify-between",children:[k.name,t.jsx(E.Check,{className:tt("mr-2 h-4 w-4",w===k.key?"opacity-100":"opacity-0")})]},k.key))}),it.length>0&&t.jsx(o.CommandGroup,{heading:"Partials",children:it.map(k=>t.jsxs(o.CommandItem,{value:k.key,onSelect:()=>be(k.key),className:"flex cursor-pointer items-center justify-between",children:[k.name,t.jsx(E.Check,{className:tt("mr-2 h-4 w-4",w===k.key?"opacity-100":"opacity-0")})]},k.key))})]})]})]})})]}),B&&t.jsxs("div",{className:"mt-2 rounded-md border border-yellow-200 bg-yellow-50 p-3",children:[t.jsx("p",{className:"text-sm text-yellow-800",children:"Changing the page type may impact the page data. Are you sure you want to proceed?"}),t.jsxs("div",{className:"mt-2 flex gap-2",children:[t.jsx(o.Button,{variant:"outline",size:"sm",onClick:()=>S(!1),children:"Cancel"}),t.jsx(o.Button,{variant:"default",size:"sm",onClick:ie,children:"Confirm"})]})]})]}),!i&&(R==null?void 0:R.hasSlug)&&de.length>0&&t.jsxs("div",{className:"space-y-1",children:[t.jsx(o.Label,{className:"mb-1 block text-sm",children:"Template"}),t.jsx(ni,{templates:de,selectedTemplateId:F,onSelectTemplate:I,isLoading:ve})]}),t.jsx(ti,{pages:l,selectedParentId:_,onChange:De}),t.jsxs("div",{className:"space-y-0.5",children:[t.jsx(o.Label,{htmlFor:"name",className:"text-sm",children:"Name"}),t.jsx(o.Input,{id:"name",value:he,onChange:k=>ye(k.target.value),required:!0,"aria-required":"true",placeholder:"Enter page name"})]}),(R==null?void 0:R.dynamicSegments)&&_&&_!=="none"&&t.jsxs("div",{className:"space-y-2",children:[t.jsxs("div",{className:"flex items-center space-x-2",children:[t.jsx("input",{type:"checkbox",id:"useDynamicSlug",checked:ce,onChange:k=>Ne(k.target.checked),className:"rounded border-gray-300"}),t.jsx(o.Label,{htmlFor:"useDynamicSlug",className:"text-sm",children:"Use Dynamic Slug"})]}),ce&&t.jsx("div",{className:"space-y-2",children:t.jsx("div",{className:"space-y-0.5",children:t.jsx(ei,{value:M,onChange:G,dynamicPattern:(R==null?void 0:R.dynamicSlug)||"{{id}}",placeholder:"Enter custom slug part (optional)",onValidationChange:W})})})]}),(!(R!=null&&R.dynamicSegments)||!ce)&&t.jsxs("div",{className:"space-y-0.5",children:[t.jsx(o.Label,{htmlFor:"slug",className:"text-sm",children:"Slug"}),t.jsx(Zs,{value:x,onChange:A,placeholder:_&&_!=="none"?"Enter page slug":w==="page"?"Leave empty for home page":"Required - e.g. your-slug",parentSlug:_&&_!=="none"?(ss=l==null?void 0:l.find(k=>k.id===_))==null?void 0:ss.slug:void 0,onValidationChange:p}),g&&t.jsx("p",{className:"text-xs text-red-500",children:g})]}),t.jsx(o.Button,{disabled:oe||!y&&(!(R!=null&&R.dynamicSegments)||!ce)||ce&&!T,type:"submit",className:"w-full",children:i?oe?"Updating...":"Update page":oe?"Creating...":"Create Page"})]})}const Qn=({addEditPage:e,setAddEditPage:s,closePanel:n})=>{const{data:a}=Pe(),r=!!(e!=null&&e.id);return t.jsx(o.Dialog,{open:!!e,onOpenChange:()=>s(void 0),children:t.jsxs(o.DialogContent,{className:"sm:max-w-[425px]",children:[t.jsxs(o.DialogHeader,{children:[t.jsxs(o.DialogTitle,{children:[r?"Edit":"Add New"," "]}),t.jsx(o.DialogDescription,{children:r?"Update your page name":"Enter details to create a new page"})]}),t.jsx(li,{closePanel:n,addEditPage:e,close:()=>s(void 0),additionalPageTypes:a??[]})]})})},oi=()=>{const e=re(),s=D.useQueryClient(),n=J();return D.useMutation({mutationFn:async({pageId:a,name:r,slug:i})=>{const l={pageId:a,name:r};return i&&(l.slug=i),await n(e,{action:"DUPLICATE_PAGE",data:l})},onSuccess:()=>{s.invalidateQueries({queryKey:[Y,L.GET_WEBSITE_PAGES]}),V.toast.success("Page duplicated successfully")},onError:a=>{V.toast.error("Failed to duplicate page",{description:a.message||"An error occurred while duplicating the page"})}})},Wn=({page:e,onClose:s})=>{const{mutate:n,isPending:a}=oi(),[r,i]=f.useState(null),[l,c]=f.useState(`${e.name} (Copy)`),u=m.isEmpty(e.slug),[d,h]=f.useState(u?"":`${e.slug.split("/").pop()}-copy`),g=u?"":m.initial(e.slug.split("/")).join("/"),[b,y]=f.useState(!1),p=w=>{if(w.preventDefault(),!l.trim()){i("Name is required");return}if(!u&&!d.trim()){i("Slug is required");return}i(null),y(!0);const v={pageId:e.id,name:l};u||(v.slug=`${g}/${d}`),n(v,{onSuccess:()=>{y(!1),s()},onError:N=>{y(!1),N.code==="SLUG_EXISTS"?i("A page with this slug already exists. Please choose a different slug."):N.code==="INVALID_SLUG"?i("The slug format is invalid. Please use only lowercase letters, numbers, and hyphens."):N.code==="PERMISSION_DENIED"?i("You don't have permission to duplicate this page."):i(N.message||"Failed to duplicate page. Please try again later.")}})};return t.jsx(o.Dialog,{open:!!e,onOpenChange:s,children:t.jsxs(o.DialogContent,{className:"sm:max-w-[425px]",children:[t.jsxs(o.DialogHeader,{children:[t.jsx(o.DialogTitle,{children:"Duplicate Page"}),t.jsx(o.DialogDescription,{children:"Create a copy of the page with a new name and slug"})]}),t.jsxs("div",{className:"bg-gray-50 p-3 rounded-md mb-4",children:[t.jsx("h3",{className:"text-sm font-medium mb-1",children:"Duplicating:"}),t.jsxs("div",{className:"text-sm text-gray-700 flex flex-col gap-1",children:[t.jsxs("div",{children:[t.jsx("span",{className:"font-medium",children:"Name:"})," ",e.name]}),!u&&t.jsxs("div",{children:[t.jsx("span",{className:"font-medium",children:"Slug:"})," ",e.slug]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-medium",children:"Type:"})," ",e.pageType]})]})]}),t.jsxs("form",{onSubmit:p,className:"space-y-4",children:[t.jsxs("div",{className:"space-y-2",children:[t.jsx(o.Label,{htmlFor:"name",className:"text-sm",children:"Name"}),t.jsx(o.Input,{id:"name",value:l,onChange:w=>c(w.target.value),required:!0})]}),!u&&t.jsxs("div",{className:"space-y-2",children:[t.jsx(o.Label,{htmlFor:"slug",className:"text-sm",children:"Slug"}),t.jsx(Zs,{value:d,onChange:w=>h(w),parentSlug:g,onValidationChange:w=>{i(w?null:"Invalid slug")}})]}),r&&t.jsxs(o.Alert,{variant:"destructive",className:"py-2",children:[t.jsx(E.AlertCircle,{className:"h-4 w-4"}),t.jsx("span",{className:"text-sm",children:r})]}),t.jsxs("div",{className:"flex justify-end gap-2",children:[t.jsx(o.Button,{type:"button",variant:"outline",onClick:s,disabled:a,children:"Cancel"}),t.jsx(o.Button,{type:"submit",disabled:!l.trim()||!u&&!d.trim()||a||b,children:a||b?"Duplicating...":"Duplicate"})]})]})]})})},ci=1*1024*1024,Yn=({page:e,onClose:s})=>{const[n,a]=f.useState(!1),[r,i]=f.useState(""),[l,c]=f.useState(""),[u,d]=f.useState(!1),h=f.useRef(null),g=zr(),{data:b}=Pe(),y=b==null?void 0:b.find(B=>B.key===e.pageType),p=(y==null?void 0:y.name)||m.startCase(e.pageType),w=f.useCallback(B=>{var P;const S=(P=B.target.files)==null?void 0:P[0];if(S){if(S.size>ci){V.toast.error("File too large",{description:`Maximum file size is 1MB. Selected file is ${(S.size/1024).toFixed(2)}KB.`}),h.current&&(h.current.value="");return}try{d(!0);const O=new FileReader;O.onloadend=()=>{c(O.result),d(!1)},O.readAsDataURL(S)}catch(O){console.error("Error reading file:",O),d(!1),V.toast.error("Failed to process image",{description:O instanceof Error?O.message:"Unknown error"})}}},[]),v=()=>{c(""),h.current&&(h.current.value="")},N=()=>{var B;(B=h.current)==null||B.click()},C=()=>{a(!0),g.mutate({page:e,name:e.name,description:r.trim()||void 0,pageType:e.pageType,...l?{previewImage:l}:{}},{onSuccess:()=>{a(!1),s()},onError:()=>{a(!1)}})};return t.jsx(o.Dialog,{open:!0,onOpenChange:s,children:t.jsxs(o.DialogContent,{children:[t.jsxs(o.DialogHeader,{children:[t.jsx(o.DialogTitle,{children:"Mark as template"}),t.jsxs(o.DialogDescription,{className:"py-4 text-slate-500 space-y-1 text-xs",children:["Are you sure you want to mark this page as a template?",t.jsx("br",{}),"Templates can be used to create new pages with the same content."]})]}),t.jsxs("div",{className:"space-y-4 mb-4 text-xs",children:[t.jsxs("div",{className:"p-4 border rounded bg-slate-50 space-y-3",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(E.Tag,{className:"w-4 h-4 text-slate-500"}),t.jsx("span",{className:"font-medium text-slate-500",children:"Page Name:"}),t.jsx("span",{className:"font-semibold",children:m.startCase(e.name)})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(E.File,{className:"w-4 h-4 text-slate-500"}),t.jsx("span",{className:"font-medium text-slate-500",children:"Type:"}),t.jsx("span",{className:"font-semibold",children:p})]})]}),t.jsxs("div",{children:[t.jsx(o.Label,{htmlFor:"description",className:"text-xs font-medium",children:"Description (Optional)"}),t.jsx(o.Textarea,{id:"description",placeholder:"Describe this template's purpose",className:"text-xs resize-none h-24 mt-1",value:r,onChange:B=>i(B.target.value)})]}),t.jsxs("div",{className:"space-y-2",children:[t.jsx(o.Label,{htmlFor:"previewImage",className:"text-xs font-medium",children:"Preview Image (Optional)"}),t.jsxs("div",{className:"space-y-2",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(o.Input,{type:"file",id:"previewImage",ref:h,onChange:w,accept:"image/*",className:"hidden"}),t.jsx(o.Button,{type:"button",variant:"outline",onClick:N,disabled:u,className:"w-full",children:u?t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsx("div",{className:"animate-spin h-4 w-4 border-2 border-current border-t-transparent rounded-full"}),"Uploading..."]}):t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsx(E.ImageIcon,{className:"h-4 w-4"}),"Select image"]})}),l&&t.jsx(o.Button,{type:"button",variant:"outline",size:"icon",onClick:v,children:t.jsx(E.X,{className:"h-4 w-4"})})]}),l&&t.jsx("div",{className:"rounded-md overflow-hidden border aspect-video",children:t.jsx("img",{src:l,alt:"Preview",className:"w-full h-full max-h-[200px] object-contain"})}),t.jsx("p",{className:"text-xs text-muted-foreground",children:"max 1mb"})]})]})]}),t.jsxs(o.DialogFooter,{className:n?"opacity-75 pointer-events-none":"",children:[t.jsx(o.Button,{variant:"outline",onClick:B=>{B.stopPropagation(),s()},children:"Cancel"}),t.jsx(o.Button,{variant:"default",disabled:n,onClick:C,children:"Mark as template"})]})]})})},Jn=({page:e,setDuplicatePage:s,setAddEditPage:n,setUnpublishPage:a,setDeletePage:r,setMarkAsTemplate:i,setUnmarkAsTemplate:l,children:c})=>{const{hasPermission:u}=q.usePermissions(),{data:d}=Pe(),h=f.useMemo(()=>m.find(d,{key:e.pageType}),[d,e.pageType]),g=f.useMemo(()=>!!e.isTemplate,[e.isTemplate]),b=f.useMemo(()=>!!(h!=null&&h.hasSlug),[h==null?void 0:h.hasSlug]);return!u(je.EDIT_PAGE)&&!u(je.DELETE_PAGE)&&!u(je.UNPUBLISH_PAGE)||!e?null:t.jsxs(o.DropdownMenu,{children:[t.jsx(o.DropdownMenuTrigger,{asChild:!0,onClick:p=>p.stopPropagation(),children:c}),t.jsxs(o.DropdownMenuContent,{align:"center",className:"text-sm",children:[u(je.ADD_PAGE)&&t.jsxs(o.DropdownMenuItem,{className:"flex items-center gap-2 cursor-pointer",onClick:p=>{p.stopPropagation(),s(e)},children:[t.jsx(E.CopyPlusIcon,{className:"size-3"}),"Duplicate page"]}),u(je.EDIT_PAGE)&&t.jsxs(o.DropdownMenuItem,{className:"flex items-center gap-2 cursor-pointer",onClick:p=>{p.stopPropagation(),n({...e,global:!(h!=null&&h.hasSlug)})},children:[t.jsx(E.Pencil,{className:"size-3"}),"Edit"]}),(e==null?void 0:e.online)&&u(je.UNPUBLISH_PAGE)&&t.jsxs(o.DropdownMenuItem,{className:"flex items-center gap-2 cursor-pointer",onClick:p=>{p.stopPropagation(),a(e)},children:[t.jsx(E.Power,{className:"size-3"}),ae.UNPUBLISH]}),u(je.DELETE_PAGE)&&t.jsxs(o.DropdownMenuItem,{className:"flex items-center gap-2 cursor-pointer",onClick:p=>{p.stopPropagation(),r(e)},children:[t.jsx(E.Trash,{className:"size-3"}),ae.DELETE]}),u(je.MARK_AS_TEMPLATE)&&b&&t.jsx(t.Fragment,{children:g?t.jsxs(o.DropdownMenuItem,{className:"flex items-center gap-2 cursor-pointer",onClick:p=>{p.stopPropagation(),l(e)},children:[t.jsx(E.SquareLibrary,{className:"size-3"}),ae.UNMARK_AS_TEMPLATE]}):t.jsxs(o.DropdownMenuItem,{className:"flex items-center gap-2 cursor-pointer",onClick:p=>{p.stopPropagation(),i(e)},children:[t.jsx(E.SquareLibrary,{className:"size-3"}),ae.MARK_AS_TEMPLATE]})})]})]})},Xn=({page:e,onClose:s})=>{const[n,a]=f.useState(!1),r=$r(),i=()=>{a(!0),r.mutate(e,{onSuccess:()=>{a(!1),s()},onError:()=>{a(!1)}})};return t.jsx(o.Dialog,{open:!0,onOpenChange:s,children:t.jsxs(o.DialogContent,{children:[t.jsxs(o.DialogHeader,{children:[t.jsx(o.DialogTitle,{children:"Unmark as template"}),t.jsx(o.DialogDescription,{className:"py-4 text-slate-500 space-y-1 text-xs",children:"Are you sure you want to unmark this page as a template?"})]}),t.jsxs(o.DialogFooter,{className:n?"opacity-75 pointer-events-none":"",children:[t.jsx(o.Button,{variant:"outline",onClick:l=>{l.stopPropagation(),s()},children:"Cancel"}),t.jsx(o.Button,{variant:"default",disabled:n,onClick:i,children:"Unmark as template"})]})]})})},ui=_n("expandedPagesState",[]),tn=e=>m.flatMap(e,s=>[s,...s.children?tn(s.children):[]]),di=(e,s)=>{const n=(a,r=[])=>{for(const i of a){const l=[...r,i.id];if(i.id===s)return l;if(i.children&&i.children.length>0){const c=n(i.children,l);if(c)return c}}return null};return n(e)||[]},Zn=(e,s)=>{if(!s)return[];const n=tn(e),a=m.find(n,r=>r.id===s);if(a){if(a.parent)return[...Zn(e,a.parent),s];const r=di(e,s);if(!m.isEmpty(r))return r}return[s]},mi=e=>{const s=new Set,n=(a,r=[])=>{a.forEach(i=>{const l=[...r,i.id];i.shouldExpandOnSearch&&l.forEach(c=>s.add(c)),i.children&&!m.isEmpty(i.children)&&n(i.children,l)})};return n(e),Array.from(s)},ea=e=>{const[s,n]=Ie.useAtom(ui),a=e?m.includes(s,e):!1,r=f.useCallback(()=>{n(d=>a?m.filter(d,h=>h!==e):[...d,e])},[n,a,e]),i=f.useCallback((d,h)=>{if(!h||m.isEmpty(d))return;const g=tn(d),b=Zn(g,h);if(!Array.isArray(b)||m.isEmpty(b))return;const y=b.slice(0,-1);m.isEmpty(y)||n(p=>m.uniq([...p,...y]))},[n]),l=f.useCallback(d=>{if(m.isEmpty(d))return;const h=mi(d);m.isEmpty(h)||n(g=>m.union(g,h))},[n]),c=f.useCallback(d=>{if(m.isEmpty(d))return;const h=m.flatMap(d,g=>{const b=y=>[y.id,...y.children?m.flatMap(y.children,b):[]];return b(g)});n(h)},[n]),u=f.useCallback(()=>{n([])},[n]);return{isExpanded:a,toggleExpanded:r,updateForSelectedPage:i,expandedPages:s,expandPagesOnSearch:l,setExpandedPages:n,expandAll:c,collapseAll:u}},fn=(e,s)=>!e||!Array.isArray(e)?[]:m.isEmpty(s)?e:m.compact(m.filter(e,n=>{const a=m.toLower(s);return m.includes(m.toLower((n==null?void 0:n.name)||""),a)||m.includes(m.toLower((n==null?void 0:n.slug)||""),a)})),hi=(e,s)=>{const n=new Set,a=m.keyBy(e,"id");return s.forEach(r=>{let i=r;for(;i.parent&&a[i.parent];)n.add(i.parent),i=a[i.parent]}),Array.from(n).map(r=>a[r])},_s=(e,s,n)=>m.isEmpty(s)?e:e.map(a=>{if(!n(a.pageType))return{...a,shouldExpandOnSearch:!0,children:a.children?_s(a.children,s,n):[]};const r=a.children&&a.children.some(i=>m.includes(m.toLower(i.name||""),m.toLower(s))||m.includes(m.toLower(i.slug||""),m.toLower(s)));return{...a,shouldExpandOnSearch:r,children:a.children?_s(a.children,s,n):[]}}),fi=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},ta=e=>!e||!e.length?[]:[...e].sort((n,a)=>(n.name||"").localeCompare(a.name||"")).map(n=>({...n,children:n.children?ta(n.children):[]})),gi=(e,s,n,a)=>{if(!e||!e.length)return[];let r=e;if(n!=="all"&&(r=m.compact(m.filter(e,{pageType:n}))),m.isEmpty(s))r=fn(r,s);else{const h=fn(r,s),g=hi(e,h);r=m.uniqBy([...h,...g],"id")}const i=ta(fi(r)),l=_s(i,s,a),c=m.filter(l,h=>a(h.pageType)).sort((h,g)=>(h.name||"").localeCompare(g.name||"")),u=m.keyBy(m.filter(l,h=>!a(h.pageType)),"pageType"),d=Object.values(m.mapValues(u,(h,g)=>({...h,name:m.startCase(g),isPartialGroup:!0,children:l.filter(b=>b.pageType===g)})));return[...c,...d]},xi=({parentSlug:e,page:s,active:n,closePanel:a,setUnpublishPage:r,setDeletePage:i,setAddEditPage:l,setMarkAsTemplate:c,setUnmarkAsTemplate:u,setDuplicatePage:d,hasChildren:h,isExpanded:g,onToggleExpand:b})=>{const y=en(),{data:p}=Pe(),[,w]=q.useSidebarActivePanel(),v=f.useMemo(()=>m.find(p,{key:s.pageType}),[p,s.pageType]),N=f.useMemo(()=>{const P=m.get(s,"slug",""),O=e?Ve(e):"",z=O?P.replace(O,""):P;return z||"/"},[s,e]),C=f.useMemo(()=>!!s.isTemplate,[s.isTemplate]),B=f.useCallback(()=>{w("outline"),y(m.get(s,"id"),a)},[y,a,s,w]),S=f.useCallback(P=>{P.stopPropagation(),b()},[b]);return t.jsxs("div",{onClick:B,className:`rounded flex p-1.5 items-center justify-between leading-none cursor-pointer px-3 py-1.5 ${n?"bg-gray-200":"hover:bg-gray-100"}`,children:[t.jsxs("div",{className:"flex items-center gap-x-2",children:[t.jsx("button",{onClick:S,disabled:!h,className:`flex items-center justify-center w-4 h-5 text-gray-400 hover:text-gray-500 transition-colors ${h?"hover:text-blue-400":"opacity-0"}`,children:t.jsx(E.ChevronRight,{size:16,className:`w-4 h-5 transition-transform duration-200 ${g?"rotate-90":""}`})}),s.dynamic?t.jsx("div",{className:"w-4 h-4 text-slate-500 stroke-[1]",children:t.jsx(E.StarsIcon,{className:"w-4 h-4 text-yellow-400"})}):v!=null&&v.icon?t.jsx("div",{className:"w-4 h-4 text-slate-500 stroke-[1]",dangerouslySetInnerHTML:{__html:v.icon}}):v!=null&&v.hasSlug?t.jsx(E.File,{className:"w-4 h-4 text-slate-500 stroke-[1]"}):t.jsx(E.Globe,{className:"w-4 h-4 text-slate-500 stroke-[1]"}),!s.isPartialGroup&&t.jsx("div",{className:`w-2.5 h-2.5 rounded-full ${s.online?"bg-green-300":"bg-gray-300"}`}),t.jsx("span",{className:"font-light leading-none truncate text-slate-800",children:s.name}),v!=null&&v.hasSlug?t.jsxs(o.Badge,{variant:"outline",className:`ml-2 text-xs max-w-full leading-tight py-px font-normal rounded-full text-gray-400 border ${n?"border-gray-300":"border-gray-200"}`,children:[N,s.dynamic&&t.jsxs("span",{className:"text-xs font-light leading-none text-slate-500",children:[m.endsWith(N,"/")?`${v==null?void 0:v.dynamicSlug}`:`/${v==null?void 0:v.dynamicSlug}`,s.dynamicSlugCustom]})]}):s.isPartialGroup?null:t.jsx(o.Badge,{variant:"outline",className:`ml-2 text-xs max-w-full leading-tight py-px font-normal rounded-full text-gray-400 border ${n?"border-gray-300":"border-gray-200"}`,children:v==null?void 0:v.name}),C&&t.jsx(o.Badge,{variant:"outline",className:"ml-2 text-xs py-0 font-normal text-blue-500 border border-blue-200 bg-blue-50",children:"Template"})]}),!s.isPartialGroup&&t.jsxs("div",{className:"flex items-center space-x-4",children:[t.jsx(Er,{currentEditor:s.currentEditor}),t.jsx(Jn,{page:s,setDuplicatePage:d,setAddEditPage:l,setUnpublishPage:r,setDeletePage:i,setMarkAsTemplate:c,setUnmarkAsTemplate:u,children:t.jsx("div",{className:"p-0.5 m-0 hover:bg-white rounded duration-100 cursor-pointer",children:t.jsx(E.MoreHorizontal,{className:"w-4 h-4",onClick:P=>P.stopPropagation()})})})]})]})},pi=({close:e,isOpen:s})=>{const[,n]=f.useState([]),[a,r]=f.useState(null),[i,l]=f.useState(""),[c,u]=f.useState(""),[d,h]=f.useState(null),g=T=>c?String(m.get(T,"name","")).toLowerCase().includes(c.toLowerCase())||String(m.get(T,"key","")).toLowerCase().includes(c.toLowerCase()):!0,[b,y]=f.useState(null),[p,w]=f.useState(null),[v,N]=f.useState(null),[C,B]=f.useState(null),{data:S,isFetching:P,refetch:O}=Zt(),[z,$]=f.useState(""),{hasPermission:se}=q.usePermissions(),{updateForSelectedPage:H,expandPagesOnSearch:K,expandAll:te,collapseAll:Q}=ea(null),[ne,_]=_e(),U=ne.get("page"),he=f.useRef(null),{data:ye}=Pe(),ce=f.useCallback(T=>{var W;return(W=m.find(ye,{key:T}))==null?void 0:W.hasSlug},[ye]);f.useEffect(()=>{s&&O()},[s,O]),f.useEffect(()=>{if(!m.isEmpty(z))return;const T=sessionStorage.getItem("pageTypeFilter")||"all";!m.isEmpty(ye)&&T&&(m.find(ye,{key:T})?$(T):$("all"))},[ye,z]);const j=T=>{$(T),sessionStorage.setItem("pageTypeFilter",T),u("")},x=f.useCallback(T=>{const F=new URLSearchParams(window.location.search).get("lang"),Z=new URLSearchParams({page:T});F&&Z.set("lang",F),window.history.pushState({},"",`?${Z.toString()}`),_(Z),window.dispatchEvent(new PopStateEvent("popstate")),e()},[_,e]);f.useEffect(()=>{if(U&&!P){const T=m.find(S,{id:U});T&&(T!=null&&T.pageType)?n(W=>[...W,T==null?void 0:T.pageType]):(window.history.replaceState(null,"","/"),_(new URLSearchParams({})),window.dispatchEvent(new PopStateEvent("popstate")))}},[S,U,P,_]);const A=f.useMemo(()=>S?gi(S,i,z,ce):[],[S,i,z,ce]);f.useEffect(()=>{U&&!P&&!m.isEmpty(A)&&(H(A,U),he.current&&he.current.scrollIntoView({behavior:"smooth",block:"end"}))},[U,P,A,H]),f.useEffect(()=>{!m.isEmpty(i)&&!m.isEmpty(A)&&K(A)},[i,A,K]);const M=f.useCallback(()=>{te(A)},[te,A]),G=f.useCallback(()=>{Q()},[Q]);return t.jsxs("div",{className:"flex flex-col justify-between h-full",children:[t.jsxs("div",{className:"flex flex-col h-full space-y-6",children:[t.jsxs("div",{className:"flex gap-1 items-center justify-between",children:[t.jsxs("div",{className:"relative flex item-center gap-x-4 flex-1",children:[t.jsx(E.Search,{strokeWidth:2.5,className:"absolute left-3 top-2.5 h-4 w-4 text-gray-400"}),t.jsx(o.Input,{placeholder:"Search pages...",className:"text-xs font-medium leading-none text-gray-700 pl-9 pr-24 placeholder:text-gray-400",value:i,onChange:T=>l(T.target.value)}),!m.isEmpty(z)&&t.jsxs(o.Select,{value:z,onValueChange:j,children:[t.jsx(o.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(o.SelectValue,{placeholder:"Select page type"})}),t.jsxs(o.SelectContent,{align:"end",children:[t.jsx("div",{className:"px-3 py-2 sticky top-0 bg-white z-10",children:t.jsxs("div",{className:"relative",children:[t.jsx(E.Search,{strokeWidth:2,className:"absolute left-2 top-2 h-4 w-4 text-gray-400"}),t.jsx(o.Input,{placeholder:"Search page types...",className:"pl-8 h-8 text-xs",value:c,onChange:T=>u(T.target.value),onKeyDown:T=>T.stopPropagation()})]})}),t.jsx(o.SelectItem,{value:"all",children:"All"},"all"),!m.isEmpty(m.filter(ye,T=>T.hasSlug&&g(T)))&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"px-2 py-1.5 text-xs font-semibold text-gray-500 mt-2 border-t pt-2",children:"Pages"}),m.map([...m.filter(ye,T=>T.hasSlug&&g(T))].sort((T,W)=>m.get(T,"name","").localeCompare(m.get(W,"name",""))),T=>t.jsx(o.SelectItem,{value:m.get(T,"key"),children:m.get(T,"name")},m.get(T,"key")))]}),!m.isEmpty(m.filter(ye,T=>!T.hasSlug&&g(T)))&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"px-2 py-1.5 text-xs font-semibold text-gray-500 mt-2 border-t pt-2",children:"Partials"}),m.map([...m.filter(ye,T=>!T.hasSlug&&g(T))].sort((T,W)=>m.get(T,"name","").localeCompare(m.get(W,"name",""))),T=>t.jsx(o.SelectItem,{value:m.get(T,"key"),children:m.get(T,"name")},m.get(T,"key")))]}),m.isEmpty(m.filter(ye,g))&&t.jsx("div",{className:"px-3 py-2 text-sm text-gray-500 text-center",children:"No matching page types found"})]})]})]}),t.jsxs("div",{className:"flex gap-1 ",children:[t.jsx(o.Button,{variant:"outline",size:"icon",onClick:M,className:"p-1 text-gray-500",children:t.jsx(E.ChevronsUpDown,{})}),t.jsx(o.Button,{variant:"outline",size:"icon",onClick:G,className:"p-1 text-gray-500",children:t.jsx(E.ChevronsDownUp,{})})]})]}),P?t.jsx("div",{className:"space-y-2",children:m.map([...Array(5).keys()],T=>t.jsx("div",{className:"w-full bg-gray-200 rounded h-9 animate-pulse"},T))}):m.isEmpty(A)?t.jsxs("div",{className:"h-[70vh] flex flex-col gap-y-1 items-center justify-center text-slate-500 text-sm font-medium",children:[t.jsx(E.File,{className:"h-6 w-6 stroke-[1]"}),"Empty List!",t.jsx("span",{className:"font-light",children:"Add new page to start"})]}):t.jsx("div",{className:"text-sm text-slate-700 space-y-2 h-[70vh] overflow-y-auto",children:m.map(A,T=>{const W=T.id===U;return t.jsx("div",{ref:W?he:null,children:t.jsx(sa,{item:T,currentPage:U,close:e,setUnpublishPage:y,setDeletePage:h,setAddEditPage:w,setMarkAsTemplate:N,setUnmarkAsTemplate:B,setDuplicatePage:r,level:0})},`page-item-${T.id}`)})})]}),se(je.ADD_PAGE)&&t.jsxs(o.Button,{className:"flex text-sm gap-x-2",onClick:()=>{w({slug:"",name:"",pageType:z==="all"?"page":z})},children:[t.jsx(E.Plus,{className:"w-4 h-4"})," Add New"]}),p&&t.jsx(Qn,{closePanel:e,editPage:x,addEditPage:p,setAddEditPage:w}),d&&t.jsx(Xs,{page:d,onClose:()=>h(null)}),b&&t.jsx(bs,{page:b,onClose:()=>y(null)}),v&&t.jsx(Yn,{page:v,onClose:()=>N(null)}),C&&t.jsx(Xn,{page:C,onClose:()=>B(null)}),a&&t.jsx(Wn,{page:a,onClose:()=>r(null)})]})},sa=({item:e,currentPage:s,close:n,setUnpublishPage:a,setDeletePage:r,setAddEditPage:i,setMarkAsTemplate:l,setUnmarkAsTemplate:c,setDuplicatePage:u,parentSlug:d,level:h=0})=>{const g=!m.isEmpty(e==null?void 0:e.children),{isExpanded:b,toggleExpanded:y}=ea(e==null?void 0:e.id);return t.jsxs("div",{className:"border-0",children:[t.jsx(xi,{closePanel:n,setUnpublishPage:a,setDeletePage:r,setAddEditPage:i,setMarkAsTemplate:l,setUnmarkAsTemplate:c,setDuplicatePage:u,active:s===e.id,page:e,parentSlug:d,hasChildren:g,isExpanded:b,onToggleExpand:y}),g&&b&&t.jsx("div",{className:"pt-2 pl-6 bg-white",children:m.map(m.get(e,"children",[]),p=>t.jsx(sa,{item:p,currentPage:s,close:n,setUnpublishPage:a,setDeletePage:r,setAddEditPage:i,setMarkAsTemplate:l,setUnmarkAsTemplate:c,setDuplicatePage:u,parentSlug:e.slug,level:h+1},p.id||`child-${h}-${p.key}`))})]},e.id||`level-${h}-${e.key}`)},yi=({isDefaultLang:e,searchQuery:s,setSearchQuery:n})=>t.jsx(o.Input,{type:"text",autoFocus:!0,value:e?s:"",onChange:a=>n(a.target.value),placeholder:e?"Search pages...":"To search select default language",disabled:!e}),ji=({dynamicPage:e,setDynamicPage:s,searchQuery:n,setSearchQuery:a,dynamicPages:r})=>{const{selectedLang:i,fallbackLang:l}=q.useLanguages(),c=(i==null?void 0:i.length)===0;return t.jsxs(o.DropdownMenu,{children:[t.jsx(o.DropdownMenuTrigger,{asChild:!0,children:t.jsxs(o.Button,{variant:"ghost",className:"w-max focus:outline-none focus:ring-0 border-[0px] rounded-md py-1 text-sm h-max border border-gray-200 hover:bg-gray-100 pl-4",children:[e?m.get(e,"name"):"Select Page",t.jsx(E.ChevronDown,{className:"ml-2 h-4 w-4"})]})}),t.jsxs(o.DropdownMenuContent,{className:"w-96 divide-y shadow-xl p-0 max-h-[75vh]",children:[t.jsx("div",{className:"p-1.5 bg-gray-50/30",children:t.jsx(yi,{isDefaultLang:c,searchQuery:n,setSearchQuery:a})}),(r==null?void 0:r.length)===0?t.jsx("div",{className:"h-24 text-xs flex items-center justify-center",children:"No pages found"}):r==null?void 0:r.map(u=>t.jsx(o.DropdownMenuItem,{onClick:()=>s(u),disabled:c?l!==u.lang:i!==u.lang,className:`flex flex-col justify-start cursor-pointer overflow-x-auto whitespace-nowrap no-scrollbar ${u.id===(e==null?void 0:e.id)?"bg-blue-50":"hover:bg-gray-50"}`,children:t.jsxs("div",{className:"w-full text-xs whitespace-nowrap p-1",children:[t.jsxs("div",{children:["Name : ",t.jsx("span",{className:"font-medium",children:u.name})]}),u.lang&&t.jsxs("div",{children:["Language : ",t.jsx("span",{className:"font-medium",children:ke[u.lang]})]}),t.jsxs("div",{children:["Slug :",t.jsxs("span",{className:"font-mono font-medium",children:[" ",u.slug]})]})]})},u.id))]})]})},vi=({children:e})=>t.jsx("div",{className:"z-[9999] fixed bottom-0 left-0 right-0 z-[20] flex items-center justify-center w-screen top-[50px] bg-black/30 backdrop-blur-sm",children:t.jsx("div",{className:"bg-white rounded-md p-4 shadow-xl min-w-[300px] max-w-[400px] flex flex-col items-center justify-center",children:e})}),bi=()=>{const{isPending:e,dynamicPage:s,dynamicPages:n,allLangPages:a,selectedLang:r,searchQuery:i,updateDynamicPage:l,updateSearchQuery:c,onChangeLanguage:u}=Sr(),d=f.useRef(void 0);f.useEffect(()=>{d.current!==r&&s&&(u(),d.current=r)},[r,n]);const h=a.length>0;return t.jsxs("div",{className:"relative",children:[!e&&!s&&t.jsxs(vi,{children:[t.jsx("h1",{className:"text-lg font-medium",children:h?"Select a page":"No pages found"}),t.jsx("p",{className:"text-sm text-center text-gray-600 pt-4",children:h?"Please select a page from the list in the top header. This will enable you to edit the page.":"Please add a new page"})]}),t.jsx(ji,{dynamicPage:s,setDynamicPage:l,searchQuery:i,setSearchQuery:c,dynamicPages:a})]})},wi=({page:e})=>{const[s,n]=f.useState(null),[a,r]=f.useState(null),[i,l]=f.useState(null),[c,u]=f.useState(null),[d,h]=f.useState(null),[g,b]=f.useState(null);return e?t.jsxs(t.Fragment,{children:[t.jsx(Jn,{page:e,setDuplicatePage:y=>h(y),setAddEditPage:y=>b(y),setUnpublishPage:y=>r(y),setDeletePage:y=>n(y),setMarkAsTemplate:y=>l(y),setUnmarkAsTemplate:y=>u(y),children:t.jsx("div",{className:"p-0 m-0 w-6 h-6 p-1 absolute right-2 top-1/2 -translate-y-1/2 hover:bg-gray-200 rounded duration-100 cursor-pointer",children:t.jsx(E.MoreHorizontal,{className:"w-4 h-4",onClick:y=>y.stopPropagation()})})}),g&&t.jsx(Qn,{closePanel:()=>b(null),editPage:()=>{},addEditPage:g,setAddEditPage:b}),s&&t.jsx(Xs,{page:s,onClose:()=>n(null)}),a&&t.jsx(bs,{page:a,onClose:()=>r(null)}),i&&t.jsx(Yn,{page:i,onClose:()=>l(null)}),c&&t.jsx(Xn,{page:c,onClose:()=>u(null)}),d&&t.jsx(Wn,{page:d,onClose:()=>h(null)})]}):null},Si=()=>{const e=He("logo",null);return e?t.jsx("div",{className:"max-h-9 w-full overflow-hidden pr-2",children:f.createElement(e,{})}):null},Ei=()=>{const[e]=_e(),s=e.get("page"),{data:n,isFetching:a}=Te(),[r,i]=f.useState(!1),{savePage:l}=q.useSavePage(),c=m.get(n,"dynamic",!1),u=!!s&&!m.isEmpty(n),d=!s||!a&&m.isEmpty(n)||r,h=q.useChaiFeatureFlag("dynamic-page-selector");return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex items-center gap-x-1",children:[t.jsxs("div",{className:"relative",children:[t.jsxs(o.Button,{variant:"outline",className:"flex w-full items-center space-x-2 py-1",onClick:()=>{l(),i(!0)},children:[t.jsx("div",{children:t.jsx(E.Logs,{className:"h-4 w-4"})}),t.jsxs("span",{className:"flex max-w-[200px] items-center truncate leading-tight",children:[t.jsx("span",{className:"pr-1 font-light text-slate-600",children:"Editing:"}),a?t.jsx(E.Loader,{className:"ml-2 h-4 w-4 animate-spin text-slate-400"}):m.startCase(m.get(n,"name"))??""]}),t.jsx("div",{className:`${a?"hidden":"w-2"}`})]},"template-viewer"),!a&&t.jsx(wi,{page:n})]}),c&&!a&&h&&t.jsxs(t.Fragment,{children:[t.jsx(E.ChevronRight,{size:14,className:"text-slate-500"}),t.jsx(bi,{})]})]}),t.jsx(o.Sheet,{open:d,onOpenChange:g=>!g&&u&&i(!1),children:t.jsxs(o.SheetContent,{side:"left","aria-describedby":"pages-manager-description",className:`z-50 w-full !max-w-screen-md border-border ${u?"":"sheet-hide-close-btn"}`,children:[t.jsxs(o.SheetHeader,{className:"mb-3",children:[t.jsxs(o.SheetTitle,{className:"flex items-center gap-2 text-sm font-semibold",children:[t.jsx("div",{className:"rounded-md bg-primary p-2 text-primary-foreground",children:t.jsx(E.File,{className:"h-6 w-6"})}),t.jsxs("div",{className:"flex flex-col",children:[t.jsx("span",{className:"text-sm font-semibold",children:"Pages"}),t.jsx("span",{id:"pages-manager-description",className:"text-xs text-muted-foreground",children:"Manage your site structure"})]})]}),t.jsx(o.SheetDescription,{className:"sr-only",children:"Manage your site structure"})]}),t.jsx("div",{className:"h-[calc(100vh-100px)] overflow-y-auto",children:t.jsx(pi,{isOpen:d,close:()=>i(!1)})})]})})]})},sn=({showAdd:e=!0,variant:s="ghost"})=>{const{fallbackLang:n,languages:a,selectedLang:r,setSelectedLang:i}=q.useLanguages(),l=m.isEmpty(r)?n:r,[,c]=_e();f.useEffect(()=>{const v=new URLSearchParams(window.location.search),N=v.get("lang");N&&(a.includes(N)?i(N):(v.delete("lang"),c(v),i("")))},[a,c,i]);const[u,d]=f.useState(null),{data:h}=Te(),{data:g}=Ze(),{data:b,isFetching:y}=Ke(),p=f.useMemo(()=>{const v=m.compact(m.map(m.get(g,"languages"),N=>{const C=m.find(b,{lang:N});return{key:N,value:m.get(ke,N,N),isLangPageAdded:!!C}})).filter(Boolean);return[{key:n,value:m.get(ke,n),isLangPageAdded:!0},...v]},[n,b,g]),w=v=>{i(v);const N=new URLSearchParams(window.location.search);v===n?N.delete("lang"):N.set("lang",v);const C=N.toString(),B=`${window.location.pathname}${C?`?${C}`:""}`;window.history.pushState({},"",B),c(N),window.dispatchEvent(new PopStateEvent("popstate"))};return m.isEmpty(a)||y?null:t.jsxs(t.Fragment,{children:[t.jsxs(o.DropdownMenu,{children:[t.jsx(o.DropdownMenuTrigger,{asChild:!0,className:"focus:outline-none",children:t.jsxs(o.Button,{variant:s,size:"sm",className:"ml-px h-max gap-2 py-1.5",children:[t.jsx(E.Languages,{className:"h-4 w-4"}),m.get(ke,l,l),t.jsx(E.ChevronDown,{className:"h-4 w-4"})]})}),t.jsxs(o.DropdownMenuContent,{className:"space-y-1 border-border",children:[m.map(p.filter(v=>v.isLangPageAdded),v=>t.jsxs(o.DropdownMenuItem,{className:q.mergeClasses("flex cursor-pointer items-center justify-between text-xs font-medium text-gray-800",v.key===l&&"!bg-gray-200 text-gray-700"),onClick:()=>w(v.key),children:[t.jsx("div",{className:"text-slate-600",children:v.value}),v.key===n&&t.jsxs("small",{className:"flex items-center gap-x-1 text-[9px] leading-none text-orange-500",children:[t.jsx(E.Star,{fill:"orange",className:"h-2 w-2"}),"Primary"]})]},v.value)),e&&!m.isEmpty(p.filter(v=>!v.isLangPageAdded))&&t.jsxs(t.Fragment,{children:[t.jsx(o.Separator,{}),t.jsxs(o.Button,{size:"sm",variant:"ghost",onClick:()=>{d({name:h==null?void 0:h.name,pageType:h==null?void 0:h.pageType,lang:"",slug:"",edit:!1})},className:"text-xs font-normal duration-200 hover:bg-slate-300 hover:text-slate-800",children:[t.jsx(E.Plus,{className:"mr-1 h-3 w-3"})," Add Langauge"]})]})]})]}),u&&t.jsx(Kn,{languages:a,langProps:u,onClose:()=>d(null)})]})};function Ni(){return t.jsxs("div",{className:"relative z-10 flex items-center justify-end gap-1",children:[t.jsx(Si,{}),t.jsx(Ei,{})]})}function Ci(e){const s=re(),n=J();return D.useQuery({queryKey:[Y,"revisions",e],queryFn:async()=>await n(s,{action:L.GET_PAGE_REVISIONS,data:{pageId:e}}),enabled:!!e,gcTime:0,staleTime:0})}const Ai=()=>{const e=re(),s=J(),n=D.useQueryClient();return D.useMutation({mutationFn:async a=>await s(e,{action:L.DELETE_PAGE_REVISION,data:{revisionId:a}}),onSuccess:()=>{n.invalidateQueries({queryKey:[Y,"revisions"]})}})},Ti=()=>{const e=re(),s=J(),n=D.useQueryClient();return D.useMutation({mutationFn:async({revisionId:a,discardCurrent:r})=>await s(e,{action:L.RESTORE_PAGE_REVISION,data:{revisionId:a,discardCurrent:r}}),onSuccess:()=>{n.invalidateQueries({queryKey:[Y,"revisions"]})}})};function Pi(){const{data:e}=Te(),{saveState:s}=q.useSavePage(),[n]=vs();return e?t.jsx("div",{className:"flex items-start gap-3 rounded-md border p-2 hover:bg-accent/50 bg-primary/5 mb-4",children:t.jsxs("div",{className:"flex-1 space-y-1",children:[t.jsx("div",{className:"flex items-center justify-between",children:t.jsx("p",{className:"text-sm flex items-center gap-1 font-medium leading-none",children:t.jsx("span",{className:"font-bold",children:"Currently editing"})})}),t.jsx("div",{className:"flex items-center text-xs text-muted-foreground",children:!m.isEmpty(n.lastSaved)&&t.jsxs("span",{children:["Last updated"," ",Ct.formatDistanceToNow(new Date(n.lastSaved),{addSuffix:!0})]})}),t.jsxs("div",{className:"flex items-center gap-2 pt-0.5",children:[t.jsxs("div",{className:"flex items-center gap-1 rounded-full bg-amber-500/10 px-1.5 py-0.5 text-xs text-amber-600",children:[t.jsx(E.Edit,{className:"h-3 w-3"}),t.jsx("span",{children:"Draft"})]}),s==="UNSAVED"?t.jsxs("div",{className:"flex items-center gap-1 rounded-full bg-red-500/10 px-1.5 py-0.5 text-xs text-red-600",children:[t.jsx(E.Save,{className:"h-3 w-3"}),t.jsx("span",{children:" Unsaved changes"})]}):null]})]})}):null}function ki(){const[e,s]=we.useState(!1),[n,a]=we.useState(null),[r,i]=we.useState(!1),[l,c]=we.useState(!1),{data:u}=Te(),{data:d,isFetching:h,error:g,refetch:b}=Ci(u==null?void 0:u.id),{mutate:y,isPending:p}=Ai(),{mutate:w,isPending:v}=Ti(),N=D.useQueryClient(),C=O=>{n&&w({revisionId:n.uid,discardCurrent:O},{onSuccess:()=>{i(!1),a(null),N.invalidateQueries({queryKey:[Y,L.GET_DRAFT_PAGE]})}})},B=O=>{a(O),i(!0)},S=O=>{a(O),c(!0)},P=()=>{n&&y(n.uid,{onSuccess:()=>{c(!1),a(null)}})};return f.useEffect(()=>{e&&b()},[e,b]),t.jsxs(t.Fragment,{children:[t.jsx(o.TooltipProvider,{children:t.jsxs(o.Tooltip,{children:[t.jsxs(o.Sheet,{open:e,onOpenChange:s,children:[t.jsx(o.SheetTrigger,{asChild:!0,children:t.jsx(o.TooltipTrigger,{asChild:!0,children:t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsxs(o.Button,{variant:"ghost",size:"icon",className:"h-8 w-8",children:[t.jsx(E.History,{className:"h-4 w-4"}),t.jsx("span",{className:"sr-only",children:"View revision history"})]}),t.jsx("div",{className:"w-px h-4 bg-gray-200 dark:bg-gray-700"})]})})}),t.jsxs(o.SheetContent,{className:"sm:max-w-md p-4",children:[t.jsxs(o.SheetHeader,{className:"pb-2",children:[t.jsxs(o.SheetTitle,{className:"flex items-center gap-2",children:[t.jsx(E.History,{className:"h-5 w-5"}),"Revision History"]}),(u==null?void 0:u.createdAt)&&t.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Page created on"," ",Ct.format(new Date(u.createdAt),"MMM d, yyyy 'at' h:mm a")]})]}),t.jsx(o.ScrollArea,{className:"h-[calc(100vh-6rem)] pr-2",children:h?t.jsx(Li,{}):g?t.jsx("div",{className:"p-4 text-center text-sm text-muted-foreground",children:"Failed to load revisions. Please try again."}):t.jsxs("div",{className:"mt-2 space-y-2",children:[t.jsx(Pi,{}),d==null?void 0:d.map(O=>t.jsx(Ii,{revision:O,isLatest:O.uid==="current",onRestore:()=>B(O),onDelete:()=>S(O)},O.uid))]})})]})]}),t.jsx(o.TooltipContent,{side:"bottom",children:t.jsx("p",{children:"Revision history"})})]})}),t.jsx(Di,{open:r,onOpenChange:i,revision:n,onRestore:C,isRestoring:v}),t.jsx(Bi,{open:l,onOpenChange:c,revision:n,onDelete:P,isDeleting:p})]})}function Li(){return t.jsx("div",{className:"space-y-2 mt-2",children:Array.from({length:5}).map((e,s)=>t.jsxs("div",{className:"flex items-start gap-3 rounded-md border p-2",children:[t.jsxs("div",{className:"flex-1 space-y-1",children:[t.jsx(o.Skeleton,{className:"h-4 w-3/4"}),t.jsx(o.Skeleton,{className:"h-3 w-1/2"}),t.jsx(o.Skeleton,{className:"h-5 w-20 mt-1"})]}),t.jsx(o.Skeleton,{className:"h-8 w-8 rounded-full"})]},s))})}function Ii({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:Ct.format(e.createdAt,"MMM d, h:mm a")})}),t.jsx("div",{className:"flex items-center gap-2 pt-0.5",children:e.type==="published"?t.jsxs("div",{className:"flex items-center gap-1 rounded-full bg-green-500/10 px-1.5 py-0.5 text-xs text-green-600",children:[t.jsx(E.ArrowUpRight,{className:"h-3 w-3"}),t.jsx("span",{children:"Published"})]}):t.jsxs("div",{className:"flex items-center gap-1 rounded-full bg-amber-500/10 px-1.5 py-0.5 text-xs text-amber-600",children:[t.jsx(E.Clock,{className:"h-3 w-3"}),t.jsx("span",{children:"Draft"})]})})]}),t.jsx(Ge,{permissions:[je.RESTORE_REVISION,je.DELETE_REVISION],children:e.uid!=="current"&&t.jsx(_i,{revision:e,onRestore:n,onDelete:a})})]})}function _i({revision:e,onRestore:s,onDelete:n}){return t.jsxs(o.DropdownMenu,{children:[t.jsx(o.DropdownMenuTrigger,{asChild:!0,children:t.jsxs(o.Button,{variant:"ghost",size:"icon",className:"h-7 w-7 -mr-1",children:[t.jsx(E.MoreHorizontal,{className:"h-4 w-4"}),t.jsx("span",{className:"sr-only",children:"More options"})]})}),t.jsxs(o.DropdownMenuContent,{align:"end",className:"text-xs",children:[t.jsx(Ge,{permission:je.RESTORE_REVISION,children:t.jsxs(o.DropdownMenuItem,{onClick:s,className:"cursor-pointer",children:[t.jsx(E.Undo2,{className:"mr-2 h-4 w-4"}),t.jsx("span",{children:"Restore this version"})]})}),t.jsx(Ge,{permission:je.DELETE_REVISION,children:e.uid!=="current"&&t.jsxs(t.Fragment,{children:[t.jsx(o.DropdownMenuSeparator,{}),t.jsxs(o.DropdownMenuItem,{onClick:n,className:"cursor-pointer text-destructive",children:[t.jsx(E.Trash,{className:"mr-2 h-4 w-4"}),t.jsx("span",{children:"Delete this version"})]})]})})]})]})}function Di({open:e,onOpenChange:s,revision:n,onRestore:a,isRestoring:r}){const{data:i}=et((n==null?void 0:n.currentEditor)||""),l=(i==null?void 0:i.name)||"Unknown";return n?t.jsx(o.Dialog,{open:e,onOpenChange:c=>{r||s(c)},children:t.jsxs(o.DialogContent,{className:"sm:max-w-md",children:[t.jsxs(o.DialogHeader,{children:[t.jsx(o.DialogTitle,{children:"Restore Revision"}),t.jsxs(o.DialogDescription,{children:["You are about to restore to revision ",n.uid.substring(0,8)," ","from ",Ct.format(n.createdAt,"MMM d, yyyy 'at' h:mm a")," by"," ",l]})]}),t.jsx("div",{className:"py-2",children:t.jsx("p",{className:"text-sm text-muted-foreground",children:"How would you like to handle your current edits?"})}),t.jsxs(o.DialogFooter,{className:"flex flex-col sm:flex-row gap-2",children:[t.jsx(o.Button,{variant:"outline",className:"sm:flex-1",onClick:()=>a(!1),disabled:r,children:r?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mr-2 h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent"}),"Saving as draft..."]}):t.jsxs(t.Fragment,{children:[t.jsx(E.CloudOff,{className:"mr-2 h-4 w-4"}),"Save as draft"]})}),t.jsx(o.Button,{variant:"default",className:"sm:flex-1",onClick:()=>a(!0),disabled:r,children:r?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mr-2 h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent"}),"Discarding current..."]}):t.jsxs(t.Fragment,{children:[t.jsx(E.Undo2,{className:"mr-2 h-4 w-4"}),"Discard current"]})})]})]})}):null}function Bi({open:e,onOpenChange:s,revision:n,onDelete:a,isDeleting:r}){const{data:i}=et((n==null?void 0:n.currentEditor)||""),l=(i==null?void 0:i.name)||"Unknown";return n?t.jsx(o.Dialog,{open:e,onOpenChange:c=>{r||s(c)},children:t.jsxs(o.DialogContent,{className:"sm:max-w-md",children:[t.jsxs(o.DialogHeader,{children:[t.jsx(o.DialogTitle,{children:"Delete Revision"}),t.jsxs(o.DialogDescription,{children:["You are about to delete revision ",n.uid.substring(0,8)," from"," ",Ct.format(n.createdAt,"MMM d, yyyy 'at' h:mm a")," by"," ",l]})]}),t.jsx("div",{className:"py-2",children:t.jsx("p",{className:"text-sm text-muted-foreground",children:"This action cannot be undone. Are you sure you want to proceed?"})}),t.jsxs(o.DialogFooter,{className:"flex flex-col sm:flex-row gap-2",children:[t.jsx(o.Button,{variant:"outline",className:"sm:flex-1",onClick:()=>s(!1),disabled:r,children:"Cancel"}),t.jsx(o.Button,{variant:"destructive",className:"sm:flex-1",onClick:a,disabled:r,children:r?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mr-2 h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent"}),"Deleting..."]}):t.jsxs(t.Fragment,{children:[t.jsx(E.Trash,{className:"mr-2 h-4 w-4"}),"Delete Revision"]})})]})]})}):null}const Mi=()=>{const e=re(),s=J();return D.useQuery({queryKey:[Y,L.GET_CHANGES],queryFn:async()=>s(e,{action:L.GET_CHANGES})})},Oi=({currentEditor:e})=>{const{data:s}=et(e);return s==null?void 0:s.name};function Gi({showModal:e=!1,onClose:s=()=>console.log("Cancelled")}){const[n,a]=f.useState([]),{data:r,isFetching:i}=Mi(),{data:l}=Pe(),c=f.useCallback(S=>{var P;return(P=m.find(l,{key:S}))==null?void 0:P.hasSlug},[l]),u=f.useMemo(()=>m.filter(l,S=>!c(S.key)).map(S=>S.key),[c,l]),d=f.useMemo(()=>m.filter(r,S=>!u.includes(S.pageType)),[r,u]),h=f.useMemo(()=>m.filter(r,S=>u.includes(S.pageType)),[r,u]),g=f.useMemo(()=>m.find(r,{pageType:"theme",id:"THEME"}),[r]),{mutate:b,isPending:y}=Ys();f.useEffect(()=>{const S=m.map(m.filter(r,{online:!0}),"id");g&&S.push(g==null?void 0:g.id),a(S)},[r,g]);const p=n.length===(r==null?void 0:r.length),w=S=>{a(P=>m.includes(P,S)?m.filter(P,O=>O!==S):m.concat(P,S))},v=()=>{a(p?[]:m.map(r,"id"))},N=()=>{b({ids:m.uniq(n)},{onSuccess:()=>{s(),Dt("CENTER_CENTER")}})},C=S=>{if(S==="theme")return"Theme";const P=m.find(l,{key:S});return P?P==null?void 0:P.name:S},B=f.useMemo(()=>{const S=[{label:"Updated",top:"pt-2"},...m.orderBy(m.filter(d,{online:!0}),"pageType"),...m.orderBy(m.filter(h,{online:!0}),"pageType")].filter(z=>z.pageType!=="theme"),P=[{label:"Offline",top:"pt-6"},...m.orderBy(m.filter(d,{online:!1}),"pageType"),...m.orderBy(m.filter(h,{online:!1}),"pageType")],O=g?[{label:"Theme",top:"pt-6"},g]:[];return[...S,...O,...P]},[d,h,g]);return t.jsx(o.Dialog,{open:e,onOpenChange:y?()=>{}:s,children:t.jsxs(o.DialogContent,{className:"max-w-4xl max-h-[80%] flex flex-col",children:[t.jsxs(o.DialogHeader,{children:[t.jsx(o.DialogTitle,{children:"Publish changes"}),t.jsx(o.DialogDescription,{className:"text-xs",children:"Select the pages you want to publish. Click publish when you're done."})]}),t.jsx("div",{className:"relative h-full max-h-full -mx-4 overflow-y-auto no-scrollbar",children:i?t.jsxs("div",{className:"px-1 space-y-2",children:[t.jsx("div",{className:"w-full h-6 mt-2 bg-gray-200 rounded animate-pulse"}),t.jsx("div",{className:"w-full h-6 bg-gray-200 rounded animate-pulse"}),t.jsx("div",{className:"w-full h-6 bg-gray-200 rounded animate-pulse"}),t.jsx("div",{className:"w-full h-6 bg-gray-200 rounded animate-pulse"})]}):t.jsxs("table",{className:"w-full text-xs text-left text-gray-500 rtl:text-right dark:text-gray-400",children:[t.jsx("thead",{className:"text-gray-700 border-b bg-gray-50 dark:bg-gray-700 dark:text-gray-400",children:t.jsxs("tr",{children:[t.jsxs("th",{scope:"col",className:"px-6 py-3 flex items-center gap-x-2 w-[1 50px]",children:[t.jsx("input",{checked:p,onClick:S=>{S.stopPropagation(),v()},type:"checkbox",className:"mt-1 rounded cursor-pointer focus:outline-none focus:ring-0"}),"Name"]}),t.jsx("th",{scope:"col",className:"px-2 py-3 w-[100px]",children:"Language"}),t.jsx("th",{scope:"col",className:"px-2 py-3 w-[100px]",children:"Type"}),t.jsx("th",{scope:"col",className:"px-4 py-3 w-[150px] text-right",children:"Status"})]})}),t.jsx("tbody",{children:m.map(B,S=>S.label?t.jsx("tr",{children:t.jsxs("td",{colSpan:4,className:`px-6 py-2 text-xs font-medium text-gray-800 relative ${S.top}`,children:[t.jsx("div",{className:"absolute inset-0 flex items-center left-6",children:t.jsx("div",{className:"w-full order-gray-300"})}),t.jsx("div",{className:"relative flex justify-start",children:t.jsx("span",{className:"pr-2 bg-gray-50",children:S.label})})]})},"separator"):t.jsxs("tr",{className:"border-b group hover:bg-gray-50 last:border-b-0",children:[t.jsxs("td",{scope:"row",className:"flex items-center px-6 py-2 text-gray-900 whitespace-nowrap dark:text-white gap-x-1",children:[t.jsx("input",{checked:m.includes(n,S==null?void 0:S.id),onClick:P=>{P.stopPropagation(),w(S==null?void 0:S.id)},type:"checkbox",className:"rounded cursor-pointer focus:outline-none focus:ring-0"})," ",c(S.pageType)?t.jsx(E.File,{className:"w-4 h-4"}):t.jsx(E.GlobeIcon,{className:"w-4 h-4"}),S.name,S.slug&&t.jsxs("span",{className:"text-xs text-gray-500",children:["(",S.slug,")"]}),S.currentEditor&&t.jsx("div",{className:"flex items-center gap-x-1",children:t.jsxs("span",{className:"flex text-xs font-bold text-gray-500",children:[" ","-"," ",t.jsx(Oi,{currentEditor:S.currentEditor})," ","is editing"]})})]}),t.jsx("td",{className:"px-2",children:S.lang}),t.jsx("td",{className:"px-2",children:C(S==null?void 0:S.pageType)}),t.jsx("td",{className:"px-4 text-right",children:m.first(S.changes)||""})]},S==null?void 0:S.id))})]})}),t.jsxs(o.DialogFooter,{className:"mt-10",children:[t.jsx(o.Button,{disabled:y,variant:"outline",onClick:s,children:"Cancel"}),t.jsx(o.Button,{disabled:y||i||m.isEmpty(r),onClick:N,children:y?"Publishing...":"Publish"})]})]})})}const Ri=()=>{const e=J(),s=re();return D.useQuery({queryKey:[L.GET_WEBSITE_DATA],staleTime:1e3*60*5,queryFn:async()=>e(s,{action:L.GET_WEBSITE_DATA,data:{draft:!0}})})};function Ui({onClose:e}){const{data:s,isFetching:n}=Ri(),{mutateAsync:a,isPending:r}=hr(),i=He("settingComponent",null),l=m.debounce(async c=>(await a({data:c}),!0),300);return i?t.jsx(o.Dialog,{open:!0,onOpenChange:e,children:t.jsxs(o.DialogContent,{className:"w-full",children:[t.jsx(o.DialogHeader,{children:t.jsx(o.DialogTitle,{children:"Website Settings"})}),n?t.jsxs("div",{className:"w-full space-y-3 py-4",children:[t.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"}),t.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"}),t.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"}),t.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"}),t.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"}),t.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"})]}):t.jsx("div",{children:f.createElement(i,{data:s||{},onSave:r?()=>{}:l,cancel:r?()=>{}:e})})]})}):null}function na({children:e,content:s}){return t.jsx(o.TooltipProvider,{children:t.jsxs(o.Tooltip,{children:[t.jsx(o.TooltipTrigger,{asChild:!0,children:e}),t.jsx(o.TooltipContent,{side:"bottom",sideOffset:10,children:t.jsx("p",{children:s})})]})})}const Fi=()=>{const{selectedLang:e,fallbackLang:s}=q.useLanguages(),n=He("getPreviewUrl",async g=>g),[a,r]=f.useState(""),{data:i}=Te(),{data:l}=Ke(),{data:c}=Pe(),u=f.useMemo(()=>{var g;return(g=l==null?void 0:l.find(b=>(b==null?void 0:b.lang)===e))==null?void 0:g.slug},[e,l]),d=f.useCallback(g=>{var b;return(b=m.find(c,{key:g}))==null?void 0:b.hasSlug},[c]),h=e===s?"":e;return f.useEffect(()=>{(async()=>{if(typeof n=="function"){const g=!d(i==null?void 0:i.pageType),b=await n(g?`${h!==""?h+"/":""}${i==null?void 0:i.id}`:u||"");r(b)}else r("")})()},[n,u,i==null?void 0:i.pageType,d,i==null?void 0:i.id,h]),t.jsx(t.Fragment,{children:t.jsx("a",{href:a,target:"_blank",rel:"noopener noreferrer",children:t.jsxs(o.Button,{variant:"ghost",size:"sm",className:"gap-2",children:[t.jsx(E.Eye,{className:"h-4 w-4"})," ",ae.PREVIEW]})})})},qi=()=>{const[e,s]=q.useRightPanel();return t.jsxs(t.Fragment,{children:[t.jsx(na,{content:ae.THEME,children:t.jsx(o.Button,{variant:e==="theme"?"outline":"ghost",size:"icon",className:"gap-2",onClick:()=>s(e==="theme"?"block":"theme"),children:t.jsx(E.Palette,{className:"h-4 w-4"})})}),t.jsx("div",{className:"h-4 w-px bg-gray-200 dark:bg-gray-700"})]})},zi=()=>{const[e,s]=f.useState(!1),{isLocked:n}=es(),{savePage:a,saveState:r}=q.useSavePage();f.useEffect(()=>{const h=g=>{r==="UNSAVED"&&(g.preventDefault(),g.returnValue=!1)};return r==="UNSAVED"&&window.addEventListener("beforeunload",h),()=>{window.removeEventListener("beforeunload",h)}},[r]);const i=f.useCallback(async()=>{s(!0),await a(!1)},[a]);f.useEffect(()=>{r==="SAVED"&&s(!1)},[r]);const l=f.useMemo(()=>{if(r==="SAVED"||r==="UNSAVED")return r;if(r==="SAVING")return e?r:"SAVED"},[e,r]),{buttonIcon:c,buttonClass:u,tooltipContent:d}=f.useMemo(()=>{switch(l){case"UNSAVED":return{tooltipContent:ae.SAVEDRAFT,buttonIcon:t.jsx(E.Save,{className:"h-4 w-4"}),buttonClass:"flex items-center gap-x-1 leading-tight"};case"SAVING":return{tooltipContent:ae.SAVING,buttonIcon:t.jsx(E.Loader,{className:"h-4 w-4 animate-spin"}),buttonClass:"flex items-center gap-x-1 leading-tight"};case"SAVED":return{tooltipContent:ae.SAVED,buttonIcon:t.jsx(E.CheckCircle,{className:"h-4 w-4"}),buttonClass:"text-green-500 flex items-center gap-x-1 leading-tight"}}},[l]);return n?null:t.jsxs(o.Button,{size:"sm",variant:"ghost",onClick:i,className:u,children:[c," ",d]})},$i=()=>{const{selectedLang:e}=q.useLanguages(),{data:s}=At(),{data:n}=Ke(),[a,r]=f.useState(!1),[i,l]=f.useState(!1),[c,u]=f.useState(null),{data:d}=Te(),{mutate:h,isPending:g}=Ys(),{buttonText:b,buttonClassName:y,isPublished:p}=f.useMemo(()=>{const N=d&&(d==null?void 0:d.online);return{buttonClassName:N?"hover:bg-green-600 bg-green-500":"",isPublished:N,buttonText:N?ae.PUBLISHED:ae.PUBLISH}},[d]),w=async()=>{const N=[s==null?void 0:s.id,s==null?void 0:s.primaryPage];h({ids:m.compact(N)},{onSuccess:()=>Dt("TOP_RIGHT")})},v=f.useMemo(()=>m.map(n??[],"id"),[n]);return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex",children:[t.jsxs(o.Button,{size:"sm",onClick:w,disabled:g||!(d!=null&&d.id),className:`relative flex items-center gap-1 overflow-hidden rounded-r-none text-white transition-all duration-300 ease-in-out ${y}`,onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),children:[t.jsx("span",{className:`flex items-center transition-transform duration-300 ease-in-out ${i?"-translate-y-10":""}`,children:p?t.jsx(E.Send,{className:"h-4 w-4"}):t.jsx(E.Rocket,{className:"h-4 w-4"})}),t.jsx("span",{className:`absolute inset-0 left-3 flex items-center transition-transform duration-300 ease-in-out ${i?"":"translate-y-10"}`,children:p?t.jsx(E.Rocket,{className:"h-4 w-4"}):t.jsx(E.Send,{className:"h-4 w-4"})}),t.jsx("span",{children:b}),e?`(${m.upperCase(e)})`:""]}),t.jsxs(o.DropdownMenu,{children:[t.jsx(o.DropdownMenuTrigger,{asChild:!0,children:t.jsx(o.Button,{size:"sm",disabled:g||!(d!=null&&d.id),className:`rounded-l-none border-l border-white/50 px-2 text-white ${y}`,children:t.jsx(E.ChevronDown,{className:"h-4 w-4"})})}),t.jsxs(o.DropdownMenuContent,{align:"end",className:"w-52",children:[t.jsxs(o.DropdownMenuItem,{disabled:g,className:"cursor-pointer text-xs",onClick:()=>h({ids:v},{onSuccess:()=>Dt("TOP_RIGHT")}),children:[ae.PUBLISH," with translation pages"]}),!p&&t.jsxs(o.DropdownMenuItem,{disabled:g,className:"cursor-pointer text-xs",onClick:()=>h({ids:[d==null?void 0:d.id]},{onSuccess:()=>Dt("TOP_RIGHT")}),children:[ae.PUBLISH," page"]}),t.jsxs(o.DropdownMenuItem,{onClick:()=>r(!0),className:"cursor-pointer text-xs",children:[ae.OPEN," publish menu"]}),p&&t.jsxs(o.DropdownMenuItem,{onClick:()=>u(s),className:"cursor-pointer text-xs",children:[ae.UNPUBLISH," page ",e?`(${m.upperCase(e)})`:""]})]})]})]}),t.jsx(Gi,{showModal:a,onClose:()=>r(!1)}),c&&t.jsx(bs,{page:c,onClose:()=>u(null)})]})},Vi=()=>{const e=He("settingComponent",null),[s,n]=f.useState(!1);return e?t.jsxs(t.Fragment,{children:[t.jsx(na,{content:ae.WEBSITEDATA,children:t.jsx(o.Button,{variant:"ghost",size:"icon",className:"gap-2",onClick:()=>n(!0),children:t.jsx(E.Settings,{className:"h-4 w-4"})})}),s&&t.jsx(Ui,{onClose:()=>n(!1)}),t.jsx("div",{className:"h-4 w-px bg-gray-200 dark:bg-gray-700"})]}):null};function Hi(){const{isLocked:e}=es(),[s]=_e(),n=s.get("lang"),a=Rn(n);return e||!a?null:t.jsxs("div",{className:"flex items-center justify-end gap-1",children:[t.jsx(ki,{}),t.jsx(Ge,{permission:je.EDIT_THEME,children:t.jsx(qi,{})}),t.jsx(Ge,{permission:je.EDIT_SETTINGS,children:t.jsx(Vi,{})}),t.jsx(Fi,{}),t.jsx(Ge,{permission:je.SAVE_PAGE,children:t.jsx(zi,{})}),t.jsx(Ge,{permission:je.PUBLISH_PAGE,children:t.jsx($i,{})})]})}function Ki(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 Qi=()=>{const{data:e}=At(),s=zn(),n=e==null?void 0:e.slug,a=!n;let r=window.location.origin+(n?n.endsWith("/")?n.slice(0,-1):n:"");s&&(r+=s);const l=(a?`Partial: ${e==null?void 0:e.name} `:Ki(s?`${n}${s}`:n)).replace(window.location.host,"");return t.jsxs("div",{className:"flex h-8 w-auto max-w-[600px] items-center rounded-md border border-gray-200 bg-white shadow-sm dark:border-gray-700 dark:bg-gray-800"+(a?" pr-2":""),children:[t.jsx(sn,{}),t.jsx("div",{className:"flex w-full items-center overflow-hidden",children:t.jsx("div",{className:`w-full overflow-hidden overflow-ellipsis whitespace-nowrap pl-1 font-mono text-xs ${a?"italic text-gray-400":"text-gray-500"}`,children:l===""?"/(Homepage)":l})}),!a&&t.jsx("a",{href:r,target:"_blank",rel:"noopener noreferrer",children:t.jsx("div",{className:"ml-2 mr-px flex-shrink-0 rounded-sm p-1.5 text-gray-500 hover:bg-gray-100 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-300",children:t.jsx(E.ExternalLink,{className:"h-4 w-4",strokeWidth:1})})})]})},Wi=()=>t.jsxs("div",{className:"flex h-full w-full items-center justify-between px-2",children:[t.jsx(Ni,{}),t.jsx(Qi,{}),t.jsx(Hi,{})]}),Yi=()=>{const e=re(),{aiContext:s}=Vs(),n=J();return f.useCallback(async(a,r,i,l)=>n(e,{action:L.ASK_AI,data:{type:a,prompt:r,blocks:i,context:s,lang:l}}),[e,s,n])},Ji=(e,s)=>s.map(n=>{if(m.has(e,n._type)){const a=In.getDefaultBlockProps(n._type);return{...a,...m.pick(n,[...m.keys(a),"_type","_id","_name","_parent","_bindings"]),...m.pickBy(n,(r,i)=>m.endsWith(i,"_attrs")),...n}}return n}),Xi=e=>{const s=In.useRegisteredChaiBlocks();return f.useMemo(()=>{if(!e||m.isEmpty(e))return{blocks:[]};const n=m.filter(e,a=>!m.includes(a==null?void 0:a._type,"@chai/"));return{blocks:Ji(s,n)}},[e,s])},gn={async getUILibraryBlock(e,s,n){const a=await s(n,{action:"GET_LIBRARY_ITEM",data:{id:e.id}}),r=m.get(a,"html",""),i=m.get(a,"blocks",[]);return m.isArray(i)?i:q.getBlocksFromHTML(r)},async getUILibraryBlocks(e,s,n){try{return(await s(n,{action:"GET_LIBRARY_ITEMS",data:{id:e.id}})).map(r=>({...r}))}catch(a){return console.error(a),[]}}},Zi=()=>{const e=re(),s=J();return D.useQuery({queryKey:[Y,"uiLibraries"],initialData:[],queryFn:async()=>{const a=(await s(e,{action:"GET_LIBRARIES"})).map(r=>({...r}));return a.forEach(r=>{q.registerChaiLibrary(r.id,{name:r.name,description:r.description,getBlocksList:i=>gn.getUILibraryBlocks(i,s,e),getBlock:({block:i})=>gn.getUILibraryBlock(i,s,e)})}),a}})},aa=()=>{const e=js(),s=J(),{user:n}=Ue(),a=n==null?void 0:n.id;return D.useQuery({queryKey:[Y,"permissions",a],queryFn:()=>s(e,{action:L.GET_ROLE_AND_PERMISSIONS,data:{userId:a}}),enabled:!!a})},el=()=>{const e=re(),s=J(),{setCurrentEditor:n}=es(),[,a]=vs();return{onSave:async({page:i,blocks:l})=>{try{const c=await s(e,{action:"UPDATE_PAGE",data:{id:i,blocks:l}});return c.code==="PAGE_LOCKED"?(n(c.editor),!0):(a(u=>({...u,lastSaved:new Date().toISOString()})),c)}catch(c){return console.error(c),new Error("Failed to save blocks")}}}},tl=()=>{const{data:e}=Zt(),s=re(),n=J();return{getPartialBlocks:f.useCallback(async()=>{const a={};for(const r of e??[])m.isEmpty(r==null?void 0:r.slug)&&(a[r.id]={type:r.pageType,name:m.startCase(r.name??r.slug),description:""});return a},[e]),getPartialBlockBlocks:f.useCallback(async a=>{if(!a)return[];try{const r=await n(s,{action:"GET_DRAFT_PAGE",data:{id:a,draft:!0,editor:!1}});return m.filter(r.blocks,i=>m.has(i,"_id"))}catch(r){return console.error(r),[]}},[n,s])}},xn=ls.z.object({email:ls.z.string().email({message:"Please enter a valid email address"}),password:ls.z.string().min(6,{message:"Password must be at least 6 characters"})}),sl=()=>{const{setUser:e,logout:s}=Ue(),n=js(),[a,r]=f.useState(""),[i,l]=f.useState(""),[c,u]=f.useState({}),[d,h]=f.useState(!1),[g,b]=f.useState(""),y=D.useMutation({mutationFn:async v=>{b("");const N=await $s(n,{action:"LOGIN",data:v});if(!N.ok){const B=await N.json();throw new Error(B.error||"Login failed")}const C=await N.json();if(m.has(C,"id")&&m.has(C,"email")&&m.has(C,"accessToken")&&m.has(C,"refreshToken"))e(C);else throw s(),new Error("Something went wrong. Please try again.");return C},onSuccess:()=>{u({}),b("")},onError:v=>{u({email:" ",password:" "}),b(v.message||"Something went wrong")}}),p=async v=>{v.preventDefault(),u({});const N={email:a,password:i};try{const C=xn.parse(N);y.mutate(C)}catch(C){if(C instanceof ls.z.ZodError){const B=C.errors.reduce((S,P)=>{const O=P.path[0];return S[O]=P.message,S},{});u(B)}}},w=xn.safeParse({email:a,password:i}).success;return t.jsx("div",{className:"flex justify-center items-center min-h-screen bg-slate-50",children:t.jsxs(o.Card,{className:"w-full max-w-md",children:[t.jsxs(o.CardHeader,{children:[t.jsx(o.CardTitle,{className:"text-2xl",children:"Sign in"}),t.jsx(o.CardDescription,{children:"Enter your credentials to sign in to visual builder"})]}),t.jsx(o.CardContent,{children:t.jsxs("form",{onSubmit:p,className:"space-y-4",children:[t.jsxs("div",{className:"space-y-1",children:[t.jsx(o.Label,{htmlFor:"email",children:"Email"}),t.jsx(o.Input,{id:"email",placeholder:"you@example.com",type:"email",value:a,onChange:v=>r(v.target.value),className:c.email?"border-destructive":""}),c.email&&t.jsx("p",{className:"text-sm text-destructive",children:c.email})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsx(o.Label,{htmlFor:"password",children:"Password"}),t.jsxs("div",{className:"relative",children:[t.jsx(o.Input,{id:"password",placeholder:"Enter your password",type:d?"text":"password",value:i,onChange:v=>l(v.target.value),className:c.password?"border-destructive":""}),t.jsx("button",{type:"button",className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground",onClick:()=>h(!d),children:d?t.jsx(E.EyeOff,{className:"h-4 w-4"}):t.jsx(E.Eye,{className:"h-4 w-4"})})]}),c.password&&t.jsx("p",{className:"text-sm text-destructive",children:c.password})]}),t.jsx("div",{children:t.jsx("p",{className:"text-sm text-destructive",children:g})}),t.jsx(o.Button,{type:"submit",className:"w-full",disabled:!w||y.isPending,children:y.isPending?t.jsxs(t.Fragment,{children:[t.jsx(E.Loader2,{className:"mr-2 h-4 w-4 animate-spin"}),"Logging in..."]}):"Login"})]})}),t.jsxs(o.CardFooter,{className:"flex flex-col justify-center",children:[t.jsxs("p",{className:"text-sm text-muted-foreground",children:["Forgot your password?"," ",t.jsx("a",{target:"_blank",href:"https://chaibuilder.com/forgot-password",className:"text-primary hover:underline",children:"Reset password"})]}),t.jsx("br",{}),t.jsx("br",{}),t.jsxs("div",{className:"flex items-center border-t pt-2 px-10 gap-2",children:["Powered by"," ",t.jsxs("a",{target:"_blank",href:"https://chaibuilder.com",className:"text-primary hover:underline flex items-center gap-1",children:[t.jsx("img",{src:"https://ucarecdn.com/a82e256c-1cf2-4755-b65c-5d85e7652daa/-/preview/400x400",alt:"Chai Builder",className:"w-4 h-4 rounded uppercase font-bold"}),"Chai Builder"]})]})]})]})})};let Ds=sl;const nl=()=>f.useMemo(()=>Ds,[Ds]),al=e=>{Ds=e},rl=()=>{const e=nl();return t.jsx(f.Suspense,{fallback:t.jsx("div",{children:"Loading..."}),children:t.jsx(e,{})})},il=({isActive:e,show:s})=>{const{data:n}=Ze();return!m.has(n,"languages")||!m.get(n,"languages",[]).length?null:t.jsx(o.Button,{size:"sm",onClick:s,variant:e?"default":"ghost",children:t.jsx(E.LanguagesIcon,{className:"w-4 h-4"})})},ra="lang",ll={id:ra,label:"Languages",position:"top",panel:Zr,button:il,view:"modal",width:400};function We({data:e,onSelect:s,dataType:n="value",disabled:a=!1}){const[r,i]=we.useState(!1),[l,c]=we.useState([]),[u,d]=we.useState(e);we.useEffect(()=>{r||c([]),d(e)},[e,r]);const h=p=>Array.isArray(p)?"array":typeof p=="object"&&p!==null?"object":"value",g=we.useCallback(p=>{const w=v=>n==="value"?v==="value"||v==="object":n==="array"?v==="array":v===n;p.type==="object"?(c(v=>[...v,p.key]),d(p.value)):w(p.type)&&(s([...l,p.key].join(".")),i(!1))},[l,s,n]),b=we.useCallback(()=>{if(l.length>0){const p=l.slice(0,-1);c(p),d(p.reduce((w,v)=>w[v],e))}},[l,e]),y=we.useMemo(()=>Object.entries(u).map(([p,w])=>({key:p,value:w,type:h(w)})).filter(p=>n==="value"?p.type==="value"||p.type==="object":n==="array"?p.type==="array"||p.type==="object":n==="object"?p.type==="object":!0),[u,n]);return t.jsxs(o.Popover,{open:r,onOpenChange:i,children:[t.jsxs(o.Tooltip,{children:[t.jsx(o.TooltipTrigger,{asChild:!0,children:t.jsx(o.PopoverTrigger,{asChild:!0,children:t.jsx(o.Button,{size:"sm",variant:"outline",className:"h-6 w-6 px-1 py-0 text-[9px] text-muted-foreground",role:"combobox","aria-expanded":r,disabled:a,children:t.jsx(E.DatabaseIcon,{className:"h-3 w-3"})})})}),t.jsx(o.TooltipContent,{children:"Add field"})]}),t.jsx(o.PopoverContent,{className:"w-[200px] z-[9999] p-0",children:t.jsxs(o.Command,{children:[t.jsx(o.CommandInput,{className:"border-none",placeholder:"Search..."}),t.jsxs(o.CommandList,{onWheel:p=>{try{p.preventDefault();const w=p.currentTarget;w.scrollTop+=p.deltaY}catch{p.preventDefault()}},children:[t.jsx(o.CommandEmpty,{children:"No option found."}),t.jsxs(o.CommandGroup,{children:[l.length>0&&t.jsxs(o.CommandItem,{onSelect:b,className:"flex items-center text-sm",children:[t.jsx(E.ChevronLeft,{className:"w-4 h-4 mr-2"}),"Back"]}),y.map(p=>t.jsxs(o.CommandItem,{onSelect:()=>g(p),className:"flex items-center justify-between",children:[t.jsx("span",{children:p.key}),t.jsxs("div",{className:"flex items-center gap-2",children:[n==="object"&&p.type==="object"&&t.jsx(o.Button,{size:"sm",variant:"ghost",className:"h-6 px-2 hover:bg-primary hover:text-primary-foreground",onClick:w=>{w.stopPropagation(),s([...l,p.key].join(".")),i(!1)},children:"Select"}),(p.type==="object"||p.type==="array")&&t.jsx("div",{className:"p-1 rounded hover:bg-muted cursor-pointer",children:t.jsx(E.ChevronRight,{className:"w-4 h-4 opacity-50"})})]})]},p.key))]})]})]})})]})}const ol=()=>{const{selectedLang:e}=q.useLanguages(),{data:s,isFetching:n}=Ke();return{data:f.useMemo(()=>m.find(s,{lang:e||""})||{},[s,e]),isFetching:n}},cl=()=>{var l;const s=(l=document.getElementById("canvas-iframe").contentDocument)==null?void 0:l.body.innerHTML;if(!s)return null;const a=new DOMParser().parseFromString(s,"text/html");a.querySelectorAll("style, script, link, svg").forEach(c=>c.remove()),a.querySelectorAll("*").forEach(c=>{Array.from(c.attributes).forEach(u=>c.removeAttribute(u.name))});const r=a.querySelectorAll("h1, h2, h3, h4, h5, h6, p");return Array.from(r).map(c=>`<${c.tagName.toLowerCase()}>${c.innerHTML}</${c.tagName.toLowerCase()}>`).join(" ").replace(/<p>Partial block. Double click to edit.<\/p>/,"")},kt=({keyword:e,onComplete:s,field:n})=>{const a=J(),r=re(),{selectedLang:i,fallbackLang:l}=q.useLanguages(),c=q.useBuilderProp("aiContext",""),{mutate:u,isPending:d}=D.useMutation({mutationFn:async()=>{const h=cl();return await a(r,{action:L.GENERATE_SEO_FIELD,data:{pageContext:c,dynamic:!1,field:n,lang:i||l,pageContent:h,keyword:e}})},onSuccess:h=>{s({fieldValue:h.field})},onError:h=>{s({fieldValue:null,error:h.message})}});return t.jsx(o.Button,{disabled:d,type:"button",className:"h-5 w-5",variant:"ghost",size:"sm",onClick:()=>u(),children:d?t.jsx(E.Loader2,{className:"h-3 w-3 animate-spin text-yellow-500"}):t.jsx(E.Sparkle,{className:"text-yellow-500"})})},ul=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),pn=e=>{if(!e.trim())return{isValid:!1,parsed:null,placeholders:[],error:{message:"JSON is empty"}};try{return{isValid:!0,parsed:JSON.parse(e),error:null,placeholders:[]}}catch{}const s=/{{([^{}]+)}}/g,n=[];let a=e,r;for(;(r=s.exec(e))!==null;){const i=r[0],l=r.index,c=`"__placeholder_${n.length}__"`;n.push({original:i,replaced:c,position:l}),a=a.replace(i,c)}try{return{isValid:!0,parsed:JSON.parse(a),error:null,placeholders:n}}catch(i){const l=i,c=l.message.match(/position (\d+)/),u=c?parseInt(c[1]):void 0;let d,h;if(u!==void 0){const g=a.substring(0,u).split(`
|
|
3
|
+
`);d=g.length,h=g[g.length-1].length+1}return{isValid:!1,parsed:null,placeholders:n,error:{message:l.message,line:d,column:h,position:u}}}},dl=(e,s)=>{let a=JSON.stringify(e,null,2);return s.forEach(({original:r},i)=>{const l=`"__placeholder_${i}__"`,c=new RegExp(ul(l),"g");a=a.replace(c,r)}),a},ml=(e,s)=>{if(!e)return"";let n=JSON.stringify(e,null,2);const a=/{{([^{}]+)}}/g;let r;for(;(r=a.exec(n))!==null;){const i=r[1],l=m.get(s,i,null);n=n.replace(r[0],l)}return n},ia=({value:e,onChange:s,disabled:n=!1,readOnly:a=!1,placeholder:r="Enter JSON",rows:i=6,id:l="json-input",pageData:c={},handleFieldInsert:u})=>{const[d,h]=f.useState("edit"),[g,b]=f.useState(null),[y,p]=f.useState(""),w=f.useRef(null),v=S=>{if(a)return;const P=S.target.value;s(P)},N=S=>{if(S.key==="Tab"){S.preventDefault();const P=S.currentTarget,O=P.selectionStart,z=P.selectionEnd;if(O!==z){const se=e.substring(O,z).split(`
|
|
4
4
|
`);if(S.shiftKey){const K=se.map(Q=>Q.startsWith(" ")?Q.substring(2):Q).join(`
|
|
5
5
|
`),te=e.substring(0,O)+K+e.substring(z);s(te),setTimeout(()=>{P.selectionStart=O,P.selectionEnd=O+K.length},0)}else{const K=se.map(Q=>` ${Q}`).join(`
|
|
6
|
-
`),te=e.substring(0,O)+K+e.substring(z);s(te),setTimeout(()=>{P.selectionStart=O,P.selectionEnd=O+K.length},0)}}else{const $=e.substring(0,O)+" "+e.substring(z);s($),setTimeout(()=>{P.selectionStart=P.selectionEnd=O+2},0)}}};f.useEffect(()=>{const S=pn(e);if(S.isValid)if(b(null),S.parsed){const P=dl(S.parsed,c);p(P)}else p("");else b(S.error),p("")},[e,c]);const C=()=>{const S=pn(e);if(S.isValid&&S.parsed){const P=ul(S.parsed,S.placeholders);s(P)}},B=()=>{g!=null&&g.position&&w.current&&(w.current.focus(),w.current.setSelectionRange(g.position,g.position+1))};return t.jsx("div",{className:"space-y-2",children:t.jsxs(o.Tabs,{value:d,onValueChange:h,className:"w-full",children:[t.jsxs("div",{className:"mb-2 flex items-center justify-between",children:[t.jsxs(o.TabsList,{className:"grid w-[200px] grid-cols-2",children:[t.jsxs(o.TabsTrigger,{value:"edit",className:"flex items-center gap-1",children:[t.jsx(E.Code,{className:"h-4 w-4"}),t.jsx("span",{children:"Edit"})]}),t.jsxs(o.TabsTrigger,{value:"preview",className:"flex items-center gap-1",disabled:!e.trim()||g!==null,children:[t.jsx(E.Eye,{className:"h-4 w-4"}),t.jsx("span",{children:"Preview"})]})]}),d==="edit"&&!a&&t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(We,{dataType:"value",data:c??{},onSelect:S=>u&&u(S,"jsonLD")}),t.jsx(o.Button,{type:"button",variant:"outline",size:"sm",onClick:C,disabled:!e.trim()||n||g!==null,children:"Format"})]})]}),t.jsxs(o.TabsContent,{value:"edit",className:"mt-0",children:[t.jsx(o.Textarea,{ref:w,id:l,name:l,className:`rounded-md border border-input text-xs ${g?"border-red-500":""}`,onChange:v,onKeyDown:N,value:e,placeholder:r,rows:i,disabled:n,readOnly:a}),g&&t.jsxs(o.Alert,{variant:"destructive",className:"mt-2",children:[t.jsx(E.AlertTriangle,{className:"h-4 w-4"}),t.jsxs(o.AlertDescription,{className:"flex flex-col",children:[t.jsx("span",{className:"font-medium",children:"Invalid JSON"}),t.jsx("span",{className:"text-sm",children:g.message}),g.line&&g.column&&t.jsxs("span",{className:"text-sm",children:["Error at line ",g.line,", column ",g.column]}),t.jsx(o.Button,{type:"button",variant:"link",size:"sm",className:"mt-1 h-auto self-start p-0 text-sm",onClick:B,children:"Show position"})]})]})]}),t.jsxs(o.TabsContent,{value:"preview",className:"mt-0",children:[t.jsx(o.Textarea,{rows:i,value:y,readOnly:!0,className:"cursor-default bg-muted font-mono text-sm"}),t.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"This is how the JSON will look after placeholder substitution."})]})]})})},yn=e=>{if(!e)return!0;try{return JSON.parse(e),!0}catch{return!1}},hl=(e,s)=>{const n=e.selectionStart||0,a=e.selectionEnd||0,r=e.value,i=r.substring(0,n),l=r.substring(a),c=`{{${s}}}`,u=i+""+c+l,d=n+0+c.length;return{value:u,newCursorPos:d}},ia=()=>{const{t:e}=q.useTranslation(),[,s]=q.useSidebarActivePanel(),{data:n}=Te(),{data:a}=Qs(),{data:r,isFetching:i}=ll(),l=r==null?void 0:r.seo,c=f.useRef(null),u=n==null?void 0:n.pageType,d=Vn(u),{selectedLang:h,fallbackLang:g}=q.useLanguages(),b=h||g,[y,p]=f.useState(!1),[w,v]=f.useState(!1),[N,C]=f.useState({keyword:"",title:"",description:"",cononicalUrl:"",noIndex:!1,noFollow:"",ogTitle:"",ogDescription:"",ogImage:"",ogImageId:"",searchTitle:"",searchDescription:"",jsonLD:"{}",...l}),B=f.useRef({initial:N,updated:N}),{mutate:S,isPending:P}=Ws(),O=P||y||w,{hasPermission:z}=q.usePermissions(),$=z(je.EDIT_SEO);f.useEffect(()=>{!i&&l&&C({title:"",description:"",cononicalUrl:"",noIndex:!1,noFollow:"",ogTitle:"",ogDescription:"",ogImage:"",searchTitle:"",searchDescription:"",jsonLD:"",...l})},[i,l]);const se=async()=>{if(!(!d||!b))try{p(!0);const _=us(d,b),U={...N,keyword:m.get(_,"seo.keyword",""),title:m.get(_,"seo.title",""),description:m.get(_,"seo.description",""),cononicalUrl:m.get(_,"seo.canonicalUrl",""),noIndex:m.get(_,"seo.noIndex",!1),noFollow:m.get(_,"seo.noFollow",!1),ogTitle:m.get(_,"seo.ogTitle",""),ogDescription:m.get(_,"seo.ogDescription","")};C(U),B.current.updated=U,V.toast.success(e("SEO fields reset to defaults"))}catch(_){V.toast.error(e("Failed to reset SEO fields")),console.error("Reset SEO error:",_)}finally{p(!1)}},H=async()=>{if(!(!d||!b))try{v(!0);const _=us(d,b),U={...N,jsonLD:m.get(_,"seo.jsonLD","")};C(U),B.current.updated=U,V.toast.success(e("JSON-LD reset to default"))}catch(_){V.toast.error(e("Failed to reset JSON-LD")),console.error("Reset JSON-LD error:",_)}finally{v(!1)}},K=async()=>{S({id:r==null?void 0:r.id,seo:N},{onSuccess:()=>{B.current.initial=N,B.current.updated=N,s("outline"),V.toast.success("SEO & JSON-LD updated successfully")}})},te=(_,U)=>{const he=document.getElementById(U);if(he){const{value:ye,newCursorPos:ce}=hl(he,_);c.current={id:U,position:ce},he.tagName.toLowerCase()==="input"?(he.value=ye,C(A=>({...A,[he.name]:ye})),he.focus(),he.setSelectionRange(ce,ce),[0,10,50,100,200].forEach(A=>{setTimeout(()=>{const M=document.getElementById(U);M&&(M.focus(),M.setSelectionRange(ce,ce))},A)})):(C(x=>({...x,[he.name]:ye})),requestAnimationFrame(()=>{const x=document.getElementById(U);x&&(x.focus(),x.setSelectionRange(ce,ce),setTimeout(()=>{const A=document.getElementById(U);A&&(A.focus(),A.setSelectionRange(ce,ce))},50))}))}},Q=_=>{const U={...N,[_.target.name]:_.target.name==="noIndex"||_.target.name==="noFollow"?_.target.checked:_.target.value};C(U),B.current.updated=U},ne=_=>U=>{m.isEmpty(U.fieldValue)||Q({target:{name:_,value:typeof U.fieldValue=="string"?U.fieldValue.replace(/^"(.*)"$/,"$1"):U.fieldValue}}),U.error&&V.toast.error(t.jsxs("div",{children:[t.jsx("h2",{children:"Failed to generate:"}),t.jsx("p",{children:U.error})]}))};return t.jsxs("div",{className:"relative flex h-full flex-col",children:[!$&&t.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center backdrop-blur-sm",children:t.jsx(o.Alert,{variant:"default",className:"w-[80%] max-w-md text-xs",children:t.jsx(o.AlertDescription,{children:e("You don't have permission to edit SEO settings. Contact your administrator for access.")})})}),t.jsxs("div",{className:"no-scrollbar flex-grow overflow-y-auto px-2 pb-20",children:[t.jsxs("div",{className:"mb-4 flex w-full items-center justify-between rounded-md bg-gray-100 p-2 text-left text-sm font-bold",children:[t.jsxs("span",{children:[r==null?void 0:r.name," ",t.jsx("br",{}),t.jsx("span",{className:"text-xs text-gray-500",children:r==null?void 0:r.slug})]}),t.jsx(sn,{variant:"outline",showAdd:!1})]}),t.jsx("form",{className:"space-y-8",children:t.jsxs(o.Tabs,{defaultValue:"seo",className:"w-full",children:[t.jsxs(o.TabsList,{className:"mb-4 grid w-full grid-cols-2",children:[t.jsx(o.TabsTrigger,{value:"seo",children:e("SEO Fields")}),t.jsx(o.TabsTrigger,{value:"jsonld",children:e("JSON-LD")})]}),t.jsx(o.TabsContent,{value:"seo",children:t.jsxs("div",{className:"space-y-4",children:[$&&t.jsx("div",{className:"mb-4 flex justify-end",children:t.jsx(o.Button,{type:"button",variant:"outline",size:"sm",onClick:se,disabled:O||!$||!d,children:e(y?"Resetting...":"Reset to Default")})}),t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(o.Label,{className:"text-xs",htmlFor:"keyword",children:e("Keyword")}),$&&t.jsx(We,{dataType:"value",data:a??{},onSelect:_=>te(_,"keyword")})]}),t.jsx(o.Input,{type:"text",id:"keyword",name:"keyword",value:N.keyword,onChange:Q,disabled:O||!$,placeholder:e("Enter keyword"),readOnly:!$})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(o.Label,{className:"text-xs",htmlFor:"title",children:e("SEO Title")}),t.jsxs("div",{className:"flex items-center justify-end gap-2",children:[t.jsx(kt,{keyword:N.keyword,onComplete:ne("title"),field:"title"}),$&&t.jsx(We,{dataType:"value",data:a??{},onSelect:_=>te(_,"title")})]})]}),t.jsx(o.Input,{type:"text",id:"title",name:"title",value:N.title,onChange:Q,disabled:O||!$,placeholder:e("Enter SEO title"),readOnly:!$})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(o.Label,{className:"text-xs",htmlFor:"description",children:e("SEO Description")}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(kt,{keyword:N.keyword,onComplete:ne("description"),field:"description"}),$&&t.jsx(We,{data:a??{},onSelect:_=>te(_,"description")})]})]}),t.jsx(o.Textarea,{id:"description",name:"description",rows:5,value:N.description,onChange:Q,disabled:O||!$,placeholder:e("Enter SEO description"),readOnly:!$})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(o.Label,{className:"text-xs",htmlFor:"title",children:e("Canonical URL")}),$&&t.jsx(We,{dataType:"value",data:a??{},onSelect:_=>te(_,"canonicalUrl")})]}),t.jsx(o.Input,{type:"text",id:"canonicalUrl",name:"canonicalUrl",value:N.canonicalUrl,onChange:Q,disabled:O||!$,placeholder:e("Enter Canonical URL"),readOnly:!$})]}),t.jsxs("div",{className:"",children:[t.jsxs("div",{className:"flex items-center gap-x-2",children:[t.jsx(o.Input,{type:"checkbox",id:"noIndex",name:"noIndex",checked:N.noIndex,onChange:Q,disabled:O||!$,className:"h-4 w-4"}),t.jsx(o.Label,{className:"pb-1 text-xs",htmlFor:"noIndex",children:e("No Index")})]}),t.jsx("p",{className:"mt-0 text-[10px] font-light leading-4 text-gray-400",children:e("Check this if you don't want search engines to index this page.")})]}),t.jsxs("div",{className:"",children:[t.jsxs("div",{className:"flex items-center gap-x-2",children:[t.jsx(o.Input,{type:"checkbox",id:"noFollow",name:"noFollow",checked:N.noFollow,onChange:Q,disabled:O||!$,className:"h-4 w-4"}),t.jsx(o.Label,{className:"pb-1 text-xs",htmlFor:"noIndex",children:e("No Follow")})]}),t.jsx("p",{className:"text-[10px] font-light leading-4 text-gray-400",children:e("Check this if you don't want search engines to follow links on this page.")})]}),t.jsxs("div",{children:[t.jsx("h3",{className:"mb-4 font-semibold text-slate-700",children:e("Open Graph")}),t.jsxs("div",{className:"space-y-4",children:[t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(o.Label,{className:"text-xs",htmlFor:"ogTitle",children:e("OG Title")}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(kt,{keyword:N.keyword,onComplete:ne("ogTitle"),field:"ogTitle"}),$&&t.jsx(We,{dataType:"value",data:a??{},onSelect:_=>te(_,"ogTitle")})]})]}),t.jsx(o.Input,{type:"text",id:"ogTitle",name:"ogTitle",value:N.ogTitle,onChange:Q,disabled:O||!$,placeholder:e("Enter OG title"),readOnly:!$})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(o.Label,{className:"text-xs",htmlFor:"ogDescription",children:e("OG Description")}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(kt,{keyword:N.keyword,onComplete:ne("ogDescription"),field:"ogDescription"}),$&&t.jsx(We,{dataType:"value",data:a??{},onSelect:_=>te(_,"ogDescription")})]})]}),t.jsx(o.Textarea,{id:"ogDescription",name:"ogDescription",rows:5,value:N.ogDescription,onChange:Q,disabled:O||!$,placeholder:e("Enter OG description"),readOnly:!$})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsx("div",{className:"flex items-center justify-between",children:t.jsx(o.Label,{className:"text-xs",htmlFor:"ogImage",children:e("OG Image")})}),t.jsx(Ya,{assetId:N.ogImageId,assetUrl:N.ogImage,onChange:_=>{C({...N,ogImage:_.url,ogImageId:_.id})},disabled:O||!$,placeholder:e("Select OG image"),className:"mb-2"})]})]})]})]})}),t.jsx(o.TabsContent,{value:"jsonld",children:t.jsxs("div",{className:"space-y-4",children:[$&&t.jsx("div",{className:"mb-4 flex justify-end",children:t.jsx(o.Button,{variant:"outline",size:"sm",type:"button",onClick:H,disabled:O||!$||!d,children:e(w?"Resetting...":"Reset to Default")})}),t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(o.Label,{className:"text-xs",htmlFor:"jsonLD",children:e("JSON-LD")}),t.jsx("div",{className:"flex items-center gap-2",children:t.jsx(kt,{keyword:N.keyword,onComplete:ne("jsonLD"),field:"jsonLD"})})]}),t.jsx("div",{className:"hidden",children:JSON.stringify(a)}),t.jsx(ml,{id:"jsonLD",value:N.jsonLD,onChange:_=>{Q({target:{name:"jsonLD",value:_}})},placeholder:e("Enter JSON-LD"),disabled:O||!$,readOnly:!$,pageData:a||{},rows:12,handleFieldInsert:te})]})]})})]})})]}),$&&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:[yn(N.jsonLD)?t.jsx("div",{}):t.jsx("p",{className:"text-xs text-red-500",children:e("Invalid JSON. Please check.")}),t.jsxs("div",{className:"flex items-center gap-4",children:[t.jsx(o.Button,{onClick:K,disabled:!yn(N==null?void 0:N.jsonLD)||m.isEqual(B.current.initial,N)||O||!$,children:e(P?"Saving...":"Save")}),t.jsx(o.Button,{variant:"link",className:"text-gray-500 hover:text-gray-700",onClick:()=>s("outline"),children:e("Cancel")})]})]})]})};ia.displayName="SeoPanel";const la="seo",fl=({isActive:e,show:s})=>{const{data:n}=Te(),a=Vn(n==null?void 0:n.pageType);return!m.has(a,"hasSlug")||!a.hasSlug?null:t.jsx(o.Button,{size:"sm",className:"my-1",onClick:s,variant:e?"default":"ghost",children:t.jsxs("svg",{className:"h-4 w-4",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 21 21",fill:"currentColor",children:[t.jsx("path",{d:"M9.931 6.818c-1.238 0-2.136.925-2.136 2.2 0 1.279.898 2.207 2.136 2.207.664 0 1.257-.246 1.67-.694a.15.15 0 0 0-.009-.213l-.311-.286a.15.15 0 0 0-.213.009c-.273.297-.677.46-1.137.46-.699 0-1.233-.444-1.375-1.12h3.295a.15.15 0 0 0 .151-.151v-.211c0-1.295-.852-2.2-2.072-2.2m0 .724c.697 0 1.188.422 1.315 1.113h-2.69c.142-.673.676-1.113 1.374-1.113m4.332-.724c-1.246 0-2.15.925-2.15 2.2 0 1.279.904 2.207 2.15 2.207.596 0 1.143-.223 1.538-.628s.612-.965.612-1.579c0-1.275-.904-2.2-2.15-2.2m0 3.683c-.826 0-1.426-.624-1.426-1.483 0-.855.6-1.475 1.426-1.475s1.426.621 1.426 1.476c0 .423-.144.804-.406 1.073-.258.264-.62.41-1.019.41M6.318 8.71c-.665-.206-.902-.335-.902-.645 0-.47.564-.521.806-.521.29 0 .552.07.801.215a.15.15 0 0 0 .206-.055l.212-.366a.15.15 0 0 0-.055-.206 2.27 2.27 0 0 0-1.165-.312c-.915 0-1.53.501-1.53 1.245 0 .899.816 1.152 1.411 1.336.655.203.812.307.804.53-.016.398-.567.429-.735.429-.386 0-.722-.129-.972-.374q-.043-.042-.107-.043a.15.15 0 0 0-.106.045l-.295.302a.15.15 0 0 0 .002.213c.383.374.908.58 1.478.58.859 0 1.432-.441 1.459-1.125.031-.833-.746-1.074-1.313-1.249"}),t.jsx("path",{d:"M20.396 2.049H.604A.604.604 0 0 0 0 2.653v12.7c0 .333.27.604.604.604h6.941c-.266 1.296-.881 1.966-.886 1.971a.604.604 0 0 0 .434 1.024h6.815a.604.604 0 0 0 .434-1.024c-.007-.007-.621-.675-.886-1.971h6.941c.333 0 .604-.27.604-.604V2.652a.604.604 0 0 0-.604-.604m-.604 12.701h-.985v-.17a.604.604 0 0 0-1.208 0v.17h-.63v-.17a.604.604 0 0 0-1.208 0v.17H1.207V3.256h18.585z"})]})})},gl={id:la,label:"SEO & JSON-LD",panel:ia,button:fl,position:"top",width:600,view:"modal"},xl="user-info",pl=()=>{const{user:e,logout:s}=Ue(),n=D.useQueryClient(),a=He("onLogout",m.noop);return e?t.jsxs(o.HoverCard,{children:[t.jsx(o.HoverCardTrigger,{asChild:!0,children:t.jsx(o.Button,{variant:"ghost",className:"text-sm font-medium",children:t.jsx(E.User,{className:"w-4 h-4"})})}),t.jsxs(o.HoverCardContent,{className:"w-auto p-4 space-y-2",children:[t.jsx("div",{className:"text-sm font-medium",children:e.name??e.email}),t.jsx("div",{className:"text-xs text-muted-foreground",children:e.email}),t.jsxs(o.AlertDialog,{children:[t.jsx(o.AlertDialogTrigger,{asChild:!0,children:t.jsx(o.Button,{variant:"outline",size:"sm",className:"w-full",children:"Logout"})}),t.jsxs(o.AlertDialogContent,{children:[t.jsxs(o.AlertDialogHeader,{children:[t.jsx(o.AlertDialogTitle,{children:"Are you sure you want to logout?"}),t.jsx(o.AlertDialogDescription,{children:"You will be redirected to the login page."})]}),t.jsxs(o.AlertDialogFooter,{children:[t.jsx(o.AlertDialogCancel,{children:"Cancel"}),t.jsx(o.AlertDialogAction,{onClick:()=>{s(),n.invalidateQueries({queryKey:[Y]}),m.isFunction(a)&&a()},children:"Logout"})]})]})]})]})]}):null},yl={id:xl,label:"User Info",button:pl,position:"bottom"},jl=()=>{q.registerChaiSidebarPanel(la,gl),q.registerChaiSidebarPanel(ra,il),q.registerChaiSidebarPanel("user-info",yl)};var ee={context:void 0,registry:void 0,effects:void 0,done:!1,getContextId(){return jn(this.context.count)},getNextContextId(){return jn(this.context.count++)}};function jn(e){const s=String(e),n=s.length-1;return ee.context.id+(n?String.fromCharCode(96+n):"")+s}function Lt(e){ee.context=e}var vl=(e,s)=>e===s,ds=Symbol("solid-proxy"),oa=typeof Proxy=="function",nn=Symbol("solid-track"),ms={equals:vl},ca=xa,Qe=1,hs=2,ua={owned:null,cleanups:null,context:null,owner:null},Ps={},me=null,ks=null,bl=null,xe=null,Le=null,$e=null,ws=0;function Ye(e,s){const n=xe,a=me,r=e.length===0,i=s===void 0?a:s,l=r?ua:{owned:null,cleanups:null,context:i?i.context:null,owner:i},c=r?e:()=>e(()=>Ae(()=>Ot(l)));me=l,xe=null;try{return ze(c,!0)}finally{xe=n,me=a}}function Se(e,s){s=s?Object.assign({},ms,s):ms;const n={value:e,observers:null,observerSlots:null,comparator:s.equals||void 0},a=r=>(typeof r=="function"&&(r=r(n.value)),ga(n,r));return[fa.bind(n),a]}function da(e,s,n){const a=Ss(e,s,!0,Qe);Tt(a)}function Je(e,s,n){const a=Ss(e,s,!1,Qe);Tt(a)}function an(e,s,n){ca=Bl;const a=Ss(e,s,!1,Qe);(!n||!n.render)&&(a.user=!0),$e?$e.push(a):Tt(a)}function Be(e,s,n){n=n?Object.assign({},ms,n):ms;const a=Ss(e,s,!0,0);return a.observers=null,a.observerSlots=null,a.comparator=n.equals||void 0,Tt(a),fa.bind(a)}function wl(e){return e&&typeof e=="object"&&"then"in e}function Sl(e,s,n){let a,r,i;arguments.length===1?(a=!0,r=e,i={}):(a=e,r=s,i={});let l=null,c=Ps,u=null,d=!1,h="initialValue"in i,g=typeof a=="function"&&Be(a);const b=new Set,[y,p]=(i.storage||Se)(i.initialValue),[w,v]=Se(void 0),[N,C]=Se(void 0,{equals:!1}),[B,S]=Se(h?"ready":"unresolved");ee.context&&(u=ee.getNextContextId(),i.ssrLoadFrom==="initial"?c=i.initialValue:ee.load&&ee.has(u)&&(c=ee.load(u)));function P(se,H,K,te){return l===se&&(l=null,te!==void 0&&(h=!0),(se===c||H===c)&&i.onHydrated&&queueMicrotask(()=>i.onHydrated(te,{value:H})),c=Ps,O(H,K)),H}function O(se,H){ze(()=>{H===void 0&&p(()=>se),S(H!==void 0?"errored":h?"ready":"unresolved"),v(H);for(const K of b.keys())K.decrement();b.clear()},!1)}function z(){const se=Il,H=y(),K=w();if(K!==void 0&&!l)throw K;return xe&&xe.user,H}function $(se=!0){if(se!==!1&&d)return;d=!1;const H=g?g():a;if(H==null||H===!1){P(l,Ae(y));return}const K=c!==Ps?c:Ae(()=>r(H,{value:y(),refetching:se}));return wl(K)?(l=K,"value"in K?(K.status==="success"?P(l,K.value,void 0,H):P(l,void 0,Bs(K.value),H),K):(d=!0,queueMicrotask(()=>d=!1),ze(()=>{S(h?"refreshing":"pending"),C()},!1),K.then(te=>P(K,te,void 0,H),te=>P(K,void 0,Bs(te),H)))):(P(l,K,void 0,H),K)}return Object.defineProperties(z,{state:{get:()=>B()},error:{get:()=>w()},loading:{get(){const se=B();return se==="pending"||se==="refreshing"}},latest:{get(){if(!h)return z();const se=w();if(se&&!l)throw se;return y()}}}),g?da(()=>$(!1)):$(!1),[z,{refetch:$,mutate:p}]}function El(e){return ze(e,!1)}function Ae(e){if(xe===null)return e();const s=xe;xe=null;try{return e()}finally{xe=s}}function Nl(e,s,n){const a=Array.isArray(e);let r,i=n&&n.defer;return l=>{let c;if(a){c=Array(e.length);for(let d=0;d<e.length;d++)c[d]=e[d]()}else c=e();if(i)return i=!1,l;const u=Ae(()=>s(c,r,l));return r=c,u}}function ma(e){an(()=>Ae(e))}function Et(e){return me===null||(me.cleanups===null?me.cleanups=[e]:me.cleanups.push(e)),e}function vn(){return me}function Cl(e,s){const n=me,a=xe;me=e,xe=null;try{return ze(s,!0)}catch(r){rn(r)}finally{me=n,xe=a}}function Al(e){const s=xe,n=me;return Promise.resolve().then(()=>{xe=s,me=n;let a;return ze(e,!1),xe=me=null,a?a.done:void 0})}var[Tl,Bc]=Se(!1);function Pl(){return[Tl,Al]}function kl(e,s){const n=Symbol("context");return{id:n,Provider:Ml(n),defaultValue:e}}function Ll(e){let s;return me&&me.context&&(s=me.context[e.id])!==void 0?s:e.defaultValue}function ha(e){const s=Be(e),n=Be(()=>Ms(s()));return n.toArray=()=>{const a=n();return Array.isArray(a)?a:a!=null?[a]:[]},n}var Il;function fa(){if(this.sources&&this.state)if(this.state===Qe)Tt(this);else{const e=Le;Le=null,ze(()=>gs(this),!1),Le=e}if(xe){const e=this.observers?this.observers.length:0;xe.sources?(xe.sources.push(this),xe.sourceSlots.push(e)):(xe.sources=[this],xe.sourceSlots=[e]),this.observers?(this.observers.push(xe),this.observerSlots.push(xe.sources.length-1)):(this.observers=[xe],this.observerSlots=[xe.sources.length-1])}return this.value}function ga(e,s,n){let a=e.value;return(!e.comparator||!e.comparator(a,s))&&(e.value=s,e.observers&&e.observers.length&&ze(()=>{for(let r=0;r<e.observers.length;r+=1){const i=e.observers[r],l=ks&&ks.running;l&&ks.disposed.has(i),(l?!i.tState:!i.state)&&(i.pure?Le.push(i):$e.push(i),i.observers&&pa(i)),l||(i.state=Qe)}if(Le.length>1e6)throw Le=[],new Error},!1)),s}function Tt(e){if(!e.fn)return;Ot(e);const s=ws;_l(e,e.value,s)}function _l(e,s,n){let a;const r=me,i=xe;xe=me=e;try{a=e.fn(s)}catch(l){return e.pure&&(e.state=Qe,e.owned&&e.owned.forEach(Ot),e.owned=null),e.updatedAt=n+1,rn(l)}finally{xe=i,me=r}(!e.updatedAt||e.updatedAt<=n)&&(e.updatedAt!=null&&"observers"in e?ga(e,a):e.value=a,e.updatedAt=n)}function Ss(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:me,context:me?me.context:null,pure:n};return me===null||me!==ua&&(me.owned?me.owned.push(i):me.owned=[i]),i}function fs(e){if(e.state===0)return;if(e.state===hs)return gs(e);if(e.suspense&&Ae(e.suspense.inFallback))return e.suspense.effects.push(e);const s=[e];for(;(e=e.owner)&&(!e.updatedAt||e.updatedAt<ws);)e.state&&s.push(e);for(let n=s.length-1;n>=0;n--)if(e=s[n],e.state===Qe)Tt(e);else if(e.state===hs){const a=Le;Le=null,ze(()=>gs(e,s[0]),!1),Le=a}}function ze(e,s){if(Le)return e();let n=!1;s||(Le=[]),$e?n=!0:$e=[],ws++;try{const a=e();return Dl(n),a}catch(a){n||($e=null),Le=null,rn(a)}}function Dl(e){if(Le&&(xa(Le),Le=null),e)return;const s=$e;$e=null,s.length&&ze(()=>ca(s),!1)}function xa(e){for(let s=0;s<e.length;s++)fs(e[s])}function Bl(e){let s,n=0;for(s=0;s<e.length;s++){const a=e[s];a.user?e[n++]=a:fs(a)}if(ee.context){if(ee.count){ee.effects||(ee.effects=[]),ee.effects.push(...e.slice(0,n));return}Lt()}for(ee.effects&&(ee.done||!ee.count)&&(e=[...ee.effects,...e],n+=ee.effects.length,delete ee.effects),s=0;s<n;s++)fs(e[s])}function gs(e,s){e.state=0;for(let n=0;n<e.sources.length;n+=1){const a=e.sources[n];if(a.sources){const r=a.state;r===Qe?a!==s&&(!a.updatedAt||a.updatedAt<ws)&&fs(a):r===hs&&gs(a,s)}}}function pa(e){for(let s=0;s<e.observers.length;s+=1){const n=e.observers[s];n.state||(n.state=hs,n.pure?Le.push(n):$e.push(n),n.observers&&pa(n))}}function Ot(e){let s;if(e.sources)for(;e.sources.length;){const n=e.sources.pop(),a=e.sourceSlots.pop(),r=n.observers;if(r&&r.length){const i=r.pop(),l=n.observerSlots.pop();a<r.length&&(i.sourceSlots[l]=a,r[a]=i,n.observerSlots[a]=l)}}if(e.tOwned){for(s=e.tOwned.length-1;s>=0;s--)Ot(e.tOwned[s]);delete e.tOwned}if(e.owned){for(s=e.owned.length-1;s>=0;s--)Ot(e.owned[s]);e.owned=null}if(e.cleanups){for(s=e.cleanups.length-1;s>=0;s--)e.cleanups[s]();e.cleanups=null}e.state=0}function Bs(e){return e instanceof Error?e:new Error(typeof e=="string"?e:"Unknown error",{cause:e})}function rn(e,s=me){throw Bs(e)}function Ms(e){if(typeof e=="function"&&!e.length)return Ms(e());if(Array.isArray(e)){const s=[];for(let n=0;n<e.length;n++){const a=Ms(e[n]);Array.isArray(a)?s.push.apply(s,a):s.push(a)}return s}return e}function Ml(e,s){return function(a){let r;return Je(()=>r=Ae(()=>(me.context={...me.context,[e]:a.value},ha(()=>a.children))),void 0),r}}var Os=Symbol("fallback");function xs(e){for(let s=0;s<e.length;s++)e[s]()}function Ol(e,s,n={}){let a=[],r=[],i=[],l=0,c=s.length>1?[]:null;return Et(()=>xs(i)),()=>{let u=e()||[],d=u.length,h,g;return u[nn],Ae(()=>{let y,p,w,v,N,C,B,S,P;if(d===0)l!==0&&(xs(i),i=[],a=[],r=[],l=0,c&&(c=[])),n.fallback&&(a=[Os],r[0]=Ye(O=>(i[0]=O,n.fallback())),l=1);else if(l===0){for(r=new Array(d),g=0;g<d;g++)a[g]=u[g],r[g]=Ye(b);l=d}else{for(w=new Array(d),v=new Array(d),c&&(N=new Array(d)),C=0,B=Math.min(l,d);C<B&&a[C]===u[C];C++);for(B=l-1,S=d-1;B>=C&&S>=C&&a[B]===u[S];B--,S--)w[S]=r[B],v[S]=i[B],c&&(N[S]=c[B]);for(y=new Map,p=new Array(S+1),g=S;g>=C;g--)P=u[g],h=y.get(P),p[g]=h===void 0?-1:h,y.set(P,g);for(h=C;h<=B;h++)P=a[h],g=y.get(P),g!==void 0&&g!==-1?(w[g]=r[h],v[g]=i[h],c&&(N[g]=c[h]),g=p[g],y.set(P,g)):i[h]();for(g=C;g<d;g++)g in w?(r[g]=w[g],i[g]=v[g],c&&(c[g]=N[g],c[g](g))):r[g]=Ye(b);r=r.slice(0,l=d),a=u.slice(0)}return r});function b(y){if(i[g]=y,c){const[p,w]=Se(g);return c[g]=w,s(u[g],p)}return s(u[g])}}}function Gl(e,s,n={}){let a=[],r=[],i=[],l=[],c=0,u;return Et(()=>xs(i)),()=>{const d=e()||[],h=d.length;return d[nn],Ae(()=>{if(h===0)return c!==0&&(xs(i),i=[],a=[],r=[],c=0,l=[]),n.fallback&&(a=[Os],r[0]=Ye(b=>(i[0]=b,n.fallback())),c=1),r;for(a[0]===Os&&(i[0](),i=[],a=[],r=[],c=0),u=0;u<h;u++)u<a.length&&a[u]!==d[u]?l[u](()=>d[u]):u>=a.length&&(r[u]=Ye(g));for(;u<a.length;u++)i[u]();return c=l.length=i.length=h,a=d.slice(0),r=r.slice(0,c)});function g(b){i[u]=b;const[y,p]=Se(d[u]);return l[u]=p,s(y,u)}}}function ln(e,s){return Ae(()=>e(s||{}))}function as(){return!0}var Gs={get(e,s,n){return s===ds?n:e.get(s)},has(e,s){return s===ds?!0:e.has(s)},set:as,deleteProperty:as,getOwnPropertyDescriptor(e,s){return{configurable:!0,enumerable:!0,get(){return e.get(s)},set:as,deleteProperty:as}},ownKeys(e){return e.keys()}};function Ls(e){return(e=typeof e=="function"?e():e)?e:{}}function Rl(){for(let e=0,s=this.length;e<s;++e){const n=this[e]();if(n!==void 0)return n}}function on(...e){let s=!1;for(let l=0;l<e.length;l++){const c=e[l];s=s||!!c&&ds in c,e[l]=typeof c=="function"?(s=!0,Be(c)):c}if(oa&&s)return new Proxy({get(l){for(let c=e.length-1;c>=0;c--){const u=Ls(e[c])[l];if(u!==void 0)return u}},has(l){for(let c=e.length-1;c>=0;c--)if(l in Ls(e[c]))return!0;return!1},keys(){const l=[];for(let c=0;c<e.length;c++)l.push(...Object.keys(Ls(e[c])));return[...new Set(l)]}},Gs);const n={},a=Object.create(null);for(let l=e.length-1;l>=0;l--){const c=e[l];if(!c)continue;const u=Object.getOwnPropertyNames(c);for(let d=u.length-1;d>=0;d--){const h=u[d];if(h==="__proto__"||h==="constructor")continue;const g=Object.getOwnPropertyDescriptor(c,h);if(!a[h])a[h]=g.get?{enumerable:!0,configurable:!0,get:Rl.bind(n[h]=[g.get.bind(c)])}:g.value!==void 0?g:void 0;else{const b=n[h];b&&(g.get?b.push(g.get.bind(c)):g.value!==void 0&&b.push(()=>g.value))}}}const r={},i=Object.keys(a);for(let l=i.length-1;l>=0;l--){const c=i[l],u=a[c];u&&u.get?Object.defineProperty(r,c,u):r[c]=u?u.value:void 0}return r}function ya(e,...s){if(oa&&ds in e){const r=new Set(s.length>1?s.flat():s[0]),i=s.map(l=>new Proxy({get(c){return l.includes(c)?e[c]:void 0},has(c){return l.includes(c)&&c in e},keys(){return l.filter(c=>c in e)}},Gs));return i.push(new Proxy({get(l){return r.has(l)?void 0:e[l]},has(l){return r.has(l)?!1:l in e},keys(){return Object.keys(e).filter(l=>!r.has(l))}},Gs)),i}const n={},a=s.map(()=>({}));for(const r of Object.getOwnPropertyNames(e)){const i=Object.getOwnPropertyDescriptor(e,r),l=!i.get&&!i.set&&i.enumerable&&i.writable&&i.configurable;let c=!1,u=0;for(const d of s)d.includes(r)&&(c=!0,l?a[u][r]=i.value:Object.defineProperty(a[u],r,i)),++u;c||(l?n[r]=i.value:Object.defineProperty(n,r,i))}return[...a,n]}function ja(e){let s,n;const a=r=>{const i=ee.context;if(i){const[c,u]=Se();ee.count||(ee.count=0),ee.count++,(n||(n=e())).then(d=>{!ee.done&&Lt(i),ee.count--,u(()=>d.default),Lt()}),s=c}else if(!s){const[c]=Sl(()=>(n||(n=e())).then(u=>u.default));s=c}let l;return Be(()=>(l=s())?Ae(()=>{if(!i||ee.done)return l(r);const c=ee.context;Lt(i);const u=l(r);return Lt(c),u}):"")};return a.preload=()=>n||((n=e()).then(r=>s=()=>r.default),n),a}var Ul=0;function Fl(){return ee.context?ee.getNextContextId():`cl-${Ul++}`}var va=e=>`Stale read from <${e}>.`;function ql(e){const s="fallback"in e&&{fallback:()=>e.fallback};return Be(Ol(()=>e.each,e.children,s||void 0))}function zl(e){const s="fallback"in e&&{fallback:()=>e.fallback};return Be(Gl(()=>e.each,e.children,s||void 0))}function $l(e){const s=e.keyed,n=Be(()=>e.when,void 0,{equals:(a,r)=>s?a===r:!a==!r});return Be(()=>{const a=n();if(a){const r=e.children;return typeof r=="function"&&r.length>0?Ae(()=>r(s?a:()=>{if(!Ae(n))throw va("Show");return e.when})):r}return e.fallback},void 0,void 0)}function Vl(e){let s=!1;const n=(i,l)=>(s?i[1]===l[1]:!i[1]==!l[1])&&i[2]===l[2],a=ha(()=>e.children),r=Be(()=>{let i=a();Array.isArray(i)||(i=[i]);for(let l=0;l<i.length;l++){const c=i[l].when;if(c)return s=!!i[l].keyed,[l,c,i[l]]}return[-1]},void 0,{equals:n});return Be(()=>{const[i,l,c]=r();if(i<0)return e.fallback;const u=c.children;return typeof u=="function"&&u.length>0?Ae(()=>u(s?l:()=>{if(Ae(r)[0]!==i)throw va("Match");return c.when})):u},void 0,void 0)}function Hl(e){return e}var Kl=["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"],Ql=new Set(["className","value","readOnly","formNoValidate","isMap","noModule","playsInline",...Kl]),Wl=new Set(["innerHTML","textContent","innerText","children"]),Yl=Object.assign(Object.create(null),{className:"class",htmlFor:"for"}),Jl=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 Xl(e,s){const n=Jl[e];return typeof n=="object"?n[s]?n.$:void 0:n}var Zl=new Set(["beforeinput","click","dblclick","contextmenu","focusin","focusout","input","keydown","keyup","mousedown","mousemove","mouseout","mouseover","mouseup","pointerdown","pointermove","pointerout","pointerover","pointerup","touchend","touchmove","touchstart"]),eo=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"]),to={xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace"};function so(e,s,n){let a=n.length,r=s.length,i=a,l=0,c=0,u=s[r-1].nextSibling,d=null;for(;l<r||c<i;){if(s[l]===n[c]){l++,c++;continue}for(;s[r-1]===n[i-1];)r--,i--;if(r===l){const h=i<a?c?n[c-1].nextSibling:n[i-c]:u;for(;c<i;)e.insertBefore(n[c++],h)}else if(i===c)for(;l<r;)(!d||!d.has(s[l]))&&s[l].remove(),l++;else if(s[l]===n[i-1]&&n[c]===s[r-1]){const h=s[--r].nextSibling;e.insertBefore(n[c++],s[l++].nextSibling),e.insertBefore(n[--i],h),s[r]=n[i]}else{if(!d){d=new Map;let g=c;for(;g<i;)d.set(n[g],g++)}const h=d.get(s[l]);if(h!=null)if(c<h&&h<i){let g=l,b=1,y;for(;++g<r&&g<i&&!((y=d.get(s[g]))==null||y!==h+b);)b++;if(b>h-c){const p=s[l];for(;c<h;)e.insertBefore(n[c++],p)}else e.replaceChild(n[c++],s[l++])}else l++;else s[l++].remove()}}}var Bt="_$DX_DELEGATE";function ba(e,s,n,a={}){let r;return Ye(i=>{r=i,s===document?e():ys(s,e(),s.firstChild?null:void 0,n)},a.owner),()=>{r(),s.textContent=""}}function no(e,s,n){let a;const r=()=>{const l=document.createElement("template");return l.innerHTML=e,l.content.firstChild},i=()=>(a||(a=r())).cloneNode(!0);return i.cloneNode=i,i}function wa(e,s=window.document){const n=s[Bt]||(s[Bt]=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,Aa))}}function ao(e=window.document){if(e[Bt]){for(let s of e[Bt].keys())e.removeEventListener(s,Aa);delete e[Bt]}}function ps(e,s,n){at(e)||(n==null?e.removeAttribute(s):e.setAttribute(s,n))}function ro(e,s,n,a){at(e)||(a==null?e.removeAttributeNS(s,n):e.setAttributeNS(s,n,a))}function io(e,s,n){at(e)||(n?e.setAttribute(s,""):e.removeAttribute(s))}function Sa(e,s){at(e)||(s==null?e.removeAttribute("class"):e.className=s)}function Ea(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 lo(e,s,n={}){const a=Object.keys(s||{}),r=Object.keys(n);let i,l;for(i=0,l=r.length;i<l;i++){const c=r[i];!c||c==="undefined"||s[c]||(bn(e,c,!1),delete n[c])}for(i=0,l=a.length;i<l;i++){const c=a[i],u=!!s[c];!c||c==="undefined"||n[c]===u||!u||(bn(e,c,!0),n[c]=u)}return n}function oo(e,s,n){if(!s)return n?ps(e,"style"):s;const a=e.style;if(typeof s=="string")return a.cssText=s;typeof n=="string"&&(a.cssText=n=void 0),n||(n={}),s||(s={});let r,i;for(i in n)s[i]==null&&a.removeProperty(i),delete n[i];for(i in s)r=s[i],r!==n[i]&&(a.setProperty(i,r),n[i]=r);return n}function Na(e,s={},n,a){const r={};return a||Je(()=>r.children=Gt(e,s.children,r.children)),Je(()=>typeof s.ref=="function"&&Ca(s.ref,e)),Je(()=>co(e,s,n,!0,r,!0)),r}function Ca(e,s,n){return Ae(()=>e(s,n))}function ys(e,s,n,a){if(n!==void 0&&!a&&(a=[]),typeof s!="function")return Gt(e,s,a,n);Je(r=>Gt(e,s(),r,n),a)}function co(e,s,n,a,r={},i=!1){s||(s={});for(const l in r)if(!(l in s)){if(l==="children")continue;r[l]=wn(e,l,null,r[l],n,i,s)}for(const l in s){if(l==="children")continue;const c=s[l];r[l]=wn(e,l,c,r[l],n,i,s)}}function uo(e){let s,n;return!at()||!(s=ee.registry.get(n=ho()))?e():(ee.completed&&ee.completed.add(s),ee.registry.delete(n),s)}function at(e){return!!ee.context&&!ee.done&&(!e||e.isConnected)}function mo(e){return e.toLowerCase().replace(/-([a-z])/g,(s,n)=>n.toUpperCase())}function bn(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 wn(e,s,n,a,r,i,l){let c,u,d,h,g;if(s==="style")return oo(e,n,a);if(s==="classList")return lo(e,n,a);if(n===a)return a;if(s==="ref")i||n(e);else if(s.slice(0,3)==="on:"){const b=s.slice(3);a&&e.removeEventListener(b,a,typeof a!="function"&&a),n&&e.addEventListener(b,n,typeof n!="function"&&n)}else if(s.slice(0,10)==="oncapture:"){const b=s.slice(10);a&&e.removeEventListener(b,a,!0),n&&e.addEventListener(b,n,!0)}else if(s.slice(0,2)==="on"){const b=s.slice(2).toLowerCase(),y=Zl.has(b);if(!y&&a){const p=Array.isArray(a)?a[0]:a;e.removeEventListener(b,p)}(y||n)&&(Ea(e,b,n,y),y&&wa([b]))}else if(s.slice(0,5)==="attr:")ps(e,s.slice(5),n);else if(s.slice(0,5)==="bool:")io(e,s.slice(5),n);else if((g=s.slice(0,5)==="prop:")||(d=Wl.has(s))||!r&&((h=Xl(s,e.tagName))||(u=Ql.has(s)))||(c=e.nodeName.includes("-")||"is"in l)){if(g)s=s.slice(5),u=!0;else if(at(e))return n;s==="class"||s==="className"?Sa(e,n):c&&!u&&!d?e[mo(s)]=n:e[h||s]=n}else{const b=r&&s.indexOf(":")>-1&&to[s.split(":")[0]];b?ro(e,b,s,n):ps(e,Yl[s]||s,n)}return n}function Aa(e){if(ee.registry&&ee.events&&ee.events.find(([u,d])=>d===e))return;let s=e.target;const n=`$$${e.type}`,a=e.target,r=e.currentTarget,i=u=>Object.defineProperty(e,"target",{configurable:!0,value:u}),l=()=>{const u=s[n];if(u&&!s.disabled){const d=s[`${n}Data`];if(d!==void 0?u.call(s,d,e):u.call(s,e),e.cancelBubble)return}return s.host&&typeof s.host!="string"&&!s.host._$host&&s.contains(e.target)&&i(s.host),!0},c=()=>{for(;l()&&(s=s._$host||s.parentNode||s.host););};if(Object.defineProperty(e,"currentTarget",{configurable:!0,get(){return s||document}}),ee.registry&&!ee.done&&(ee.done=_$HY.done=!0),e.composedPath){const u=e.composedPath();i(u[0]);for(let d=0;d<u.length-2&&(s=u[d],!!l());d++){if(s._$host){s=s._$host,c();break}if(s.parentNode===r)break}}else c();i(a)}function Gt(e,s,n,a,r){const i=at(e);if(i){!n&&(n=[...e.childNodes]);let u=[];for(let d=0;d<n.length;d++){const h=n[d];h.nodeType===8&&h.data.slice(0,2)==="!$"?h.remove():u.push(h)}n=u}for(;typeof n=="function";)n=n();if(s===n)return n;const l=typeof s,c=a!==void 0;if(e=c&&n[0]&&n[0].parentNode||e,l==="string"||l==="number"){if(i||l==="number"&&(s=s.toString(),s===n))return n;if(c){let u=n[0];u&&u.nodeType===3?u.data!==s&&(u.data=s):u=document.createTextNode(s),n=lt(e,n,a,u)}else n!==""&&typeof n=="string"?n=e.firstChild.data=s:n=e.textContent=s}else if(s==null||l==="boolean"){if(i)return n;n=lt(e,n,a)}else{if(l==="function")return Je(()=>{let u=s();for(;typeof u=="function";)u=u();n=Gt(e,u,n,a)}),()=>n;if(Array.isArray(s)){const u=[],d=n&&Array.isArray(n);if(Rs(u,s,n,r))return Je(()=>n=Gt(e,u,n,a,!0)),()=>n;if(i){if(!u.length)return n;if(a===void 0)return n=[...e.childNodes];let h=u[0];if(h.parentNode!==e)return n;const g=[h];for(;(h=h.nextSibling)!==a;)g.push(h);return n=g}if(u.length===0){if(n=lt(e,n,a),c)return n}else d?n.length===0?Sn(e,u,a):so(e,n,u):(n&<(e),Sn(e,u));n=u}else if(s.nodeType){if(i&&s.parentNode)return n=c?[s]:s;if(Array.isArray(n)){if(c)return n=lt(e,n,a,s);lt(e,n,null,s)}else n==null||n===""||!e.firstChild?e.appendChild(s):e.replaceChild(s,e.firstChild);n=s}}return n}function Rs(e,s,n,a){let r=!1;for(let i=0,l=s.length;i<l;i++){let c=s[i],u=n&&n[e.length],d;if(!(c==null||c===!0||c===!1))if((d=typeof c)=="object"&&c.nodeType)e.push(c);else if(Array.isArray(c))r=Rs(e,c,u)||r;else if(d==="function")if(a){for(;typeof c=="function";)c=c();r=Rs(e,Array.isArray(c)?c:[c],Array.isArray(u)?u:[u])||r}else e.push(c),r=!0;else{const h=String(c);u&&u.nodeType===3&&u.data===h?e.push(u):e.push(document.createTextNode(h))}}return r}function Sn(e,s,n=null){for(let a=0,r=s.length;a<r;a++)e.insertBefore(s[a],n)}function lt(e,s,n,a){if(n===void 0)return e.textContent="";const r=a||document.createTextNode("");if(s.length){let i=!1;for(let l=s.length-1;l>=0;l--){const c=s[l];if(r!==c){const u=c.parentNode===e;!i&&!l?u?e.replaceChild(r,c):e.insertBefore(r,n):u&&c.remove()}else i=!0}}else e.insertBefore(r,n);return[r]}function ho(){return ee.getNextContextId()}var fo="http://www.w3.org/2000/svg";function Ta(e,s=!1){return s?document.createElementNS(fo,e):document.createElement(e)}function go(e){const{useShadow:s}=e,n=document.createTextNode(""),a=()=>e.mount||document.body,r=vn();let i,l=!!ee.context;return an(()=>{l&&(vn().user=l=!1),i||(i=Cl(r,()=>Be(()=>e.children)));const c=a();if(c instanceof HTMLHeadElement){const[u,d]=Se(!1),h=()=>d(!0);Ye(g=>ys(c,()=>u()?g():i(),null)),Et(h)}else{const u=Ta(e.isSVG?"g":"div",e.isSVG),d=s&&u.attachShadow?u.attachShadow({mode:"open"}):u;Object.defineProperty(u,"_$host",{get(){return n.parentNode},configurable:!0}),ys(d,i),c.appendChild(u),e.ref&&e.ref(u),Et(()=>c.removeChild(u))}},void 0,{render:!l}),n}function xo(e){const[s,n]=ya(e,["component"]),a=Be(()=>s.component);return Be(()=>{const r=a();switch(typeof r){case"function":return Ae(()=>r(n));case"string":const i=eo.has(r),l=ee.context?uo():Ta(r,i);return Na(l,n,i),l}})}var po=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()}},Pa=class{constructor(e){this.generateIdentifier=e,this.kv=new po}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)}},yo=class extends Pa{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 jo(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 vo(e,s){const n=jo(e);if("find"in n)return n.find(s);const a=n;for(let r=0;r<a.length;r++){const i=a[r];if(s(i))return i}}function Nt(e,s){Object.entries(e).forEach(([n,a])=>s(a,n))}function os(e,s){return e.indexOf(s)!==-1}function En(e,s){for(let n=0;n<e.length;n++){const a=e[n];if(s(a))return a}}var bo=class{constructor(){this.transfomers={}}register(e){this.transfomers[e.name]=e}findApplicable(e){return vo(this.transfomers,s=>s.isApplicable(e))}findByName(e){return this.transfomers[e]}},wo=e=>Object.prototype.toString.call(e).slice(8,-1),ka=e=>typeof e>"u",So=e=>e===null,Rt=e=>typeof e!="object"||e===null||e===Object.prototype?!1:Object.getPrototypeOf(e)===null?!0:Object.getPrototypeOf(e)===Object.prototype,Us=e=>Rt(e)&&Object.keys(e).length===0,Xe=e=>Array.isArray(e),Eo=e=>typeof e=="string",No=e=>typeof e=="number"&&!isNaN(e),Co=e=>typeof e=="boolean",Ao=e=>e instanceof RegExp,Ut=e=>e instanceof Map,Ft=e=>e instanceof Set,La=e=>wo(e)==="Symbol",To=e=>e instanceof Date&&!isNaN(e.valueOf()),Po=e=>e instanceof Error,Nn=e=>typeof e=="number"&&isNaN(e),ko=e=>Co(e)||So(e)||ka(e)||No(e)||Eo(e)||La(e),Lo=e=>typeof e=="bigint",Io=e=>e===1/0||e===-1/0,_o=e=>ArrayBuffer.isView(e)&&!(e instanceof DataView),Do=e=>e instanceof URL,Ia=e=>e.replace(/\./g,"\\."),Is=e=>e.map(String).map(Ia).join("."),Mt=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 qe(e,s,n,a){return{isApplicable:e,annotation:s,transform:n,untransform:a}}var _a=[qe(ka,"undefined",()=>null,()=>{}),qe(Lo,"bigint",e=>e.toString(),e=>typeof BigInt<"u"?BigInt(e):e),qe(To,"Date",e=>e.toISOString(),e=>new Date(e)),qe(Po,"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}),qe(Ao,"regexp",e=>""+e,e=>{const s=e.slice(1,e.lastIndexOf("/")),n=e.slice(e.lastIndexOf("/")+1);return new RegExp(s,n)}),qe(Ft,"set",e=>[...e.values()],e=>new Set(e)),qe(Ut,"map",e=>[...e.entries()],e=>new Map(e)),qe(e=>Nn(e)||Io(e),"number",e=>Nn(e)?"NaN":e>0?"Infinity":"-Infinity",Number),qe(e=>e===0&&1/e===-1/0,"number",()=>"-0",Number),qe(Do,"URL",e=>e.toString(),e=>new URL(e))];function Es(e,s,n,a){return{isApplicable:e,annotation:s,transform:n,untransform:a}}var Da=Es((e,s)=>La(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}),Bo=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,Uint8ClampedArray].reduce((e,s)=>(e[s.name]=s,e),{}),Ba=Es(_o,e=>["typed-array",e.constructor.name],e=>[...e],(e,s)=>{const n=Bo[s[1]];if(!n)throw new Error("Trying to deserialize unknown typed array");return new n(e)});function Ma(e,s){return e!=null&&e.constructor?!!s.classRegistry.getIdentifier(e.constructor):!1}var Oa=Es(Ma,(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)}),Ga=Es((e,s)=>!!s.customTransformerRegistry.findApplicable(e),(e,s)=>["custom",s.customTransformerRegistry.findApplicable(e).name],(e,s)=>s.customTransformerRegistry.findApplicable(e).serialize(e),(e,s,n)=>{const a=n.customTransformerRegistry.findByName(s[1]);if(!a)throw new Error("Trying to deserialize unknown custom value");return a.deserialize(e)}),Mo=[Oa,Da,Ga,Ba],Cn=(e,s)=>{const n=En(Mo,r=>r.isApplicable(e,s));if(n)return{value:n.transform(e,s),type:n.annotation(e,s)};const a=En(_a,r=>r.isApplicable(e,s));if(a)return{value:a.transform(e,s),type:a.annotation}},Ra={};_a.forEach(e=>{Ra[e.annotation]=e});var Oo=(e,s,n)=>{if(Xe(s))switch(s[0]){case"symbol":return Da.untransform(e,s,n);case"class":return Oa.untransform(e,s,n);case"custom":return Ga.untransform(e,s,n);case"typed-array":return Ba.untransform(e,s,n);default:throw new Error("Unknown transformation: "+s)}else{const a=Ra[s];if(!a)throw new Error("Unknown transformation: "+s);return a.untransform(e,n)}},ot=(e,s)=>{const n=e.keys();for(;s>0;)n.next(),s--;return n.next().value};function Ua(e){if(os(e,"__proto__"))throw new Error("__proto__ is not allowed as a property");if(os(e,"prototype"))throw new Error("prototype is not allowed as a property");if(os(e,"constructor"))throw new Error("constructor is not allowed as a property")}var Go=(e,s)=>{Ua(s);for(let n=0;n<s.length;n++){const a=s[n];if(Ft(e))e=ot(e,+a);else if(Ut(e)){const r=+a,i=+s[++n]==0?"key":"value",l=ot(e,r);switch(i){case"key":e=l;break;case"value":e=e.get(l);break}}else e=e[a]}return e},Fs=(e,s,n)=>{if(Ua(s),s.length===0)return n(e);let a=e;for(let i=0;i<s.length-1;i++){const l=s[i];if(Xe(a)){const c=+l;a=a[c]}else if(Rt(a))a=a[l];else if(Ft(a)){const c=+l;a=ot(a,c)}else if(Ut(a)){if(i===s.length-2)break;const u=+l,d=+s[++i]==0?"key":"value",h=ot(a,u);switch(d){case"key":a=h;break;case"value":a=a.get(h);break}}}const r=s[s.length-1];if(Xe(a)?a[+r]=n(a[+r]):Rt(a)&&(a[r]=n(a[r])),Ft(a)){const i=ot(a,+r),l=n(i);i!==l&&(a.delete(i),a.add(l))}if(Ut(a)){const i=+s[s.length-2],l=ot(a,i);switch(+r==0?"key":"value"){case"key":{const u=n(l);a.set(u,a.get(l)),u!==l&&a.delete(l);break}case"value":{a.set(l,n(a.get(l)));break}}}return e};function qs(e,s,n=[]){if(!e)return;if(!Xe(e)){Nt(e,(i,l)=>qs(i,s,[...n,...Mt(l)]));return}const[a,r]=e;r&&Nt(r,(i,l)=>{qs(i,s,[...n,...Mt(l)])}),s(a,n)}function Ro(e,s,n){return qs(s,(a,r)=>{e=Fs(e,r,i=>Oo(i,a,n))}),e}function Uo(e,s){function n(a,r){const i=Go(e,Mt(r));a.map(Mt).forEach(l=>{e=Fs(e,l,()=>i)})}if(Xe(s)){const[a,r]=s;a.forEach(i=>{e=Fs(e,Mt(i),()=>e)}),r&&Nt(r,n)}else Nt(s,n);return e}var Fo=(e,s)=>Rt(e)||Xe(e)||Ut(e)||Ft(e)||Ma(e,s);function qo(e,s,n){const a=n.get(e);a?a.push(s):n.set(e,[s])}function zo(e,s){const n={};let a;return e.forEach(r=>{if(r.length<=1)return;s||(r=r.map(c=>c.map(String)).sort((c,u)=>c.length-u.length));const[i,...l]=r;i.length===0?a=l.map(Is):n[Is(i)]=l.map(Is)}),a?Us(n)?[a]:[a,n]:Us(n)?void 0:n}var Fa=(e,s,n,a,r=[],i=[],l=new Map)=>{const c=ko(e);if(!c){qo(e,r,s);const y=l.get(e);if(y)return a?{transformedValue:null}:y}if(!Fo(e,n)){const y=Cn(e,n),p=y?{transformedValue:y.value,annotations:[y.type]}:{transformedValue:e};return c||l.set(e,p),p}if(os(i,e))return{transformedValue:null};const u=Cn(e,n),d=(u==null?void 0:u.value)??e,h=Xe(d)?[]:{},g={};Nt(d,(y,p)=>{if(p==="__proto__"||p==="constructor"||p==="prototype")throw new Error(`Detected property ${p}. This is a prototype pollution risk, please remove it from your object.`);const w=Fa(y,s,n,a,[...r,p],[...i,e],l);h[p]=w.transformedValue,Xe(w.annotations)?g[p]=w.annotations:Rt(w.annotations)&&Nt(w.annotations,(v,N)=>{g[Ia(p)+"."+N]=v})});const b=Us(g)?{transformedValue:h,annotations:u?[u.type]:void 0}:{transformedValue:h,annotations:u?[u.type,g]:g};return c||l.set(e,b),b};function qa(e){return Object.prototype.toString.call(e).slice(8,-1)}function An(e){return qa(e)==="Array"}function $o(e){if(qa(e)!=="Object")return!1;const s=Object.getPrototypeOf(e);return!!s&&s.constructor===Object&&s===Object.prototype}function Vo(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 zs(e,s={}){if(An(e))return e.map(r=>zs(r,s));if(!$o(e))return e;const n=Object.getOwnPropertyNames(e),a=Object.getOwnPropertySymbols(e);return[...n,...a].reduce((r,i)=>{if(An(s.props)&&!s.props.includes(i))return r;const l=e[i],c=zs(l,s);return Vo(r,i,c,e,s.nonenumerable),r},{})}var pe=class{constructor({dedupe:e=!1}={}){this.classRegistry=new yo,this.symbolRegistry=new Pa(s=>s.description??""),this.customTransformerRegistry=new bo,this.allowedErrorProps=[],this.dedupe=e}serialize(e){const s=new Map,n=Fa(e,s,this,this.dedupe),a={json:n.transformedValue};n.annotations&&(a.meta={...a.meta,values:n.annotations});const r=zo(s,this.dedupe);return r&&(a.meta={...a.meta,referentialEqualities:r}),a}deserialize(e){const{json:s,meta:n}=e;let a=zs(s);return n!=null&&n.values&&(a=Ro(a,n.values,this)),n!=null&&n.referentialEqualities&&(a=Uo(a,n.referentialEqualities)),a}stringify(e){return JSON.stringify(this.serialize(e))}parse(e){return this.deserialize(JSON.parse(e))}registerClass(e,s){this.classRegistry.register(e,s)}registerSymbol(e,s){this.symbolRegistry.register(e,s)}registerCustom(e,s){this.customTransformerRegistry.register({name:s,...e})}allowErrorProps(...e){this.allowedErrorProps.push(...e)}};pe.defaultInstance=new pe;pe.serialize=pe.defaultInstance.serialize.bind(pe.defaultInstance);pe.deserialize=pe.defaultInstance.deserialize.bind(pe.defaultInstance);pe.stringify=pe.defaultInstance.stringify.bind(pe.defaultInstance);pe.parse=pe.defaultInstance.parse.bind(pe.defaultInstance);pe.registerClass=pe.defaultInstance.registerClass.bind(pe.defaultInstance);pe.registerSymbol=pe.defaultInstance.registerSymbol.bind(pe.defaultInstance);pe.registerCustom=pe.defaultInstance.registerCustom.bind(pe.defaultInstance);pe.allowErrorProps=pe.defaultInstance.allowErrorProps.bind(pe.defaultInstance);var za=pe.serialize,Ho=pe.stringify;function Ko(e){return e.state.fetchStatus==="fetching"?"fetching":e.getObserversCount()?e.state.fetchStatus==="paused"?"paused":e.isStale()?"stale":"fresh":"inactive"}function Qo(e,s){return`${e}${s.charAt(0).toUpperCase()+s.slice(1)}`}function Wo({queryState:e,observerCount:s,isStale:n}){return e.fetchStatus==="fetching"?"blue":s?e.fetchStatus==="paused"?"purple":n?"yellow":"green":"gray"}function Yo({status:e,isPaused:s}){return s?"purple":e==="error"?"red":e==="pending"?"yellow":e==="success"?"green":"gray"}function Jo(e){return e==="fresh"?"green":e==="stale"?"yellow":e==="paused"?"purple":e==="inactive"?"gray":"blue"}var Xo=(e,s=!1)=>{const{json:n}=za(e);return JSON.stringify(n,null,s?2:void 0)},rs=e=>e.state.fetchStatus!=="idle"?0:e.getObserversCount()?e.isStale()?2:1:3,Zo=(e,s)=>e.queryHash.localeCompare(s.queryHash),$a=(e,s)=>e.state.dataUpdatedAt<s.state.dataUpdatedAt?1:-1,ec=(e,s)=>rs(e)===rs(s)?$a(e,s):rs(e)>rs(s)?1:-1,tc={status:ec,"query hash":Zo,"last updated":$a},is=e=>e.state.isPaused?0:e.state.status==="error"?2:e.state.status==="pending"?1:3,Va=(e,s)=>e.state.submittedAt<s.state.submittedAt?1:-1,sc=(e,s)=>is(e)===is(s)?Va(e,s):is(e)>is(s)?1:-1,nc={status:sc,"last updated":Va},ac=e=>e*parseFloat(getComputedStyle(document.documentElement).fontSize),rc=()=>{const[e,s]=Se("dark");return ma(()=>{const n=window.matchMedia("(prefers-color-scheme: dark)");s(n.matches?"dark":"light");const a=r=>{s(r.matches?"dark":"light")};n.addEventListener("change",a),Et(()=>n.removeEventListener("change",a))}),e},It=(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,It(a.get(r),i,n)),a}if(e instanceof Set){const a=It(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]=It(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]=It(a[r],i,n),a}return e},_t=(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,_t(n.get(a),r)),n}if(e instanceof Set){const n=_t(Array.from(e),s);return new Set(n)}if(Array.isArray(e)){const n=[...e];if(s.length===1)return n.filter((i,l)=>l.toString()!==s[0]);const[a,...r]=s;return n[a]=_t(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]=_t(n[a],r),n}return e},Ha=(e,s)=>{if(!e||document.querySelector("#_goober")||(s==null?void 0:s.querySelector("#_goober")))return;const a=document.createElement("style"),r=document.createTextNode("");a.appendChild(r),a.id="_goober",a.setAttribute("nonce",e),s?s.appendChild(a):document.head.appendChild(a)},ct,qt,zt,$t,st,Vt,ut,dt,mt,ht,ft,gt,Ht,kn,ic=(kn=class{constructor(e){ge(this,ct);ge(this,qt);ge(this,zt);ge(this,$t);ge(this,st,!1);ge(this,Vt);ge(this,ut);ge(this,dt);ge(this,mt);ge(this,ht);ge(this,ft);ge(this,gt);ge(this,Ht);const{client:s,queryFlavor:n,version:a,onlineManager:r,buttonPosition:i,position:l,initialIsOpen:c,errorTypes:u,styleNonce:d,shadowDOMTarget:h}=e;fe(this,ct,Se(s)),fe(this,zt,n),fe(this,$t,a),fe(this,qt,r),fe(this,Vt,d),fe(this,ut,h),fe(this,dt,Se(i)),fe(this,mt,Se(l)),fe(this,ht,Se(c)),fe(this,ft,Se(u))}setButtonPosition(e){X(this,dt)[1](e)}setPosition(e){X(this,mt)[1](e)}setInitialIsOpen(e){X(this,ht)[1](e)}setErrorTypes(e){X(this,ft)[1](e)}setClient(e){X(this,ct)[1](e)}mount(e){if(X(this,st))throw new Error("Devtools is already mounted");const s=ba(()=>{const n=this,[a]=X(this,dt),[r]=X(this,mt),[i]=X(this,ht),[l]=X(this,ft),[c]=X(this,ct);let u;return X(this,gt)?u=X(this,gt):(u=ja(()=>Promise.resolve().then(()=>require("./HO4MOOFI-BVjj5z_y.cjs"))),fe(this,gt,u)),Ha(X(this,Vt),X(this,ut)),ln(u,on({get queryFlavor(){return X(n,zt)},get version(){return X(n,$t)},get onlineManager(){return X(n,qt)},get shadowDOMTarget(){return X(n,ut)}},{get client(){return c()},get buttonPosition(){return a()},get position(){return r()},get initialIsOpen(){return i()},get errorTypes(){return l()}}))},e);fe(this,st,!0),fe(this,Ht,s)}unmount(){var e;if(!X(this,st))throw new Error("Devtools is not mounted");(e=X(this,Ht))==null||e.call(this),fe(this,st,!1)}},ct=new WeakMap,qt=new WeakMap,zt=new WeakMap,$t=new WeakMap,st=new WeakMap,Vt=new WeakMap,ut=new WeakMap,dt=new WeakMap,mt=new WeakMap,ht=new WeakMap,ft=new WeakMap,gt=new WeakMap,Ht=new WeakMap,kn),xt,Kt,Qt,Wt,nt,Yt,pt,yt,jt,vt,bt,wt,St,Jt,Ln,lc=(Ln=class{constructor(e){ge(this,xt);ge(this,Kt);ge(this,Qt);ge(this,Wt);ge(this,nt,!1);ge(this,Yt);ge(this,pt);ge(this,yt);ge(this,jt);ge(this,vt);ge(this,bt);ge(this,wt);ge(this,St);ge(this,Jt);const{client:s,queryFlavor:n,version:a,onlineManager:r,buttonPosition:i,position:l,initialIsOpen:c,errorTypes:u,styleNonce:d,shadowDOMTarget:h,onClose:g}=e;fe(this,xt,Se(s)),fe(this,Qt,n),fe(this,Wt,a),fe(this,Kt,r),fe(this,Yt,d),fe(this,pt,h),fe(this,yt,Se(i)),fe(this,jt,Se(l)),fe(this,vt,Se(c)),fe(this,bt,Se(u)),fe(this,wt,Se(g))}setButtonPosition(e){X(this,yt)[1](e)}setPosition(e){X(this,jt)[1](e)}setInitialIsOpen(e){X(this,vt)[1](e)}setErrorTypes(e){X(this,bt)[1](e)}setClient(e){X(this,xt)[1](e)}setOnClose(e){X(this,wt)[1](()=>e)}mount(e){if(X(this,nt))throw new Error("Devtools is already mounted");const s=ba(()=>{const n=this,[a]=X(this,yt),[r]=X(this,jt),[i]=X(this,vt),[l]=X(this,bt),[c]=X(this,xt),[u]=X(this,wt);let d;return X(this,St)?d=X(this,St):(d=ja(()=>Promise.resolve().then(()=>require("./HUY7CZI3-DvxfQh-B.cjs"))),fe(this,St,d)),Ha(X(this,Yt),X(this,pt)),ln(d,on({get queryFlavor(){return X(n,Qt)},get version(){return X(n,Wt)},get onlineManager(){return X(n,Kt)},get shadowDOMTarget(){return X(n,pt)}},{get client(){return c()},get buttonPosition(){return a()},get position(){return r()},get initialIsOpen(){return i()},get errorTypes(){return l()},get onClose(){return u()}}))},e);fe(this,nt,!0),fe(this,Jt,s)}unmount(){var e;if(!X(this,nt))throw new Error("Devtools is not mounted");(e=X(this,Jt))==null||e.call(this),fe(this,nt,!1)}},xt=new WeakMap,Kt=new WeakMap,Qt=new WeakMap,Wt=new WeakMap,nt=new WeakMap,Yt=new WeakMap,pt=new WeakMap,yt=new WeakMap,jt=new WeakMap,vt=new WeakMap,bt=new WeakMap,wt=new WeakMap,St=new WeakMap,Jt=new WeakMap,Ln);function oc(e){const s=D.useQueryClient(e.client),n=we.useRef(null),{buttonPosition:a,position:r,initialIsOpen:i,errorTypes:l,styleNonce:c,shadowDOMTarget:u}=e,[d]=we.useState(new ic({client:s,queryFlavor:"React Query",version:"5",onlineManager:D.onlineManager,buttonPosition:a,position:r,initialIsOpen:i,errorTypes:l,styleNonce:c,shadowDOMTarget:u}));return we.useEffect(()=>{d.setClient(s)},[s,d]),we.useEffect(()=>{a&&d.setButtonPosition(a)},[a,d]),we.useEffect(()=>{r&&d.setPosition(r)},[r,d]),we.useEffect(()=>{d.setInitialIsOpen(i||!1)},[i,d]),we.useEffect(()=>{d.setErrorTypes(l||[])},[l,d]),we.useEffect(()=>(n.current&&d.mount(n.current),()=>{d.unmount()}),[d]),t.jsx("div",{className:"tsqd-parent-container",ref:n})}function cc(e){const s=D.useQueryClient(e.client),n=we.useRef(null),{errorTypes:a,styleNonce:r,shadowDOMTarget:i}=e,[l]=we.useState(new lc({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 we.useEffect(()=>{l.setClient(s)},[s,l]),we.useEffect(()=>{l.setOnClose(e.onClose??(()=>{}))},[e.onClose,l]),we.useEffect(()=>{l.setErrorTypes(a||[])},[a,l]),we.useEffect(()=>(n.current&&l.mount(n.current),()=>{l.unmount()}),[l]),t.jsx("div",{style:{height:"500px",...e.style},className:"tsqd-parent-container",ref:n})}var uc=process.env.NODE_ENV!=="development"?function(){return null}:oc;process.env.NODE_ENV;const Ka=()=>t.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center w-screen h-screen bg-white/40",children:t.jsx("div",{className:"flex items-center justify-center bg-white rounded-full size-10",children:t.jsx(E.Loader2,{className:"size-5 animate-spin"})})}),dc=()=>{q.registerChaiFeatureFlag("dynamic-page-selector",{description:"Dynamic page selector"}),q.registerChaiFeatureFlag("realtime-page-lock",{description:"Realtime page lock"})},mc=()=>{const e=re(),s=J();return D.useQuery({queryKey:[Y,L.GET_COLLECTIONS],initialData:[],queryFn:async()=>s(e,{action:L.GET_COLLECTIONS})})},hc=()=>{const{data:e}=Te(),{data:s}=At(),{data:n}=Ze(),a=re(),r=J(),i=f.useMemo(()=>(n==null?void 0:n.fallbackLang)||"en",[n==null?void 0:n.fallbackLang]);return D.useMutation({mutationFn:async({block:l})=>r(a,{action:L.GET_BLOCK_ASYNC_PROPS,data:{block:l,lang:(s==null?void 0:s.lang)||i,pageProps:{slug:s==null?void 0:s.slug,searchParams:{},pageType:s==null?void 0:s.pageType,fallbackLang:i,lastSaved:s.lastSaved,pageId:e.id,primaryPageId:s.primaryPage||e.id,pageBaseSlug:s==null?void 0:s.slug,dynamic:e==null?void 0:e.dynamic,languagePageId:s.id}}})})},Qa=()=>{const e=en();return f.useCallback(({pageId:s})=>{e(s)},[e])},fc=60*5;function gc(){const{user:e,setUser:s,logout:n,isLoggedIn:a,isSessionExpired:r}=Ue(),i=js(),l=f.useRef(null),c=f.useCallback(async()=>{if(!(!m.has(e,"expiresAt")||!m.has(e,"accessToken")||!m.has(e,"refreshToken")))try{const u=await $s(i,{action:"REFRESH_TOKEN",data:{refreshToken:e.refreshToken,accessToken:e.accessToken}});if(!u.ok){n();return}const d=await u.json();m.has(d,"id")&&m.has(d,"email")&&m.has(d,"accessToken")&&m.has(d,"refreshToken")?s(d):n()}catch{n()}},[e,n,s,i]);return f.useEffect(()=>{a&&r&&c()},[r,a,c]),f.useEffect(()=>{if(!a||!m.has(e,"expiresAt")||!m.has(e,"refreshToken")||!m.has(e,"accessToken")){l.current&&(clearInterval(l.current),l.current=null);return}return l.current||(l.current=setInterval(()=>{if(!m.has(e,"expiresAt")||!m.has(e,"refreshToken")||!m.has(e,"accessToken"))return;const u=Math.floor(Date.now()/1e3),d=e.expiresAt-u;d<fc&&d>0&&c()},1e3)),()=>{l.current&&(clearInterval(l.current),l.current=null)}},[a,e==null?void 0:e.expiresAt,e==null?void 0:e.refreshToken,e==null?void 0:e.accessToken,i]),null}const xc=f.lazy(()=>Promise.resolve().then(()=>Lc));dc();sr.loadWebBlocks();q.registerChaiTopBar(Qi);jl();q.registerChaiMediaManager(xc);q.registerChaiSaveToLibrary(Or);const pc=e=>{const s=f.useRef([]),[n]=_e(),a=n.get("page"),{data:r}=Te(),{data:i={role:"",permissions:null}}=aa();Xi(),yr();const{data:l,isFetching:c}=$n(),{blocks:u}=Ji(l),{data:d}=Pe(),{mutateAsync:h}=Mn(),g=Wi(),{onSave:b}=Zi(),{getPartialBlocks:y,getPartialBlockBlocks:p}=el(),{aiContext:w,setAiContext:v}=Vs(),{mutateAsync:N}=Rr(),[C,B]=f.useState(!1),{data:S}=Ze(),P=Ks(),{data:O}=Qs(),{data:z}=mc(),{mutateAsync:$}=hc(),se=Qa();fr(),f.useEffect(()=>{const Q=()=>{document.hidden?B(!0):B(!1)};return window.addEventListener("visibilitychange",Q),()=>window.removeEventListener("visibilitychange",Q)},[]),s.current=u;const H=f.useMemo(()=>{const Q={};return i&&(Q.permissions=m.get(i,"permissions",null),Q.role=m.get(i,"role","user")),Q},[i]),K=f.useCallback(async(Q,ne)=>await N({pageType:Q,query:ne}),[N]),te=f.useMemo(()=>m.get(S,"theme",{})||{},[S]);return t.jsxs(t.Fragment,{children:[c&&t.jsx(Ka,{}),t.jsx(q.ChaiBuilderEditor,{gotoPage:se,collections:z??[],getBlockAsyncProps:$,pageExternalData:O,themePresets:e.themePresets??[],pageId:r==null?void 0:r.id,loading:c,fallbackLang:P,languages:(S==null?void 0:S.languages)||[],brandingOptions:(S==null?void 0:S.theme)||{},translations:e.translations||{},locale:e.locale||"en",htmlDir:e.htmlDir||"ltr",autoSaveSupport:!C&&(e.autoSaveSupport??!0),autoSaveInterval:e.autoSaveInterval??15,onError:e.onError||console.error,getPartialBlockBlocks:p,getPartialBlocks:y,blocks:c?[]:u,theme:m.cloneDeep(te),pageTypes:d,searchPageTypeItems:K,saveAiContextCallback:async Q=>{if(!a)return!0;const ne=s.current,_={_type:"@chai/ai-context",_value:m.isString(Q)?Q:""},U=[...ne,_];return await b({page:a,blocks:U}),v(Q),!0},aiContext:w,askAiCallBack:g,onSave:async({blocks:Q,theme:ne})=>{if(!a)return!0;s.current=Q;const _={_type:"@chai/ai-context",_value:m.isString(w)?w:""},U=[...Q,_];return await b({page:a,blocks:U}),s.current=U,m.isEqual(ne,te)||await h({settings:{theme:ne}}),!0},themePanelComponent:Qr,...H}),t.jsxs("div",{children:[t.jsx(Cr,{}),t.jsx(Ar,{})]})]})},yc=new D.QueryClient({defaultOptions:{queries:{refetchOnWindowFocus:!1,refetchOnReconnect:!1}}}),jc=e=>{gc();const{isLoggedIn:s,isSessionExpired:n}=Ue(),[,a]=On(),[r,i]=f.useState(!1);return f.useEffect(()=>(a(m.pick(e,["apiUrl","usersApiUrl","assetsApiUrl","getPreviewUrl","getLiveUrl","logo","onLogout","realtimeInstance"])),setTimeout(()=>{i(!0)},200),()=>{i(!1),a({})}),[e,a]),r?t.jsxs(D.QueryClientProvider,{client:yc,children:[s?n?t.jsx(Ka,{}):t.jsx(pc,{...e}):t.jsx(al,{}),t.jsx(uc,{}),t.jsx(V.Toaster,{richColors:!0})]}):t.jsx("div",{})},vc=()=>{const e=re(),s=J(),{data:n}=At(),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:L.UPDATE_PAGE_METADATA,data:{id:n.id,metadata:r}})},onSuccess:()=>{a.invalidateQueries({queryKey:[Y,L.GET_BUILDER_PAGE_DATA]}),a.invalidateQueries({queryKey:[Y,L.GET_LANGUAGE_PAGES]})},onError:()=>{console.error("Failed to update metadata")}})},bc=()=>{const e=Xt(),s=D.useQueryClient(),n=J();return D.useMutation({mutationFn:async({file:a,folderId:r,name:i,optimize:l=!0})=>n(e,{action:L.UPLOAD_ASSET,data:{file:a,folderId:r,name:i,optimize:l}}),onSuccess:a=>{if(a!=null&&a.error)throw new Error(a==null?void 0:a.error);s.invalidateQueries({queryKey:[Y,L.GET_ASSETS]}),V.toast.success("Asset uploaded successfully")},onError:()=>{V.toast.error("Failed to upload asset")}})},wc=()=>{const e=Xt(),s=D.useQueryClient(),n=J();return D.useMutation({mutationFn:async a=>n(e,{action:L.DELETE_ASSET,data:{id:a}}),onSuccess:a=>{if(a!=null&&a.error)throw new Error(a==null?void 0:a.error);s.invalidateQueries({queryKey:[Y,L.GET_ASSETS]}),V.toast.success("Asset deleted successfully")},onError:()=>{V.toast.error("Failed to delete asset")}})},Sc=()=>{const e=Xt(),s=D.useQueryClient(),n=J();return D.useMutation({mutationFn:async a=>n(e,{action:L.UPDATE_ASSET,data:a}),onSuccess:a=>{if(a!=null&&a.error)throw new Error(a==null?void 0:a.error);s.invalidateQueries({queryKey:[Y,L.GET_ASSETS]}),V.toast.success("Asset updated successfully")},onError:()=>{V.toast.error("Failed to update asset")}})},Ec=(e={})=>{const s=Xt(),n=J(),{search:a,page:r=1,limit:i=30}=e;return D.useQuery({queryKey:[Y,L.GET_ASSETS,a,r,i],queryFn:async()=>{const l=await n(s,{action:L.GET_ASSETS,data:{search:a,page:r,limit:i}});return l.page=r,l.limit=i,l},staleTime:1e3*60*5,retry:1})},Nc=e=>{const s=Xt(),n=J();return D.useQuery({queryKey:[Y,L.GET_ASSET,e],queryFn:async()=>e?await n(s,{action:L.GET_ASSET,data:{id:e}}):null,staleTime:1e3*60*5,retry:1})};function Cc(e){const s=isNaN(e)?0:typeof e=="number"?e:parseInt(e);return s?s<1024?`${s.toFixed(2)} B`:s<1024*1024?`${(s/1024).toFixed(2)} KB`:`${(s/(1024*1024)).toFixed(2)} MB`:"0 B"}function Tn(e){if(!e)return"N/A";const s=new Date(e);return new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric",hour:"2-digit",minute:"2-digit"}).format(s)}function Pn(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 Ac=({assetId:e,onBack:s,onEdit:n,onSave:a,isSaving:r})=>{var g,b,y;const{data:i,isLoading:l,isError:c}=Nc(e||""),[u,d]=f.useState(""),h=async(p,w)=>{try{await navigator.clipboard.writeText(p),V.toast.success(`${w} copied to clipboard`)}catch(v){V.toast.error(`Failed to copy ${w}`,{description:v==null?void 0:v.message})}};return f.useEffect(()=>{i!=null&&i.description&&d(i.description)},[i]),l?t.jsx("div",{className:"flex-1 flex items-center justify-center",children:t.jsx(E.Loader,{className:"h-8 w-8 animate-spin"})}):c||!(i!=null&&i.id)?t.jsx("div",{className:"flex-1 flex items-center justify-center",children:t.jsxs("div",{className:"text-center max-w-md mx-auto p-6",children:[t.jsx("div",{className:"flex justify-center mb-4",children:t.jsx(E.AlertCircle,{className:"h-12 w-12 text-gray-400"})}),t.jsx("h3",{className:"text-lg font-medium text-gray-900 mb-2",children:"No Asset Found"}),t.jsx("p",{className:"text-sm text-gray-500 mb-6",children:c?"There was an error loading the asset. Please try again later.":"The asset you're looking for doesn't exist or has been removed."}),t.jsxs("div",{className:"flex justify-center gap-4",children:[t.jsx(o.Button,{variant:"outline",onClick:s,children:"Back to Assets"}),c&&t.jsx(o.Button,{variant:"default",onClick:()=>window.location.reload(),children:"Try Again"})]})]})}):t.jsxs("div",{className:"flex-1 flex flex-col gap-y-4 overflow-hidden",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsxs(o.Button,{variant:"outline",size:"sm",onClick:s,disabled:r,children:[t.jsx(E.ChevronLeft,{className:"h-4 w-4"}),"Back to Assets"]}),t.jsxs("div",{className:"flex gap-2",children:[t.jsx(o.Button,{variant:"outline",onClick:s,disabled:r,children:"Cancel"}),t.jsxs(o.Button,{variant:"outline",onClick:()=>h(i.url,"Asset URL"),disabled:r,children:[t.jsx(E.Copy,{className:"h-4 w-4 mr-2"}),"Copy URL"]}),t.jsxs(o.Button,{variant:"default",onClick:()=>n(i),disabled:r,children:[t.jsx(E.Pencil,{className:"h-4 w-4"}),"Edit Image"]})]})]}),t.jsxs("div",{className:"grid grid-cols-2 items-start gap-6 flex-1 overflow-hidden",children:[t.jsx("div",{className:"relative h-[calc(80vh-200px)] w-full flex items-start justify-center",children:t.jsx("img",{src:`${i.url}?v=${((g=i.metadata)==null?void 0:g.updatedAt)||i.createdAt}`,alt:i.name,className:"w-full h-full object-contain rounded-lg max-h-max max-w-max"})}),t.jsxs("div",{className:"space-y-6",children:[t.jsxs("div",{className:"grid gap-3 border rounded-md pt-2 bg-gray-100",children:[t.jsx(o.Label,{className:"w-full text-center",children:"Details"}),t.jsx("div",{className:"grid grid-cols-1 gap-2 text-sm border rounded-md p-2 bg-white",children:[{label:"File Name",value:i.name},{label:"Type",value:i.type,capitalize:!0},{label:"Format",value:((b=i.metadata)==null?void 0:b.format)||i.type,capitalize:!0},{label:"Size",value:Cc(i.size)},{label:"Dimensions",value:`${i.width||0} × ${i.height||0}`},{label:"Created",value:Tn(i.createdAt)},{label:"Updated",value:Tn(((y=i.metadata)==null?void 0:y.updatedAt)||i.createdAt)},{label:"URL",value:i.url,copyable:!0}].map(p=>t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(o.Label,{className:"w-max text-left px-2 w-1/4 font-normal text-gray-700",children:p.label}),":",t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("div",{className:"w-max text-left font-medium text-gray-900"+(p.capitalize?" capitalize":""),children:p.value}),p.copyable&&t.jsx(o.Button,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>h(p.value,p.label),children:t.jsx(E.Link,{className:"h-3 w-3"})})]})]},p.label))})]}),i.usedOn&&i.usedOn.length>0&&t.jsxs("div",{className:"grid gap-3",children:[t.jsx(o.Label,{children:"Used On"}),t.jsx("div",{className:"grid grid-cols-1 gap-2 text-sm border rounded-md p-2",children:i.usedOn.map((p,w)=>t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("div",{className:"w-max text-left font-medium text-gray-900",children:p.name}),t.jsxs("div",{className:"text-gray-500",children:["(",p.slug,")"]})]},w))})]}),t.jsxs("div",{className:"grid gap-3 border rounded-md pt-2 bg-gray-100 relative",children:[t.jsx(o.Label,{className:"w-full text-center",children:"Description"}),t.jsx(o.Textarea,{id:"description",value:u,placeholder:"Enter a description for the asset",onChange:p=>d(p.target.value),rows:3,disabled:r,className:"hover:border-black/40 bg-white"}),t.jsx("div",{className:"flex justify-end items-start absolute top-1.5 right-2",children:t.jsx("button",{type:"button",onClick:()=>a(u),disabled:r||!Pn(u,i),className:`py-0 bg-blue-500 text-white px-3 py-0.5 rounded-md text-sm ${r||!Pn(u,i)?"opacity-50 cursor-not-allowed":""}`,children:r?t.jsxs(t.Fragment,{children:[t.jsx(E.Loader,{className:"h-4 w-4 mr-2 animate-spin"}),"Saving..."]}):"Save"})})]})]})]})]})},Tc=f.lazy(()=>Promise.resolve().then(()=>require("./image-editor-BWLJT1mr.cjs")));function Pc(e){const s=isNaN(e)?0:typeof e=="number"?e:parseInt(e);return s?s<1024?`${s.toFixed(2)} B`:s<1024*1024?`${(s/1024).toFixed(2)} KB`:`${(s/(1024*1024)).toFixed(2)} MB`:"0 B"}const kc=({isUpdatingAsset:e,allowedTypes:s,maxFileSize:n,uploadAsset:a,isUploadingAsset:r,onUploaded:i})=>{const[l,c]=f.useState(()=>{const y=localStorage.getItem("chai_optimize_images");return y!==null?y==="true":!0});f.useEffect(()=>{localStorage.setItem("chai_optimize_images",l.toString())},[l]);const u=e||r,d=f.useCallback(async y=>new Promise((p,w)=>{const v=y[0],N=new FileReader;N.readAsDataURL(v),N.onload=async()=>{a({file:N.result,folderId:void 0,name:v.name,optimize:l},{onSuccess:C=>{i&&i(C),p(C)},onError:C=>{w(C)}})},N.onerror=C=>w(C)}),[a,l,i]),{getRootProps:h,getInputProps:g,isDragActive:b}=tr.useDropzone({onDrop:d,accept:{"image/*":s.includes("image")?[]:[]},maxSize:n*1024*1024,disabled:e||r});return t.jsx("div",{className:`flex flex-col items-center justify-center w-full border-2 hover:border-black/50 border-dashed p-0 rounded-lg border-slate-300 py-2 h-[60px] ${u?"opacity-90 bg-gray-100 pointer-events-none":"hover:border-black/50 bg-gray-100 hover:bg-gray-100"}`,children:t.jsxs("div",{...h(),className:q.mergeClasses("rounded-lg text-center cursor-pointer w-full h-max flex flex-col justify-center",u?"items-start":"items-center",b?"border-primary bg-primary/5":"border-muted-foreground/20"),children:[t.jsx("input",{...g()}),u?t.jsx("div",{className:"flex flex-col items-center px-6",children:t.jsxs("div",{className:"leading-tight flex items-center justify-center gap-2",children:[t.jsx("div",{className:"flex items-center justify-center rounded-full bg-indigo-100 p-2",children:t.jsx(E.Loader,{className:"h-4 w-4 text-indigo-500 animate-spin"})}),t.jsxs("div",{className:"text-left",children:[t.jsx("div",{className:"font-medium",children:e?"Updating file...":"Uploading file..."}),t.jsxs("div",{className:"text-xs text-muted-foreground font-light",children:["Please wait while we ",e?"update":"upload"," ","your file..."]})]})]})}):t.jsxs("div",{className:"flex items-center justify-between w-full px-6",children:[t.jsx("div",{className:"flex flex-col items-center",children:t.jsxs("div",{className:"leading-tight flex items-center justify-between gap-2",children:[t.jsx("div",{className:"flex items-center justify-center rounded-full bg-indigo-100 p-2 border border-indigo-500",children:t.jsx(E.Upload,{className:"h-4 w-4 text-indigo-500"})}),t.jsxs("div",{className:"text-left",children:[t.jsxs("div",{className:"font-medium",children:["Drop your file here or"," ",t.jsx("span",{className:"text-indigo-500 cursor-pointer hover:underline",children:"browse"})]}),t.jsxs("div",{className:"text-xs text-muted-foreground font-light",children:[t.jsxs("span",{className:"",children:["Accepted file types:"," ",t.jsx("span",{className:"capitalize text-indigo-400",children:s.join(", ")})," & "]}),t.jsxs("span",{children:["Max file size:"," ",t.jsxs("span",{className:"capitalize text-indigo-400",children:[n," MB"]})]})]})]})]})}),t.jsxs("div",{className:"text-xs text-muted-foreground flex items-center gap-2",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsxs("span",{className:"text-xs",children:["Optimization:"," ",t.jsx("span",{className:l?"text-indigo-600":"text-gray-400",children:l?"On":"Off"})]}),t.jsx(o.Switch,{checked:l,onCheckedChange:y=>{c(y)},onClick:y=>{y.stopPropagation()},className:"data-[state=checked]:bg-indigo-500"})]}),t.jsx(o.TooltipProvider,{children:t.jsxs(o.Tooltip,{children:[t.jsx(o.TooltipTrigger,{asChild:!0,children:t.jsx("span",{className:`text-amber-500 flex items-center cursor-help ${l?"invisible":""}`,children:t.jsx(E.AlertTriangle,{className:"h-4 w-4 mr-1"})})}),t.jsx(o.TooltipContent,{side:"top",children:t.jsxs("p",{className:"text-white text-xs",children:["Warning: Unoptimized images may affect ",t.jsx("br",{})," performance and page load times"]})})]})})]})]})]})})};function Wa({close:e,onSelect:s,mode:n="image",assetId:a}){const l=f.useMemo(()=>[n],[n]),[c,u]=f.useState(null),[d,h]=f.useState(null),[g,b]=f.useState(null),[y,p]=f.useState({show:!1,file:""}),[w,v]=f.useState(!1),[N,C]=f.useState(a?"details":"grid"),[B,S]=f.useState(""),[P,O]=f.useState(""),[z,$]=f.useState(1),[se]=f.useState(30),[H,K]=f.useState([]);f.useEffect(()=>{a&&(u(a),C("details"))},[a]),f.useEffect(()=>{const I=setTimeout(()=>{S(P),$(1)},300);return()=>clearTimeout(I)},[P]);const{data:te,isLoading:Q}=Ec({search:B.toLowerCase().trim(),page:z,limit:se}),ne=(te==null?void 0:te.assets)||[],_=(te==null?void 0:te.total)||0,U=Math.ceil(_/se),he=z<U,ye=z>1,ce=(ne==null?void 0:ne.length)>0,{mutate:j}=wc(),{mutate:x,isPending:A}=bc(),{mutate:M,isPending:G}=Sc(),T=f.useCallback(I=>{I>=1&&I<=U&&$(I)},[U]),W=f.useCallback(()=>{he&&T(z+1)},[z,he,T]),F=f.useCallback(()=>{ye&&T(z-1)},[z,ye,T]),Z=I=>{O(I.target.value)},de=f.useCallback(I=>{K(le=>m.find(le,{id:I.id})?[]:[I])},[!1]),ve=f.useCallback(()=>{K([])},[]),oe=I=>{(I==null?void 0:I.length)!==0&&(s(m.pick(m.first(I||H),["id","url","width","height","description"])),e())},R=async I=>{h(I)},be=async()=>{d&&(b(d==null?void 0:d.id),await j(d.id,{onSuccess:()=>{b(null),h(null)},onError:()=>{b(null)}}),h(null))},ie=I=>{u(I.id),C("details")},Ne=async(I,le)=>{try{const Ee=localStorage.getItem("chai_optimize_images")!=="false";le?(await x({file:I,folderId:void 0,name:y.name||"",optimize:Ee}),p({show:!1,file:""})):(await M({id:y.id||"",file:I}),p({show:!1,file:""}))}catch(Ee){console.error("Error saving edited image:",Ee)}},De=f.useCallback(I=>{K([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"}),N==="grid"?t.jsxs(t.Fragment,{children:[t.jsx(kc,{maxFileSize:10,allowedTypes:l,uploadAsset:x,isUpdatingAsset:G,isUploadingAsset:A,onUploaded:De}),t.jsxs("div",{className:"border p-2 rounded-lg flex-1 flex flex-col gap-y-3 overflow-hidden relative",children:[t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsxs("div",{className:"relative w-1/2 ",children:[t.jsx(E.Search,{strokeWidth:3,className:`absolute left-2 top-2.5 h-4 w-4 text-muted-foreground ${P.length>0?"text-indigo-800":""}`}),t.jsx(o.Input,{placeholder:"Search assets...",onChange:Z,value:P,className:"pl-8"})]}),H.length>0?t.jsx("div",{className:"flex justify-between items-center",children:t.jsxs("div",{className:"flex items-center gap-2",children:[H.length>0&&t.jsx(t.Fragment,{children:t.jsx(o.Button,{variant:"outline",size:"sm",onClick:()=>ve(),title:"Clear selection",children:"Clear"})}),t.jsx(o.Button,{size:"sm",onClick:()=>oe(H),disabled:H.length===0,children:"Select Asset"})]})}):null]}),t.jsx("div",{className:"flex-1 overflow-y-auto pb-[66px]",children:Q?t.jsxs("div",{className:"columns-1 gap-3 space-y-3 sm:columns-3 md:columns-5",children:[t.jsx("div",{className:"bg-gray-200 h-64 w-full animate-pulse rounded"}),t.jsx("div",{className:"bg-gray-200 h-64 w-full animate-pulse rounded"}),t.jsx("div",{className:"bg-gray-200 h-64 w-full animate-pulse rounded"}),t.jsx("div",{className:"bg-gray-200 h-64 w-full animate-pulse rounded"}),t.jsx("div",{className:"bg-gray-200 h-64 w-full animate-pulse rounded"}),t.jsx("div",{className:"bg-gray-200 h-64 w-full animate-pulse rounded"}),t.jsx("div",{className:"bg-gray-200 h-64 w-full animate-pulse rounded"}),t.jsx("div",{className:"bg-gray-200 h-64 w-full animate-pulse rounded"}),t.jsx("div",{className:"bg-gray-200 h-64 w-full animate-pulse rounded"}),t.jsx("div",{className:"bg-gray-200 h-64 w-full animate-pulse rounded"})]}):!Q&&!ce?t.jsxs("div",{className:"flex flex-col items-center justify-center h-full border rounded-lg",children:[t.jsx("div",{className:"text-muted-foreground",children:t.jsx(E.Archive,{className:"h-9 w-9 text-indigo-500"})}),t.jsx("div",{className:"text-muted-foreground text-lg",children:"No assets found"}),t.jsx("div",{className:"text-muted-foreground text-sm",children:B.length>0?"No assets found for your search: "+B:"Start uploading assets to get started"}),t.jsx("br",{})]}):t.jsx("div",{className:"flex flex-wrap gap-3 p-1",children:ne==null?void 0:ne.map(I=>t.jsxs("div",{className:q.mergeClasses("relative cursor-pointer overflow-hidden transition-all rounded-lg border-2 group max-w-[180px] max-h-[180px] flex flex-col justify-between",H.some(le=>le.id===I.id)?"border-blue-500":"hover:border-black/90",g&&(d==null?void 0:d.id)===I.id?"opacity-50 pointer-events-none":"",g===I.id?"opacity-50 pointer-events-none":""),onClick:()=>de(I),onDoubleClick:()=>oe([I]),children:[t.jsxs("div",{className:"aspect-square relative overflow-hidden",children:[g===I.id?t.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/50",children:t.jsx(E.Loader,{className:"h-8 w-8 animate-spin text-white"})}):null,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] ${H.some(le=>le.id===I.id)?"":"group-hover:blur group-hover:contrast-50"}`}):t.jsxs("div",{className:"flex items-center justify-center h-full",children:[t.jsx(E.Film,{className:"h-12 w-12 text-muted-foreground"}),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:Pc((I==null?void 0:I.size)||0)})})]}),!H.some(le=>le.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(o.TooltipProvider,{children:t.jsxs(o.Tooltip,{children:[t.jsx(o.TooltipTrigger,{asChild:!0,children:t.jsx(o.Button,{variant:"secondary",size:"icon",className:"h-8 w-8 rounded-full",onClick:le=>{le.stopPropagation(),ie(I)},children:t.jsx(E.ImageIcon,{className:"h-4 w-4"})})}),t.jsx(o.TooltipContent,{children:t.jsx("p",{children:"View Details"})})]})}),t.jsx(o.TooltipProvider,{children:t.jsxs(o.Tooltip,{children:[t.jsx(o.TooltipTrigger,{asChild:!0,children:t.jsx(o.Button,{variant:"secondary",size:"icon",className:"h-8 w-8 rounded-full",onClick:le=>{le.stopPropagation(),navigator.clipboard.writeText(I.url),V.toast.success("Asset URL copied to clipboard")},children:t.jsx(E.Copy,{className:"h-4 w-4"})})}),t.jsx(o.TooltipContent,{children:t.jsx("p",{children:"Copy URL"})})]})}),t.jsx(o.TooltipProvider,{children:t.jsxs(o.Tooltip,{children:[t.jsx(o.TooltipTrigger,{asChild:!0,children:t.jsx(o.Button,{variant:"secondary",size:"icon",className:"h-8 w-8 rounded-full",onClick:le=>{le.stopPropagation(),p({id:I.id,show:!0,file:I.url,name:I.name})},children:t.jsx(E.Edit,{className:"h-4 w-4"})})}),t.jsx(o.TooltipContent,{children:t.jsx("p",{children:"Edit Image"})})]})}),t.jsx(o.TooltipProvider,{children:t.jsxs(o.Tooltip,{children:[t.jsx(o.TooltipTrigger,{asChild:!0,children:t.jsx(o.Button,{variant:"destructive",size:"icon",className:"h-8 w-8 rounded-full",onClick:le=>{le.stopPropagation(),R(I)},children:t.jsx(E.Trash2,{className:"h-4 w-4"})})}),t.jsx(o.TooltipContent,{children:t.jsx("p",{children:"Delete Asset"})})]})})]})}),H.some(le=>le.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(E.Check,{className:"w-3 h-3 text-white",strokeWidth:5})})]},I.id))})}),U>1&&t.jsx("div",{className:"absolute bottom-0 left-0 right-0 bg-white border-t p-4",children:t.jsxs("div",{className:"flex items-center justify-center space-x-2",children:[t.jsx(o.Button,{variant:"outline",size:"sm",onClick:F,disabled:!ye,children:"Previous"}),Array.from({length:Math.min(5,U)},(I,le)=>{const Ee=le+1;return t.jsx(o.Button,{variant:z===Ee?"default":"outline",size:"sm",onClick:()=>T(Ee),children:Ee},Ee)}),U>5&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"text-muted-foreground",children:"..."}),t.jsx(o.Button,{variant:z===U?"default":"outline",size:"sm",onClick:()=>T(U),children:U})]}),t.jsx(o.Button,{variant:"outline",size:"sm",onClick:W,disabled:!he,children:"Next"})]})})]})]}):t.jsx(Ac,{assetId:c||a||"",onBack:()=>{C("grid"),u(null)},onEdit:I=>{p({id:I.id,show:!0,file:I.url,name:I.name})},onSave:async I=>{if(c){v(!0);try{const le=ne.find(Ee=>Ee.id===c);le&&await M(m.merge(le,{description:I}))}finally{v(!1)}}},isSaving:w})]}),y.show&&t.jsx(f.Suspense,{fallback:t.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:t.jsx(E.Loader,{className:"h-8 w-8 animate-spin"})}),children:t.jsx(Tc,{imageUrl:y.file,onSave:Ne,onClose:()=>p({show:!1,file:""}),defaultSavedImageName:y.name,isEditing:!!y.id})}),d&&t.jsx(o.Dialog,{open:!!d,onOpenChange:()=>h(null),children:t.jsxs(o.DialogContent,{children:[t.jsxs(o.DialogHeader,{children:[t.jsx(o.DialogTitle,{children:"Delete Asset"}),t.jsxs(o.DialogDescription,{children:['Are you sure you want to delete "',d.name,'"? This action cannot be undone.']})]}),t.jsxs(o.DialogFooter,{className:"gap-2 sm:gap-0",children:[t.jsx(o.Button,{variant:"outline",onClick:()=>h(null),children:"Cancel"}),t.jsx(o.Button,{variant:"destructive",onClick:be,children:"Delete"})]})]})})]})}const Lc=Object.freeze(Object.defineProperty({__proto__:null,default:Wa},Symbol.toStringTag,{value:"Module"})),Ya=({assetId:e,assetUrl:s,onChange:n,className:a="",placeholder:r="Select an image",disabled:i=!1})=>{const[l,c]=f.useState(!1),u=()=>{i||c(!0)},d=()=>{c(!1)},h=b=>{const y=Array.isArray(b)?b[0]:b;y!=null&&y.url&&n(m.pick(y,["url","id"])),c(!1)},g=()=>{n({url:"",id:""})};return t.jsxs("div",{className:`w-full ${a}`,children:[s?t.jsxs("div",{className:"relative border rounded-md overflow-hidden",children:[t.jsx("img",{onClick:u,src:s,alt:"Selected image",className:"w-full h-auto bg-gray-300 object-contain max-h-[100px]"}),t.jsxs("div",{className:"absolute top-2 right-2 flex gap-2",children:[t.jsx(o.Button,{type:"button",variant:"destructive",size:"icon",className:"h-8 w-8 rounded-full bg-white/80 text-red-500 hover:bg-white/90",onClick:g,disabled:i,children:t.jsx(E.Trash2,{className:"h-4 w-4"})}),t.jsx(o.Button,{type:"button",variant:"secondary",size:"icon",className:"h-8 w-8 rounded-full bg-white/80 hover:bg-white/90",onClick:u,disabled:i,children:t.jsx(E.ImageIcon,{className:"h-4 w-4"})})]})]}):t.jsx("div",{className:`flex items-center justify-center border border-dashed rounded-md p-6 cursor-pointer ${i?"opacity-50 cursor-not-allowed":"hover:border-gray-400"}`,onClick:u,children:t.jsxs("div",{className:"flex flex-col items-center gap-2",children:[t.jsx(E.ImageIcon,{className:"h-10 w-10 text-gray-400"}),t.jsx("p",{className:"text-sm text-gray-500",children:r})]})}),t.jsx(o.Dialog,{open:l,onOpenChange:c,children:t.jsxs(o.DialogContent,{className:"w-full max-w-7xl h-fit p-0 overflow-hidden",children:[t.jsxs(o.DialogHeader,{className:"px-4 py-2 border-b hidden",children:[t.jsx(o.DialogTitle,{children:"Select Image"}),t.jsx(o.Button,{type:"button",variant:"ghost",size:"icon",className:"absolute right-4 top-2",onClick:d,children:t.jsx(E.X,{className:"h-4 w-4"})})]}),t.jsx("div",{className:"flex-1 p-4 h-full",children:t.jsx(Wa,{close:d,onSelect:h,mode:"image",assetId:e})})]})})]})},Ic=()=>{const{user:e,logout:s}=Ue(),n=e==null?void 0:e.accessToken;return f.useCallback(async({url:a,method:r="GET",body:i={},headers:l={}})=>{if(!n)throw new Error("No auth token");if(!a)throw new Error("URL is required");try{const c=await fetch(a,{method:r,headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`,...l},body:JSON.stringify(i)});if(c.status===401)return console.log("Session expired",c),await s(),null;if(c.status===400)throw new Error((await c.json()).error);return await c.json()}catch(c){throw console.log("Something went wrong",c),c}},[n,s])};class _c{constructor(s){As(this,"client");As(this,"channel",null);this.client=s}listenEvent(s,n){var a;(a=this.channel)==null||a.on("broadcast",{event:s},({payload:r})=>{n(r)}).subscribe()}async joinPage(s,n){const a=`PAGE:${s}`;return this.channel&&(await this.channel.untrack({userId:n}),await this.channel.unsubscribe()),this.channel=this.client.channel(a,{config:{presence:{key:n}}}),new Promise(r=>{var i;(i=this.channel)==null||i.on("presence",{event:"sync"},()=>{const l=this.getOnlineUsers();l.length>0?l.length===1&&l.includes(n)?r(!0):r(!1):r(!0)}).subscribe(async l=>{var c;l==="SUBSCRIBED"&&await((c=this.channel)==null?void 0:c.track({userId:n,online_at:new Date}))})})}async leavePage(){this.channel&&await this.channel.untrack()}async requestTakeOver(s,n){return new Promise(a=>{var r;(r=this.channel)==null||r.send({type:"broadcast",event:"TAKE_OVER_REQUESTED",payload:{pageId:s,requesterUserId:n,userId:n}}).then(()=>{a()})})}acceptTakeOver(s,n){return new Promise(a=>{var r;(r=this.channel)==null||r.send({type:"broadcast",event:"TAKE_OVER_REQUEST_ACCEPTED",payload:{pageId:s,userId:n}}).then(()=>{this.leavePage(),a()})})}rejectTakeOver(s,n){return new Promise(a=>{var r;(r=this.channel)==null||r.send({type:"broadcast",event:"TAKE_OVER_REQUEST_REJECTED",payload:{pageId:s,userId:n}}).then(()=>{a()})})}getOnlineUsers(){var s;return Object.keys(((s=this.channel)==null?void 0:s.presenceState())||{})}}if(typeof window>"u")throw new Error("@chaibuilder/pages is not available on the server");exports.$TRACK=nn;exports.ChaiBuilderPages=jc;exports.ChaiBuilderPagesRealtime=_c;exports.Dynamic=xo;exports.For=ql;exports.ImagePicker=Ya;exports.Index=zl;exports.LanguageSwitcher=sn;exports.Match=Hl;exports.NestedPathSelector=We;exports.PermissionChecker=Ge;exports.Portal=go;exports.Show=$l;exports.Switch=Vl;exports.addEventListener=Ea;exports.batch=El;exports.className=Sa;exports.clearDelegatedEvents=ao;exports.convertRemToPixels=ac;exports.createComponent=ln;exports.createComputed=da;exports.createContext=kl;exports.createEffect=an;exports.createMemo=Be;exports.createRenderEffect=Je;exports.createRoot=Ye;exports.createSignal=Se;exports.createUniqueId=Fl;exports.delegateEvents=wa;exports.deleteNestedDataByPath=_t;exports.displayValue=Xo;exports.getMutationStatusColor=Yo;exports.getPreferredColorScheme=rc;exports.getQueryStatusColor=Wo;exports.getQueryStatusColorByLabel=Jo;exports.getQueryStatusLabel=Ko;exports.getSidedProp=Qo;exports.insert=ys;exports.mergeProps=on;exports.mutationSortFns=nc;exports.on=Nl;exports.onCleanup=Et;exports.onMount=ma;exports.registerLoginComponent=nl;exports.serialize=za;exports.setAttribute=ps;exports.sortFns=tc;exports.splitProps=ya;exports.spread=Na;exports.stringify=Ho;exports.template=no;exports.untrack=Ae;exports.updateNestedDataByPath=It;exports.use=Ca;exports.useActivePage=At;exports.useBuilderPageData=Qs;exports.useChaiAuth=Ue;exports.useChaiFetch=Ic;exports.useChaiUserInfo=et;exports.useContext=Ll;exports.useCurrentPage=Te;exports.useFallbackLang=Ks;exports.useFetch=J;exports.useGotoPage=Qa;exports.useLanguagePages=Ke;exports.usePageTypes=Pe;exports.useTransition=Pl;exports.useUpdateActivePageMetadata=vc;exports.useUserRoleAndPermissions=aa;exports.useWebsitePages=Zt;exports.useWebsiteSetting=Ze;
|
|
6
|
+
`),te=e.substring(0,O)+K+e.substring(z);s(te),setTimeout(()=>{P.selectionStart=O,P.selectionEnd=O+K.length},0)}}else{const $=e.substring(0,O)+" "+e.substring(z);s($),setTimeout(()=>{P.selectionStart=P.selectionEnd=O+2},0)}}};f.useEffect(()=>{const S=pn(e);if(S.isValid)if(b(null),S.parsed){const P=ml(S.parsed,c);p(P)}else p("");else b(S.error),p("")},[e,c]);const C=()=>{const S=pn(e);if(S.isValid&&S.parsed){const P=dl(S.parsed,S.placeholders);s(P)}},B=()=>{g!=null&&g.position&&w.current&&(w.current.focus(),w.current.setSelectionRange(g.position,g.position+1))};return t.jsx("div",{className:"space-y-2",children:t.jsxs(o.Tabs,{value:d,onValueChange:h,className:"w-full",children:[t.jsxs("div",{className:"mb-2 flex items-center justify-between",children:[t.jsxs(o.TabsList,{className:"grid w-[200px] grid-cols-2",children:[t.jsxs(o.TabsTrigger,{value:"edit",className:"flex items-center gap-1",children:[t.jsx(E.Code,{className:"h-4 w-4"}),t.jsx("span",{children:"Edit"})]}),t.jsxs(o.TabsTrigger,{value:"preview",className:"flex items-center gap-1",disabled:!e.trim()||g!==null,children:[t.jsx(E.Eye,{className:"h-4 w-4"}),t.jsx("span",{children:"Preview"})]})]}),d==="edit"&&!a&&t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(We,{dataType:"value",data:c??{},onSelect:S=>u&&u(S,"jsonLD")}),t.jsx(o.Button,{type:"button",variant:"outline",size:"sm",onClick:C,disabled:!e.trim()||n||g!==null,children:"Format"})]})]}),t.jsxs(o.TabsContent,{value:"edit",className:"mt-0",children:[t.jsx(o.Textarea,{ref:w,id:l,name:l,className:`rounded-md border border-input text-xs ${g?"border-red-500":""}`,onChange:v,onKeyDown:N,value:e,placeholder:r,rows:i,disabled:n,readOnly:a}),g&&t.jsxs(o.Alert,{variant:"destructive",className:"mt-2",children:[t.jsx(E.AlertTriangle,{className:"h-4 w-4"}),t.jsxs(o.AlertDescription,{className:"flex flex-col",children:[t.jsx("span",{className:"font-medium",children:"Invalid JSON"}),t.jsx("span",{className:"text-sm",children:g.message}),g.line&&g.column&&t.jsxs("span",{className:"text-sm",children:["Error at line ",g.line,", column ",g.column]}),t.jsx(o.Button,{type:"button",variant:"link",size:"sm",className:"mt-1 h-auto self-start p-0 text-sm",onClick:B,children:"Show position"})]})]})]}),t.jsxs(o.TabsContent,{value:"preview",className:"mt-0",children:[t.jsx(o.Textarea,{rows:i,value:y,readOnly:!0,className:"cursor-default bg-muted font-mono text-sm"}),t.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"This is how the JSON will look after placeholder substitution."})]})]})})},yn=e=>{if(!e)return!0;try{return JSON.parse(e),!0}catch{return!1}},hl=(e,s)=>{const n=e.selectionStart||0,a=e.selectionEnd||0,r=e.value,i=r.substring(0,n),l=r.substring(a),c=`{{${s}}}`,u=i+""+c+l,d=n+0+c.length;return{value:u,newCursorPos:d}},la=()=>{const{t:e}=q.useTranslation(),[,s]=q.useSidebarActivePanel(),{data:n}=Te(),{data:a}=Qs(),{data:r,isFetching:i}=ol(),l=r==null?void 0:r.seo,c=f.useRef(null),u=n==null?void 0:n.pageType,d=Vn(u),{selectedLang:h,fallbackLang:g}=q.useLanguages(),b=h||g,[y,p]=f.useState(!1),[w,v]=f.useState(!1),[N,C]=f.useState({keyword:"",title:"",description:"",cononicalUrl:"",noIndex:!1,noFollow:"",ogTitle:"",ogDescription:"",ogImage:"",ogImageId:"",searchTitle:"",searchDescription:"",jsonLD:"{}",...l}),B=f.useRef({initial:N,updated:N}),{mutate:S,isPending:P}=Ws(),O=P||y||w,{hasPermission:z}=q.usePermissions(),$=z(je.EDIT_SEO);f.useEffect(()=>{!i&&l&&C({title:"",description:"",cononicalUrl:"",noIndex:!1,noFollow:"",ogTitle:"",ogDescription:"",ogImage:"",searchTitle:"",searchDescription:"",jsonLD:"",...l})},[i,l]);const se=async()=>{if(!(!d||!b))try{p(!0);const _=us(d,b),U={...N,keyword:m.get(_,"seo.keyword",""),title:m.get(_,"seo.title",""),description:m.get(_,"seo.description",""),cononicalUrl:m.get(_,"seo.canonicalUrl",""),noIndex:m.get(_,"seo.noIndex",!1),noFollow:m.get(_,"seo.noFollow",!1),ogTitle:m.get(_,"seo.ogTitle",""),ogDescription:m.get(_,"seo.ogDescription","")};C(U),B.current.updated=U,V.toast.success(e("SEO fields reset to defaults"))}catch(_){V.toast.error(e("Failed to reset SEO fields")),console.error("Reset SEO error:",_)}finally{p(!1)}},H=async()=>{if(!(!d||!b))try{v(!0);const _=us(d,b),U={...N,jsonLD:m.get(_,"seo.jsonLD","")};C(U),B.current.updated=U,V.toast.success(e("JSON-LD reset to default"))}catch(_){V.toast.error(e("Failed to reset JSON-LD")),console.error("Reset JSON-LD error:",_)}finally{v(!1)}},K=async()=>{S({id:r==null?void 0:r.id,seo:N},{onSuccess:()=>{B.current.initial=N,B.current.updated=N,s("outline"),V.toast.success("SEO & JSON-LD updated successfully")}})},te=(_,U)=>{const he=document.getElementById(U);if(he){const{value:ye,newCursorPos:ce}=hl(he,_);c.current={id:U,position:ce},he.tagName.toLowerCase()==="input"?(he.value=ye,C(A=>({...A,[he.name]:ye})),he.focus(),he.setSelectionRange(ce,ce),[0,10,50,100,200].forEach(A=>{setTimeout(()=>{const M=document.getElementById(U);M&&(M.focus(),M.setSelectionRange(ce,ce))},A)})):(C(x=>({...x,[he.name]:ye})),requestAnimationFrame(()=>{const x=document.getElementById(U);x&&(x.focus(),x.setSelectionRange(ce,ce),setTimeout(()=>{const A=document.getElementById(U);A&&(A.focus(),A.setSelectionRange(ce,ce))},50))}))}},Q=_=>{const U={...N,[_.target.name]:_.target.name==="noIndex"||_.target.name==="noFollow"?_.target.checked:_.target.value};C(U),B.current.updated=U},ne=_=>U=>{m.isEmpty(U.fieldValue)||Q({target:{name:_,value:typeof U.fieldValue=="string"?U.fieldValue.replace(/^"(.*)"$/,"$1"):U.fieldValue}}),U.error&&V.toast.error(t.jsxs("div",{children:[t.jsx("h2",{children:"Failed to generate:"}),t.jsx("p",{children:U.error})]}))};return t.jsxs("div",{className:"relative flex h-full flex-col",children:[!$&&t.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center backdrop-blur-sm",children:t.jsx(o.Alert,{variant:"default",className:"w-[80%] max-w-md text-xs",children:t.jsx(o.AlertDescription,{children:e("You don't have permission to edit SEO settings. Contact your administrator for access.")})})}),t.jsxs("div",{className:"no-scrollbar flex-grow overflow-y-auto px-2 pb-20",children:[t.jsxs("div",{className:"mb-4 flex w-full items-center justify-between rounded-md bg-gray-100 p-2 text-left text-sm font-bold",children:[t.jsxs("span",{children:[r==null?void 0:r.name," ",t.jsx("br",{}),t.jsx("span",{className:"text-xs text-gray-500",children:r==null?void 0:r.slug})]}),t.jsx(sn,{variant:"outline",showAdd:!1})]}),t.jsx("form",{className:"space-y-8",children:t.jsxs(o.Tabs,{defaultValue:"seo",className:"w-full",children:[t.jsxs(o.TabsList,{className:"mb-4 grid w-full grid-cols-2",children:[t.jsx(o.TabsTrigger,{value:"seo",children:e("SEO Fields")}),t.jsx(o.TabsTrigger,{value:"jsonld",children:e("JSON-LD")})]}),t.jsx(o.TabsContent,{value:"seo",children:t.jsxs("div",{className:"space-y-4",children:[$&&t.jsx("div",{className:"mb-4 flex justify-end",children:t.jsx(o.Button,{type:"button",variant:"outline",size:"sm",onClick:se,disabled:O||!$||!d,children:e(y?"Resetting...":"Reset to Default")})}),t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(o.Label,{className:"text-xs",htmlFor:"keyword",children:e("Keyword")}),$&&t.jsx(We,{dataType:"value",data:a??{},onSelect:_=>te(_,"keyword")})]}),t.jsx(o.Input,{type:"text",id:"keyword",name:"keyword",value:N.keyword,onChange:Q,disabled:O||!$,placeholder:e("Enter keyword"),readOnly:!$})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(o.Label,{className:"text-xs",htmlFor:"title",children:e("SEO Title")}),t.jsxs("div",{className:"flex items-center justify-end gap-2",children:[t.jsx(kt,{keyword:N.keyword,onComplete:ne("title"),field:"title"}),$&&t.jsx(We,{dataType:"value",data:a??{},onSelect:_=>te(_,"title")})]})]}),t.jsx(o.Input,{type:"text",id:"title",name:"title",value:N.title,onChange:Q,disabled:O||!$,placeholder:e("Enter SEO title"),readOnly:!$})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(o.Label,{className:"text-xs",htmlFor:"description",children:e("SEO Description")}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(kt,{keyword:N.keyword,onComplete:ne("description"),field:"description"}),$&&t.jsx(We,{data:a??{},onSelect:_=>te(_,"description")})]})]}),t.jsx(o.Textarea,{id:"description",name:"description",rows:5,value:N.description,onChange:Q,disabled:O||!$,placeholder:e("Enter SEO description"),readOnly:!$})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(o.Label,{className:"text-xs",htmlFor:"title",children:e("Canonical URL")}),$&&t.jsx(We,{dataType:"value",data:a??{},onSelect:_=>te(_,"canonicalUrl")})]}),t.jsx(o.Input,{type:"text",id:"canonicalUrl",name:"canonicalUrl",value:N.canonicalUrl,onChange:Q,disabled:O||!$,placeholder:e("Enter Canonical URL"),readOnly:!$})]}),t.jsxs("div",{className:"",children:[t.jsxs("div",{className:"flex items-center gap-x-2",children:[t.jsx(o.Input,{type:"checkbox",id:"noIndex",name:"noIndex",checked:N.noIndex,onChange:Q,disabled:O||!$,className:"h-4 w-4"}),t.jsx(o.Label,{className:"pb-1 text-xs",htmlFor:"noIndex",children:e("No Index")})]}),t.jsx("p",{className:"mt-0 text-[10px] font-light leading-4 text-gray-400",children:e("Check this if you don't want search engines to index this page.")})]}),t.jsxs("div",{className:"",children:[t.jsxs("div",{className:"flex items-center gap-x-2",children:[t.jsx(o.Input,{type:"checkbox",id:"noFollow",name:"noFollow",checked:N.noFollow,onChange:Q,disabled:O||!$,className:"h-4 w-4"}),t.jsx(o.Label,{className:"pb-1 text-xs",htmlFor:"noIndex",children:e("No Follow")})]}),t.jsx("p",{className:"text-[10px] font-light leading-4 text-gray-400",children:e("Check this if you don't want search engines to follow links on this page.")})]}),t.jsxs("div",{children:[t.jsx("h3",{className:"mb-4 font-semibold text-slate-700",children:e("Open Graph")}),t.jsxs("div",{className:"space-y-4",children:[t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(o.Label,{className:"text-xs",htmlFor:"ogTitle",children:e("OG Title")}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(kt,{keyword:N.keyword,onComplete:ne("ogTitle"),field:"ogTitle"}),$&&t.jsx(We,{dataType:"value",data:a??{},onSelect:_=>te(_,"ogTitle")})]})]}),t.jsx(o.Input,{type:"text",id:"ogTitle",name:"ogTitle",value:N.ogTitle,onChange:Q,disabled:O||!$,placeholder:e("Enter OG title"),readOnly:!$})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(o.Label,{className:"text-xs",htmlFor:"ogDescription",children:e("OG Description")}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(kt,{keyword:N.keyword,onComplete:ne("ogDescription"),field:"ogDescription"}),$&&t.jsx(We,{dataType:"value",data:a??{},onSelect:_=>te(_,"ogDescription")})]})]}),t.jsx(o.Textarea,{id:"ogDescription",name:"ogDescription",rows:5,value:N.ogDescription,onChange:Q,disabled:O||!$,placeholder:e("Enter OG description"),readOnly:!$})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsx("div",{className:"flex items-center justify-between",children:t.jsx(o.Label,{className:"text-xs",htmlFor:"ogImage",children:e("OG Image")})}),t.jsx(Ja,{assetId:N.ogImageId,assetUrl:N.ogImage,onChange:_=>{C({...N,ogImage:_.url,ogImageId:_.id})},disabled:O||!$,placeholder:e("Select OG image"),className:"mb-2"})]})]})]})]})}),t.jsx(o.TabsContent,{value:"jsonld",children:t.jsxs("div",{className:"space-y-4",children:[$&&t.jsx("div",{className:"mb-4 flex justify-end",children:t.jsx(o.Button,{variant:"outline",size:"sm",type:"button",onClick:H,disabled:O||!$||!d,children:e(w?"Resetting...":"Reset to Default")})}),t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(o.Label,{className:"text-xs",htmlFor:"jsonLD",children:e("JSON-LD")}),t.jsx("div",{className:"flex items-center gap-2",children:t.jsx(kt,{keyword:N.keyword,onComplete:ne("jsonLD"),field:"jsonLD"})})]}),t.jsx("div",{className:"hidden",children:JSON.stringify(a)}),t.jsx(ia,{id:"jsonLD",value:N.jsonLD,onChange:_=>{Q({target:{name:"jsonLD",value:_}})},placeholder:e("Enter JSON-LD"),disabled:O||!$,readOnly:!$,pageData:a||{},rows:12,handleFieldInsert:te})]})]})})]})})]}),$&&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:[yn(N.jsonLD)?t.jsx("div",{}):t.jsx("p",{className:"text-xs text-red-500",children:e("Invalid JSON. Please check.")}),t.jsxs("div",{className:"flex items-center gap-4",children:[t.jsx(o.Button,{onClick:K,disabled:!yn(N==null?void 0:N.jsonLD)||m.isEqual(B.current.initial,N)||O||!$,children:e(P?"Saving...":"Save")}),t.jsx(o.Button,{variant:"link",className:"text-gray-500 hover:text-gray-700",onClick:()=>s("outline"),children:e("Cancel")})]})]})]})};la.displayName="SeoPanel";const oa="seo",fl=({isActive:e,show:s})=>{const{data:n}=Te(),a=Vn(n==null?void 0:n.pageType);return!m.has(a,"hasSlug")||!a.hasSlug?null:t.jsx(o.Button,{size:"sm",className:"my-1",onClick:s,variant:e?"default":"ghost",children:t.jsxs("svg",{className:"h-4 w-4",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 21 21",fill:"currentColor",children:[t.jsx("path",{d:"M9.931 6.818c-1.238 0-2.136.925-2.136 2.2 0 1.279.898 2.207 2.136 2.207.664 0 1.257-.246 1.67-.694a.15.15 0 0 0-.009-.213l-.311-.286a.15.15 0 0 0-.213.009c-.273.297-.677.46-1.137.46-.699 0-1.233-.444-1.375-1.12h3.295a.15.15 0 0 0 .151-.151v-.211c0-1.295-.852-2.2-2.072-2.2m0 .724c.697 0 1.188.422 1.315 1.113h-2.69c.142-.673.676-1.113 1.374-1.113m4.332-.724c-1.246 0-2.15.925-2.15 2.2 0 1.279.904 2.207 2.15 2.207.596 0 1.143-.223 1.538-.628s.612-.965.612-1.579c0-1.275-.904-2.2-2.15-2.2m0 3.683c-.826 0-1.426-.624-1.426-1.483 0-.855.6-1.475 1.426-1.475s1.426.621 1.426 1.476c0 .423-.144.804-.406 1.073-.258.264-.62.41-1.019.41M6.318 8.71c-.665-.206-.902-.335-.902-.645 0-.47.564-.521.806-.521.29 0 .552.07.801.215a.15.15 0 0 0 .206-.055l.212-.366a.15.15 0 0 0-.055-.206 2.27 2.27 0 0 0-1.165-.312c-.915 0-1.53.501-1.53 1.245 0 .899.816 1.152 1.411 1.336.655.203.812.307.804.53-.016.398-.567.429-.735.429-.386 0-.722-.129-.972-.374q-.043-.042-.107-.043a.15.15 0 0 0-.106.045l-.295.302a.15.15 0 0 0 .002.213c.383.374.908.58 1.478.58.859 0 1.432-.441 1.459-1.125.031-.833-.746-1.074-1.313-1.249"}),t.jsx("path",{d:"M20.396 2.049H.604A.604.604 0 0 0 0 2.653v12.7c0 .333.27.604.604.604h6.941c-.266 1.296-.881 1.966-.886 1.971a.604.604 0 0 0 .434 1.024h6.815a.604.604 0 0 0 .434-1.024c-.007-.007-.621-.675-.886-1.971h6.941c.333 0 .604-.27.604-.604V2.652a.604.604 0 0 0-.604-.604m-.604 12.701h-.985v-.17a.604.604 0 0 0-1.208 0v.17h-.63v-.17a.604.604 0 0 0-1.208 0v.17H1.207V3.256h18.585z"})]})})},gl={id:oa,label:"SEO & JSON-LD",panel:la,button:fl,position:"top",width:600,view:"modal"},xl="user-info",pl=()=>{const{user:e,logout:s}=Ue(),n=D.useQueryClient(),a=He("onLogout",m.noop);return e?t.jsxs(o.HoverCard,{children:[t.jsx(o.HoverCardTrigger,{asChild:!0,children:t.jsx(o.Button,{variant:"ghost",className:"text-sm font-medium",children:t.jsx(E.User,{className:"w-4 h-4"})})}),t.jsxs(o.HoverCardContent,{className:"w-auto p-4 space-y-2",children:[t.jsx("div",{className:"text-sm font-medium",children:e.name??e.email}),t.jsx("div",{className:"text-xs text-muted-foreground",children:e.email}),t.jsxs(o.AlertDialog,{children:[t.jsx(o.AlertDialogTrigger,{asChild:!0,children:t.jsx(o.Button,{variant:"outline",size:"sm",className:"w-full",children:"Logout"})}),t.jsxs(o.AlertDialogContent,{children:[t.jsxs(o.AlertDialogHeader,{children:[t.jsx(o.AlertDialogTitle,{children:"Are you sure you want to logout?"}),t.jsx(o.AlertDialogDescription,{children:"You will be redirected to the login page."})]}),t.jsxs(o.AlertDialogFooter,{children:[t.jsx(o.AlertDialogCancel,{children:"Cancel"}),t.jsx(o.AlertDialogAction,{onClick:()=>{s(),n.invalidateQueries({queryKey:[Y]}),m.isFunction(a)&&a()},children:"Logout"})]})]})]})]})]}):null},yl={id:xl,label:"User Info",button:pl,position:"bottom"},jl=()=>{q.registerChaiSidebarPanel(oa,gl),q.registerChaiSidebarPanel(ra,ll),q.registerChaiSidebarPanel("user-info",yl)};var ee={context:void 0,registry:void 0,effects:void 0,done:!1,getContextId(){return jn(this.context.count)},getNextContextId(){return jn(this.context.count++)}};function jn(e){const s=String(e),n=s.length-1;return ee.context.id+(n?String.fromCharCode(96+n):"")+s}function Lt(e){ee.context=e}var vl=(e,s)=>e===s,ds=Symbol("solid-proxy"),ca=typeof Proxy=="function",nn=Symbol("solid-track"),ms={equals:vl},ua=pa,Qe=1,hs=2,da={owned:null,cleanups:null,context:null,owner:null},Ps={},me=null,ks=null,bl=null,xe=null,Le=null,$e=null,ws=0;function Ye(e,s){const n=xe,a=me,r=e.length===0,i=s===void 0?a:s,l=r?da:{owned:null,cleanups:null,context:i?i.context:null,owner:i},c=r?e:()=>e(()=>Ae(()=>Ot(l)));me=l,xe=null;try{return ze(c,!0)}finally{xe=n,me=a}}function Se(e,s){s=s?Object.assign({},ms,s):ms;const n={value:e,observers:null,observerSlots:null,comparator:s.equals||void 0},a=r=>(typeof r=="function"&&(r=r(n.value)),xa(n,r));return[ga.bind(n),a]}function ma(e,s,n){const a=Ss(e,s,!0,Qe);Tt(a)}function Je(e,s,n){const a=Ss(e,s,!1,Qe);Tt(a)}function an(e,s,n){ua=Bl;const a=Ss(e,s,!1,Qe);(!n||!n.render)&&(a.user=!0),$e?$e.push(a):Tt(a)}function Be(e,s,n){n=n?Object.assign({},ms,n):ms;const a=Ss(e,s,!0,0);return a.observers=null,a.observerSlots=null,a.comparator=n.equals||void 0,Tt(a),ga.bind(a)}function wl(e){return e&&typeof e=="object"&&"then"in e}function Sl(e,s,n){let a,r,i;arguments.length===1?(a=!0,r=e,i={}):(a=e,r=s,i={});let l=null,c=Ps,u=null,d=!1,h="initialValue"in i,g=typeof a=="function"&&Be(a);const b=new Set,[y,p]=(i.storage||Se)(i.initialValue),[w,v]=Se(void 0),[N,C]=Se(void 0,{equals:!1}),[B,S]=Se(h?"ready":"unresolved");ee.context&&(u=ee.getNextContextId(),i.ssrLoadFrom==="initial"?c=i.initialValue:ee.load&&ee.has(u)&&(c=ee.load(u)));function P(se,H,K,te){return l===se&&(l=null,te!==void 0&&(h=!0),(se===c||H===c)&&i.onHydrated&&queueMicrotask(()=>i.onHydrated(te,{value:H})),c=Ps,O(H,K)),H}function O(se,H){ze(()=>{H===void 0&&p(()=>se),S(H!==void 0?"errored":h?"ready":"unresolved"),v(H);for(const K of b.keys())K.decrement();b.clear()},!1)}function z(){const se=Il,H=y(),K=w();if(K!==void 0&&!l)throw K;return xe&&xe.user,H}function $(se=!0){if(se!==!1&&d)return;d=!1;const H=g?g():a;if(H==null||H===!1){P(l,Ae(y));return}const K=c!==Ps?c:Ae(()=>r(H,{value:y(),refetching:se}));return wl(K)?(l=K,"value"in K?(K.status==="success"?P(l,K.value,void 0,H):P(l,void 0,Bs(K.value),H),K):(d=!0,queueMicrotask(()=>d=!1),ze(()=>{S(h?"refreshing":"pending"),C()},!1),K.then(te=>P(K,te,void 0,H),te=>P(K,void 0,Bs(te),H)))):(P(l,K,void 0,H),K)}return Object.defineProperties(z,{state:{get:()=>B()},error:{get:()=>w()},loading:{get(){const se=B();return se==="pending"||se==="refreshing"}},latest:{get(){if(!h)return z();const se=w();if(se&&!l)throw se;return y()}}}),g?ma(()=>$(!1)):$(!1),[z,{refetch:$,mutate:p}]}function El(e){return ze(e,!1)}function Ae(e){if(xe===null)return e();const s=xe;xe=null;try{return e()}finally{xe=s}}function Nl(e,s,n){const a=Array.isArray(e);let r,i=n&&n.defer;return l=>{let c;if(a){c=Array(e.length);for(let d=0;d<e.length;d++)c[d]=e[d]()}else c=e();if(i)return i=!1,l;const u=Ae(()=>s(c,r,l));return r=c,u}}function ha(e){an(()=>Ae(e))}function Et(e){return me===null||(me.cleanups===null?me.cleanups=[e]:me.cleanups.push(e)),e}function vn(){return me}function Cl(e,s){const n=me,a=xe;me=e,xe=null;try{return ze(s,!0)}catch(r){rn(r)}finally{me=n,xe=a}}function Al(e){const s=xe,n=me;return Promise.resolve().then(()=>{xe=s,me=n;let a;return ze(e,!1),xe=me=null,a?a.done:void 0})}var[Tl,Bc]=Se(!1);function Pl(){return[Tl,Al]}function kl(e,s){const n=Symbol("context");return{id:n,Provider:Ml(n),defaultValue:e}}function Ll(e){let s;return me&&me.context&&(s=me.context[e.id])!==void 0?s:e.defaultValue}function fa(e){const s=Be(e),n=Be(()=>Ms(s()));return n.toArray=()=>{const a=n();return Array.isArray(a)?a:a!=null?[a]:[]},n}var Il;function ga(){if(this.sources&&this.state)if(this.state===Qe)Tt(this);else{const e=Le;Le=null,ze(()=>gs(this),!1),Le=e}if(xe){const e=this.observers?this.observers.length:0;xe.sources?(xe.sources.push(this),xe.sourceSlots.push(e)):(xe.sources=[this],xe.sourceSlots=[e]),this.observers?(this.observers.push(xe),this.observerSlots.push(xe.sources.length-1)):(this.observers=[xe],this.observerSlots=[xe.sources.length-1])}return this.value}function xa(e,s,n){let a=e.value;return(!e.comparator||!e.comparator(a,s))&&(e.value=s,e.observers&&e.observers.length&&ze(()=>{for(let r=0;r<e.observers.length;r+=1){const i=e.observers[r],l=ks&&ks.running;l&&ks.disposed.has(i),(l?!i.tState:!i.state)&&(i.pure?Le.push(i):$e.push(i),i.observers&&ya(i)),l||(i.state=Qe)}if(Le.length>1e6)throw Le=[],new Error},!1)),s}function Tt(e){if(!e.fn)return;Ot(e);const s=ws;_l(e,e.value,s)}function _l(e,s,n){let a;const r=me,i=xe;xe=me=e;try{a=e.fn(s)}catch(l){return e.pure&&(e.state=Qe,e.owned&&e.owned.forEach(Ot),e.owned=null),e.updatedAt=n+1,rn(l)}finally{xe=i,me=r}(!e.updatedAt||e.updatedAt<=n)&&(e.updatedAt!=null&&"observers"in e?xa(e,a):e.value=a,e.updatedAt=n)}function Ss(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:me,context:me?me.context:null,pure:n};return me===null||me!==da&&(me.owned?me.owned.push(i):me.owned=[i]),i}function fs(e){if(e.state===0)return;if(e.state===hs)return gs(e);if(e.suspense&&Ae(e.suspense.inFallback))return e.suspense.effects.push(e);const s=[e];for(;(e=e.owner)&&(!e.updatedAt||e.updatedAt<ws);)e.state&&s.push(e);for(let n=s.length-1;n>=0;n--)if(e=s[n],e.state===Qe)Tt(e);else if(e.state===hs){const a=Le;Le=null,ze(()=>gs(e,s[0]),!1),Le=a}}function ze(e,s){if(Le)return e();let n=!1;s||(Le=[]),$e?n=!0:$e=[],ws++;try{const a=e();return Dl(n),a}catch(a){n||($e=null),Le=null,rn(a)}}function Dl(e){if(Le&&(pa(Le),Le=null),e)return;const s=$e;$e=null,s.length&&ze(()=>ua(s),!1)}function pa(e){for(let s=0;s<e.length;s++)fs(e[s])}function Bl(e){let s,n=0;for(s=0;s<e.length;s++){const a=e[s];a.user?e[n++]=a:fs(a)}if(ee.context){if(ee.count){ee.effects||(ee.effects=[]),ee.effects.push(...e.slice(0,n));return}Lt()}for(ee.effects&&(ee.done||!ee.count)&&(e=[...ee.effects,...e],n+=ee.effects.length,delete ee.effects),s=0;s<n;s++)fs(e[s])}function gs(e,s){e.state=0;for(let n=0;n<e.sources.length;n+=1){const a=e.sources[n];if(a.sources){const r=a.state;r===Qe?a!==s&&(!a.updatedAt||a.updatedAt<ws)&&fs(a):r===hs&&gs(a,s)}}}function ya(e){for(let s=0;s<e.observers.length;s+=1){const n=e.observers[s];n.state||(n.state=hs,n.pure?Le.push(n):$e.push(n),n.observers&&ya(n))}}function Ot(e){let s;if(e.sources)for(;e.sources.length;){const n=e.sources.pop(),a=e.sourceSlots.pop(),r=n.observers;if(r&&r.length){const i=r.pop(),l=n.observerSlots.pop();a<r.length&&(i.sourceSlots[l]=a,r[a]=i,n.observerSlots[a]=l)}}if(e.tOwned){for(s=e.tOwned.length-1;s>=0;s--)Ot(e.tOwned[s]);delete e.tOwned}if(e.owned){for(s=e.owned.length-1;s>=0;s--)Ot(e.owned[s]);e.owned=null}if(e.cleanups){for(s=e.cleanups.length-1;s>=0;s--)e.cleanups[s]();e.cleanups=null}e.state=0}function Bs(e){return e instanceof Error?e:new Error(typeof e=="string"?e:"Unknown error",{cause:e})}function rn(e,s=me){throw Bs(e)}function Ms(e){if(typeof e=="function"&&!e.length)return Ms(e());if(Array.isArray(e)){const s=[];for(let n=0;n<e.length;n++){const a=Ms(e[n]);Array.isArray(a)?s.push.apply(s,a):s.push(a)}return s}return e}function Ml(e,s){return function(a){let r;return Je(()=>r=Ae(()=>(me.context={...me.context,[e]:a.value},fa(()=>a.children))),void 0),r}}var Os=Symbol("fallback");function xs(e){for(let s=0;s<e.length;s++)e[s]()}function Ol(e,s,n={}){let a=[],r=[],i=[],l=0,c=s.length>1?[]:null;return Et(()=>xs(i)),()=>{let u=e()||[],d=u.length,h,g;return u[nn],Ae(()=>{let y,p,w,v,N,C,B,S,P;if(d===0)l!==0&&(xs(i),i=[],a=[],r=[],l=0,c&&(c=[])),n.fallback&&(a=[Os],r[0]=Ye(O=>(i[0]=O,n.fallback())),l=1);else if(l===0){for(r=new Array(d),g=0;g<d;g++)a[g]=u[g],r[g]=Ye(b);l=d}else{for(w=new Array(d),v=new Array(d),c&&(N=new Array(d)),C=0,B=Math.min(l,d);C<B&&a[C]===u[C];C++);for(B=l-1,S=d-1;B>=C&&S>=C&&a[B]===u[S];B--,S--)w[S]=r[B],v[S]=i[B],c&&(N[S]=c[B]);for(y=new Map,p=new Array(S+1),g=S;g>=C;g--)P=u[g],h=y.get(P),p[g]=h===void 0?-1:h,y.set(P,g);for(h=C;h<=B;h++)P=a[h],g=y.get(P),g!==void 0&&g!==-1?(w[g]=r[h],v[g]=i[h],c&&(N[g]=c[h]),g=p[g],y.set(P,g)):i[h]();for(g=C;g<d;g++)g in w?(r[g]=w[g],i[g]=v[g],c&&(c[g]=N[g],c[g](g))):r[g]=Ye(b);r=r.slice(0,l=d),a=u.slice(0)}return r});function b(y){if(i[g]=y,c){const[p,w]=Se(g);return c[g]=w,s(u[g],p)}return s(u[g])}}}function Gl(e,s,n={}){let a=[],r=[],i=[],l=[],c=0,u;return Et(()=>xs(i)),()=>{const d=e()||[],h=d.length;return d[nn],Ae(()=>{if(h===0)return c!==0&&(xs(i),i=[],a=[],r=[],c=0,l=[]),n.fallback&&(a=[Os],r[0]=Ye(b=>(i[0]=b,n.fallback())),c=1),r;for(a[0]===Os&&(i[0](),i=[],a=[],r=[],c=0),u=0;u<h;u++)u<a.length&&a[u]!==d[u]?l[u](()=>d[u]):u>=a.length&&(r[u]=Ye(g));for(;u<a.length;u++)i[u]();return c=l.length=i.length=h,a=d.slice(0),r=r.slice(0,c)});function g(b){i[u]=b;const[y,p]=Se(d[u]);return l[u]=p,s(y,u)}}}function ln(e,s){return Ae(()=>e(s||{}))}function as(){return!0}var Gs={get(e,s,n){return s===ds?n:e.get(s)},has(e,s){return s===ds?!0:e.has(s)},set:as,deleteProperty:as,getOwnPropertyDescriptor(e,s){return{configurable:!0,enumerable:!0,get(){return e.get(s)},set:as,deleteProperty:as}},ownKeys(e){return e.keys()}};function Ls(e){return(e=typeof e=="function"?e():e)?e:{}}function Rl(){for(let e=0,s=this.length;e<s;++e){const n=this[e]();if(n!==void 0)return n}}function on(...e){let s=!1;for(let l=0;l<e.length;l++){const c=e[l];s=s||!!c&&ds in c,e[l]=typeof c=="function"?(s=!0,Be(c)):c}if(ca&&s)return new Proxy({get(l){for(let c=e.length-1;c>=0;c--){const u=Ls(e[c])[l];if(u!==void 0)return u}},has(l){for(let c=e.length-1;c>=0;c--)if(l in Ls(e[c]))return!0;return!1},keys(){const l=[];for(let c=0;c<e.length;c++)l.push(...Object.keys(Ls(e[c])));return[...new Set(l)]}},Gs);const n={},a=Object.create(null);for(let l=e.length-1;l>=0;l--){const c=e[l];if(!c)continue;const u=Object.getOwnPropertyNames(c);for(let d=u.length-1;d>=0;d--){const h=u[d];if(h==="__proto__"||h==="constructor")continue;const g=Object.getOwnPropertyDescriptor(c,h);if(!a[h])a[h]=g.get?{enumerable:!0,configurable:!0,get:Rl.bind(n[h]=[g.get.bind(c)])}:g.value!==void 0?g:void 0;else{const b=n[h];b&&(g.get?b.push(g.get.bind(c)):g.value!==void 0&&b.push(()=>g.value))}}}const r={},i=Object.keys(a);for(let l=i.length-1;l>=0;l--){const c=i[l],u=a[c];u&&u.get?Object.defineProperty(r,c,u):r[c]=u?u.value:void 0}return r}function ja(e,...s){if(ca&&ds in e){const r=new Set(s.length>1?s.flat():s[0]),i=s.map(l=>new Proxy({get(c){return l.includes(c)?e[c]:void 0},has(c){return l.includes(c)&&c in e},keys(){return l.filter(c=>c in e)}},Gs));return i.push(new Proxy({get(l){return r.has(l)?void 0:e[l]},has(l){return r.has(l)?!1:l in e},keys(){return Object.keys(e).filter(l=>!r.has(l))}},Gs)),i}const n={},a=s.map(()=>({}));for(const r of Object.getOwnPropertyNames(e)){const i=Object.getOwnPropertyDescriptor(e,r),l=!i.get&&!i.set&&i.enumerable&&i.writable&&i.configurable;let c=!1,u=0;for(const d of s)d.includes(r)&&(c=!0,l?a[u][r]=i.value:Object.defineProperty(a[u],r,i)),++u;c||(l?n[r]=i.value:Object.defineProperty(n,r,i))}return[...a,n]}function va(e){let s,n;const a=r=>{const i=ee.context;if(i){const[c,u]=Se();ee.count||(ee.count=0),ee.count++,(n||(n=e())).then(d=>{!ee.done&&Lt(i),ee.count--,u(()=>d.default),Lt()}),s=c}else if(!s){const[c]=Sl(()=>(n||(n=e())).then(u=>u.default));s=c}let l;return Be(()=>(l=s())?Ae(()=>{if(!i||ee.done)return l(r);const c=ee.context;Lt(i);const u=l(r);return Lt(c),u}):"")};return a.preload=()=>n||((n=e()).then(r=>s=()=>r.default),n),a}var Ul=0;function Fl(){return ee.context?ee.getNextContextId():`cl-${Ul++}`}var ba=e=>`Stale read from <${e}>.`;function ql(e){const s="fallback"in e&&{fallback:()=>e.fallback};return Be(Ol(()=>e.each,e.children,s||void 0))}function zl(e){const s="fallback"in e&&{fallback:()=>e.fallback};return Be(Gl(()=>e.each,e.children,s||void 0))}function $l(e){const s=e.keyed,n=Be(()=>e.when,void 0,{equals:(a,r)=>s?a===r:!a==!r});return Be(()=>{const a=n();if(a){const r=e.children;return typeof r=="function"&&r.length>0?Ae(()=>r(s?a:()=>{if(!Ae(n))throw ba("Show");return e.when})):r}return e.fallback},void 0,void 0)}function Vl(e){let s=!1;const n=(i,l)=>(s?i[1]===l[1]:!i[1]==!l[1])&&i[2]===l[2],a=fa(()=>e.children),r=Be(()=>{let i=a();Array.isArray(i)||(i=[i]);for(let l=0;l<i.length;l++){const c=i[l].when;if(c)return s=!!i[l].keyed,[l,c,i[l]]}return[-1]},void 0,{equals:n});return Be(()=>{const[i,l,c]=r();if(i<0)return e.fallback;const u=c.children;return typeof u=="function"&&u.length>0?Ae(()=>u(s?l:()=>{if(Ae(r)[0]!==i)throw ba("Match");return c.when})):u},void 0,void 0)}function Hl(e){return e}var Kl=["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"],Ql=new Set(["className","value","readOnly","formNoValidate","isMap","noModule","playsInline",...Kl]),Wl=new Set(["innerHTML","textContent","innerText","children"]),Yl=Object.assign(Object.create(null),{className:"class",htmlFor:"for"}),Jl=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 Xl(e,s){const n=Jl[e];return typeof n=="object"?n[s]?n.$:void 0:n}var Zl=new Set(["beforeinput","click","dblclick","contextmenu","focusin","focusout","input","keydown","keyup","mousedown","mousemove","mouseout","mouseover","mouseup","pointerdown","pointermove","pointerout","pointerover","pointerup","touchend","touchmove","touchstart"]),eo=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"]),to={xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace"};function so(e,s,n){let a=n.length,r=s.length,i=a,l=0,c=0,u=s[r-1].nextSibling,d=null;for(;l<r||c<i;){if(s[l]===n[c]){l++,c++;continue}for(;s[r-1]===n[i-1];)r--,i--;if(r===l){const h=i<a?c?n[c-1].nextSibling:n[i-c]:u;for(;c<i;)e.insertBefore(n[c++],h)}else if(i===c)for(;l<r;)(!d||!d.has(s[l]))&&s[l].remove(),l++;else if(s[l]===n[i-1]&&n[c]===s[r-1]){const h=s[--r].nextSibling;e.insertBefore(n[c++],s[l++].nextSibling),e.insertBefore(n[--i],h),s[r]=n[i]}else{if(!d){d=new Map;let g=c;for(;g<i;)d.set(n[g],g++)}const h=d.get(s[l]);if(h!=null)if(c<h&&h<i){let g=l,b=1,y;for(;++g<r&&g<i&&!((y=d.get(s[g]))==null||y!==h+b);)b++;if(b>h-c){const p=s[l];for(;c<h;)e.insertBefore(n[c++],p)}else e.replaceChild(n[c++],s[l++])}else l++;else s[l++].remove()}}}var Bt="_$DX_DELEGATE";function wa(e,s,n,a={}){let r;return Ye(i=>{r=i,s===document?e():ys(s,e(),s.firstChild?null:void 0,n)},a.owner),()=>{r(),s.textContent=""}}function no(e,s,n){let a;const r=()=>{const l=document.createElement("template");return l.innerHTML=e,l.content.firstChild},i=()=>(a||(a=r())).cloneNode(!0);return i.cloneNode=i,i}function Sa(e,s=window.document){const n=s[Bt]||(s[Bt]=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,Ta))}}function ao(e=window.document){if(e[Bt]){for(let s of e[Bt].keys())e.removeEventListener(s,Ta);delete e[Bt]}}function ps(e,s,n){at(e)||(n==null?e.removeAttribute(s):e.setAttribute(s,n))}function ro(e,s,n,a){at(e)||(a==null?e.removeAttributeNS(s,n):e.setAttributeNS(s,n,a))}function io(e,s,n){at(e)||(n?e.setAttribute(s,""):e.removeAttribute(s))}function Ea(e,s){at(e)||(s==null?e.removeAttribute("class"):e.className=s)}function Na(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 lo(e,s,n={}){const a=Object.keys(s||{}),r=Object.keys(n);let i,l;for(i=0,l=r.length;i<l;i++){const c=r[i];!c||c==="undefined"||s[c]||(bn(e,c,!1),delete n[c])}for(i=0,l=a.length;i<l;i++){const c=a[i],u=!!s[c];!c||c==="undefined"||n[c]===u||!u||(bn(e,c,!0),n[c]=u)}return n}function oo(e,s,n){if(!s)return n?ps(e,"style"):s;const a=e.style;if(typeof s=="string")return a.cssText=s;typeof n=="string"&&(a.cssText=n=void 0),n||(n={}),s||(s={});let r,i;for(i in n)s[i]==null&&a.removeProperty(i),delete n[i];for(i in s)r=s[i],r!==n[i]&&(a.setProperty(i,r),n[i]=r);return n}function Ca(e,s={},n,a){const r={};return a||Je(()=>r.children=Gt(e,s.children,r.children)),Je(()=>typeof s.ref=="function"&&Aa(s.ref,e)),Je(()=>co(e,s,n,!0,r,!0)),r}function Aa(e,s,n){return Ae(()=>e(s,n))}function ys(e,s,n,a){if(n!==void 0&&!a&&(a=[]),typeof s!="function")return Gt(e,s,a,n);Je(r=>Gt(e,s(),r,n),a)}function co(e,s,n,a,r={},i=!1){s||(s={});for(const l in r)if(!(l in s)){if(l==="children")continue;r[l]=wn(e,l,null,r[l],n,i,s)}for(const l in s){if(l==="children")continue;const c=s[l];r[l]=wn(e,l,c,r[l],n,i,s)}}function uo(e){let s,n;return!at()||!(s=ee.registry.get(n=ho()))?e():(ee.completed&&ee.completed.add(s),ee.registry.delete(n),s)}function at(e){return!!ee.context&&!ee.done&&(!e||e.isConnected)}function mo(e){return e.toLowerCase().replace(/-([a-z])/g,(s,n)=>n.toUpperCase())}function bn(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 wn(e,s,n,a,r,i,l){let c,u,d,h,g;if(s==="style")return oo(e,n,a);if(s==="classList")return lo(e,n,a);if(n===a)return a;if(s==="ref")i||n(e);else if(s.slice(0,3)==="on:"){const b=s.slice(3);a&&e.removeEventListener(b,a,typeof a!="function"&&a),n&&e.addEventListener(b,n,typeof n!="function"&&n)}else if(s.slice(0,10)==="oncapture:"){const b=s.slice(10);a&&e.removeEventListener(b,a,!0),n&&e.addEventListener(b,n,!0)}else if(s.slice(0,2)==="on"){const b=s.slice(2).toLowerCase(),y=Zl.has(b);if(!y&&a){const p=Array.isArray(a)?a[0]:a;e.removeEventListener(b,p)}(y||n)&&(Na(e,b,n,y),y&&Sa([b]))}else if(s.slice(0,5)==="attr:")ps(e,s.slice(5),n);else if(s.slice(0,5)==="bool:")io(e,s.slice(5),n);else if((g=s.slice(0,5)==="prop:")||(d=Wl.has(s))||!r&&((h=Xl(s,e.tagName))||(u=Ql.has(s)))||(c=e.nodeName.includes("-")||"is"in l)){if(g)s=s.slice(5),u=!0;else if(at(e))return n;s==="class"||s==="className"?Ea(e,n):c&&!u&&!d?e[mo(s)]=n:e[h||s]=n}else{const b=r&&s.indexOf(":")>-1&&to[s.split(":")[0]];b?ro(e,b,s,n):ps(e,Yl[s]||s,n)}return n}function Ta(e){if(ee.registry&&ee.events&&ee.events.find(([u,d])=>d===e))return;let s=e.target;const n=`$$${e.type}`,a=e.target,r=e.currentTarget,i=u=>Object.defineProperty(e,"target",{configurable:!0,value:u}),l=()=>{const u=s[n];if(u&&!s.disabled){const d=s[`${n}Data`];if(d!==void 0?u.call(s,d,e):u.call(s,e),e.cancelBubble)return}return s.host&&typeof s.host!="string"&&!s.host._$host&&s.contains(e.target)&&i(s.host),!0},c=()=>{for(;l()&&(s=s._$host||s.parentNode||s.host););};if(Object.defineProperty(e,"currentTarget",{configurable:!0,get(){return s||document}}),ee.registry&&!ee.done&&(ee.done=_$HY.done=!0),e.composedPath){const u=e.composedPath();i(u[0]);for(let d=0;d<u.length-2&&(s=u[d],!!l());d++){if(s._$host){s=s._$host,c();break}if(s.parentNode===r)break}}else c();i(a)}function Gt(e,s,n,a,r){const i=at(e);if(i){!n&&(n=[...e.childNodes]);let u=[];for(let d=0;d<n.length;d++){const h=n[d];h.nodeType===8&&h.data.slice(0,2)==="!$"?h.remove():u.push(h)}n=u}for(;typeof n=="function";)n=n();if(s===n)return n;const l=typeof s,c=a!==void 0;if(e=c&&n[0]&&n[0].parentNode||e,l==="string"||l==="number"){if(i||l==="number"&&(s=s.toString(),s===n))return n;if(c){let u=n[0];u&&u.nodeType===3?u.data!==s&&(u.data=s):u=document.createTextNode(s),n=lt(e,n,a,u)}else n!==""&&typeof n=="string"?n=e.firstChild.data=s:n=e.textContent=s}else if(s==null||l==="boolean"){if(i)return n;n=lt(e,n,a)}else{if(l==="function")return Je(()=>{let u=s();for(;typeof u=="function";)u=u();n=Gt(e,u,n,a)}),()=>n;if(Array.isArray(s)){const u=[],d=n&&Array.isArray(n);if(Rs(u,s,n,r))return Je(()=>n=Gt(e,u,n,a,!0)),()=>n;if(i){if(!u.length)return n;if(a===void 0)return n=[...e.childNodes];let h=u[0];if(h.parentNode!==e)return n;const g=[h];for(;(h=h.nextSibling)!==a;)g.push(h);return n=g}if(u.length===0){if(n=lt(e,n,a),c)return n}else d?n.length===0?Sn(e,u,a):so(e,n,u):(n&<(e),Sn(e,u));n=u}else if(s.nodeType){if(i&&s.parentNode)return n=c?[s]:s;if(Array.isArray(n)){if(c)return n=lt(e,n,a,s);lt(e,n,null,s)}else n==null||n===""||!e.firstChild?e.appendChild(s):e.replaceChild(s,e.firstChild);n=s}}return n}function Rs(e,s,n,a){let r=!1;for(let i=0,l=s.length;i<l;i++){let c=s[i],u=n&&n[e.length],d;if(!(c==null||c===!0||c===!1))if((d=typeof c)=="object"&&c.nodeType)e.push(c);else if(Array.isArray(c))r=Rs(e,c,u)||r;else if(d==="function")if(a){for(;typeof c=="function";)c=c();r=Rs(e,Array.isArray(c)?c:[c],Array.isArray(u)?u:[u])||r}else e.push(c),r=!0;else{const h=String(c);u&&u.nodeType===3&&u.data===h?e.push(u):e.push(document.createTextNode(h))}}return r}function Sn(e,s,n=null){for(let a=0,r=s.length;a<r;a++)e.insertBefore(s[a],n)}function lt(e,s,n,a){if(n===void 0)return e.textContent="";const r=a||document.createTextNode("");if(s.length){let i=!1;for(let l=s.length-1;l>=0;l--){const c=s[l];if(r!==c){const u=c.parentNode===e;!i&&!l?u?e.replaceChild(r,c):e.insertBefore(r,n):u&&c.remove()}else i=!0}}else e.insertBefore(r,n);return[r]}function ho(){return ee.getNextContextId()}var fo="http://www.w3.org/2000/svg";function Pa(e,s=!1){return s?document.createElementNS(fo,e):document.createElement(e)}function go(e){const{useShadow:s}=e,n=document.createTextNode(""),a=()=>e.mount||document.body,r=vn();let i,l=!!ee.context;return an(()=>{l&&(vn().user=l=!1),i||(i=Cl(r,()=>Be(()=>e.children)));const c=a();if(c instanceof HTMLHeadElement){const[u,d]=Se(!1),h=()=>d(!0);Ye(g=>ys(c,()=>u()?g():i(),null)),Et(h)}else{const u=Pa(e.isSVG?"g":"div",e.isSVG),d=s&&u.attachShadow?u.attachShadow({mode:"open"}):u;Object.defineProperty(u,"_$host",{get(){return n.parentNode},configurable:!0}),ys(d,i),c.appendChild(u),e.ref&&e.ref(u),Et(()=>c.removeChild(u))}},void 0,{render:!l}),n}function xo(e){const[s,n]=ja(e,["component"]),a=Be(()=>s.component);return Be(()=>{const r=a();switch(typeof r){case"function":return Ae(()=>r(n));case"string":const i=eo.has(r),l=ee.context?uo():Pa(r,i);return Ca(l,n,i),l}})}var po=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()}},ka=class{constructor(e){this.generateIdentifier=e,this.kv=new po}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)}},yo=class extends ka{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 jo(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 vo(e,s){const n=jo(e);if("find"in n)return n.find(s);const a=n;for(let r=0;r<a.length;r++){const i=a[r];if(s(i))return i}}function Nt(e,s){Object.entries(e).forEach(([n,a])=>s(a,n))}function os(e,s){return e.indexOf(s)!==-1}function En(e,s){for(let n=0;n<e.length;n++){const a=e[n];if(s(a))return a}}var bo=class{constructor(){this.transfomers={}}register(e){this.transfomers[e.name]=e}findApplicable(e){return vo(this.transfomers,s=>s.isApplicable(e))}findByName(e){return this.transfomers[e]}},wo=e=>Object.prototype.toString.call(e).slice(8,-1),La=e=>typeof e>"u",So=e=>e===null,Rt=e=>typeof e!="object"||e===null||e===Object.prototype?!1:Object.getPrototypeOf(e)===null?!0:Object.getPrototypeOf(e)===Object.prototype,Us=e=>Rt(e)&&Object.keys(e).length===0,Xe=e=>Array.isArray(e),Eo=e=>typeof e=="string",No=e=>typeof e=="number"&&!isNaN(e),Co=e=>typeof e=="boolean",Ao=e=>e instanceof RegExp,Ut=e=>e instanceof Map,Ft=e=>e instanceof Set,Ia=e=>wo(e)==="Symbol",To=e=>e instanceof Date&&!isNaN(e.valueOf()),Po=e=>e instanceof Error,Nn=e=>typeof e=="number"&&isNaN(e),ko=e=>Co(e)||So(e)||La(e)||No(e)||Eo(e)||Ia(e),Lo=e=>typeof e=="bigint",Io=e=>e===1/0||e===-1/0,_o=e=>ArrayBuffer.isView(e)&&!(e instanceof DataView),Do=e=>e instanceof URL,_a=e=>e.replace(/\./g,"\\."),Is=e=>e.map(String).map(_a).join("."),Mt=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 qe(e,s,n,a){return{isApplicable:e,annotation:s,transform:n,untransform:a}}var Da=[qe(La,"undefined",()=>null,()=>{}),qe(Lo,"bigint",e=>e.toString(),e=>typeof BigInt<"u"?BigInt(e):e),qe(To,"Date",e=>e.toISOString(),e=>new Date(e)),qe(Po,"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}),qe(Ao,"regexp",e=>""+e,e=>{const s=e.slice(1,e.lastIndexOf("/")),n=e.slice(e.lastIndexOf("/")+1);return new RegExp(s,n)}),qe(Ft,"set",e=>[...e.values()],e=>new Set(e)),qe(Ut,"map",e=>[...e.entries()],e=>new Map(e)),qe(e=>Nn(e)||Io(e),"number",e=>Nn(e)?"NaN":e>0?"Infinity":"-Infinity",Number),qe(e=>e===0&&1/e===-1/0,"number",()=>"-0",Number),qe(Do,"URL",e=>e.toString(),e=>new URL(e))];function Es(e,s,n,a){return{isApplicable:e,annotation:s,transform:n,untransform:a}}var Ba=Es((e,s)=>Ia(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}),Bo=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,Uint8ClampedArray].reduce((e,s)=>(e[s.name]=s,e),{}),Ma=Es(_o,e=>["typed-array",e.constructor.name],e=>[...e],(e,s)=>{const n=Bo[s[1]];if(!n)throw new Error("Trying to deserialize unknown typed array");return new n(e)});function Oa(e,s){return e!=null&&e.constructor?!!s.classRegistry.getIdentifier(e.constructor):!1}var Ga=Es(Oa,(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)}),Ra=Es((e,s)=>!!s.customTransformerRegistry.findApplicable(e),(e,s)=>["custom",s.customTransformerRegistry.findApplicable(e).name],(e,s)=>s.customTransformerRegistry.findApplicable(e).serialize(e),(e,s,n)=>{const a=n.customTransformerRegistry.findByName(s[1]);if(!a)throw new Error("Trying to deserialize unknown custom value");return a.deserialize(e)}),Mo=[Ga,Ba,Ra,Ma],Cn=(e,s)=>{const n=En(Mo,r=>r.isApplicable(e,s));if(n)return{value:n.transform(e,s),type:n.annotation(e,s)};const a=En(Da,r=>r.isApplicable(e,s));if(a)return{value:a.transform(e,s),type:a.annotation}},Ua={};Da.forEach(e=>{Ua[e.annotation]=e});var Oo=(e,s,n)=>{if(Xe(s))switch(s[0]){case"symbol":return Ba.untransform(e,s,n);case"class":return Ga.untransform(e,s,n);case"custom":return Ra.untransform(e,s,n);case"typed-array":return Ma.untransform(e,s,n);default:throw new Error("Unknown transformation: "+s)}else{const a=Ua[s];if(!a)throw new Error("Unknown transformation: "+s);return a.untransform(e,n)}},ot=(e,s)=>{const n=e.keys();for(;s>0;)n.next(),s--;return n.next().value};function Fa(e){if(os(e,"__proto__"))throw new Error("__proto__ is not allowed as a property");if(os(e,"prototype"))throw new Error("prototype is not allowed as a property");if(os(e,"constructor"))throw new Error("constructor is not allowed as a property")}var Go=(e,s)=>{Fa(s);for(let n=0;n<s.length;n++){const a=s[n];if(Ft(e))e=ot(e,+a);else if(Ut(e)){const r=+a,i=+s[++n]==0?"key":"value",l=ot(e,r);switch(i){case"key":e=l;break;case"value":e=e.get(l);break}}else e=e[a]}return e},Fs=(e,s,n)=>{if(Fa(s),s.length===0)return n(e);let a=e;for(let i=0;i<s.length-1;i++){const l=s[i];if(Xe(a)){const c=+l;a=a[c]}else if(Rt(a))a=a[l];else if(Ft(a)){const c=+l;a=ot(a,c)}else if(Ut(a)){if(i===s.length-2)break;const u=+l,d=+s[++i]==0?"key":"value",h=ot(a,u);switch(d){case"key":a=h;break;case"value":a=a.get(h);break}}}const r=s[s.length-1];if(Xe(a)?a[+r]=n(a[+r]):Rt(a)&&(a[r]=n(a[r])),Ft(a)){const i=ot(a,+r),l=n(i);i!==l&&(a.delete(i),a.add(l))}if(Ut(a)){const i=+s[s.length-2],l=ot(a,i);switch(+r==0?"key":"value"){case"key":{const u=n(l);a.set(u,a.get(l)),u!==l&&a.delete(l);break}case"value":{a.set(l,n(a.get(l)));break}}}return e};function qs(e,s,n=[]){if(!e)return;if(!Xe(e)){Nt(e,(i,l)=>qs(i,s,[...n,...Mt(l)]));return}const[a,r]=e;r&&Nt(r,(i,l)=>{qs(i,s,[...n,...Mt(l)])}),s(a,n)}function Ro(e,s,n){return qs(s,(a,r)=>{e=Fs(e,r,i=>Oo(i,a,n))}),e}function Uo(e,s){function n(a,r){const i=Go(e,Mt(r));a.map(Mt).forEach(l=>{e=Fs(e,l,()=>i)})}if(Xe(s)){const[a,r]=s;a.forEach(i=>{e=Fs(e,Mt(i),()=>e)}),r&&Nt(r,n)}else Nt(s,n);return e}var Fo=(e,s)=>Rt(e)||Xe(e)||Ut(e)||Ft(e)||Oa(e,s);function qo(e,s,n){const a=n.get(e);a?a.push(s):n.set(e,[s])}function zo(e,s){const n={};let a;return e.forEach(r=>{if(r.length<=1)return;s||(r=r.map(c=>c.map(String)).sort((c,u)=>c.length-u.length));const[i,...l]=r;i.length===0?a=l.map(Is):n[Is(i)]=l.map(Is)}),a?Us(n)?[a]:[a,n]:Us(n)?void 0:n}var qa=(e,s,n,a,r=[],i=[],l=new Map)=>{const c=ko(e);if(!c){qo(e,r,s);const y=l.get(e);if(y)return a?{transformedValue:null}:y}if(!Fo(e,n)){const y=Cn(e,n),p=y?{transformedValue:y.value,annotations:[y.type]}:{transformedValue:e};return c||l.set(e,p),p}if(os(i,e))return{transformedValue:null};const u=Cn(e,n),d=(u==null?void 0:u.value)??e,h=Xe(d)?[]:{},g={};Nt(d,(y,p)=>{if(p==="__proto__"||p==="constructor"||p==="prototype")throw new Error(`Detected property ${p}. This is a prototype pollution risk, please remove it from your object.`);const w=qa(y,s,n,a,[...r,p],[...i,e],l);h[p]=w.transformedValue,Xe(w.annotations)?g[p]=w.annotations:Rt(w.annotations)&&Nt(w.annotations,(v,N)=>{g[_a(p)+"."+N]=v})});const b=Us(g)?{transformedValue:h,annotations:u?[u.type]:void 0}:{transformedValue:h,annotations:u?[u.type,g]:g};return c||l.set(e,b),b};function za(e){return Object.prototype.toString.call(e).slice(8,-1)}function An(e){return za(e)==="Array"}function $o(e){if(za(e)!=="Object")return!1;const s=Object.getPrototypeOf(e);return!!s&&s.constructor===Object&&s===Object.prototype}function Vo(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 zs(e,s={}){if(An(e))return e.map(r=>zs(r,s));if(!$o(e))return e;const n=Object.getOwnPropertyNames(e),a=Object.getOwnPropertySymbols(e);return[...n,...a].reduce((r,i)=>{if(An(s.props)&&!s.props.includes(i))return r;const l=e[i],c=zs(l,s);return Vo(r,i,c,e,s.nonenumerable),r},{})}var pe=class{constructor({dedupe:e=!1}={}){this.classRegistry=new yo,this.symbolRegistry=new ka(s=>s.description??""),this.customTransformerRegistry=new bo,this.allowedErrorProps=[],this.dedupe=e}serialize(e){const s=new Map,n=qa(e,s,this,this.dedupe),a={json:n.transformedValue};n.annotations&&(a.meta={...a.meta,values:n.annotations});const r=zo(s,this.dedupe);return r&&(a.meta={...a.meta,referentialEqualities:r}),a}deserialize(e){const{json:s,meta:n}=e;let a=zs(s);return n!=null&&n.values&&(a=Ro(a,n.values,this)),n!=null&&n.referentialEqualities&&(a=Uo(a,n.referentialEqualities)),a}stringify(e){return JSON.stringify(this.serialize(e))}parse(e){return this.deserialize(JSON.parse(e))}registerClass(e,s){this.classRegistry.register(e,s)}registerSymbol(e,s){this.symbolRegistry.register(e,s)}registerCustom(e,s){this.customTransformerRegistry.register({name:s,...e})}allowErrorProps(...e){this.allowedErrorProps.push(...e)}};pe.defaultInstance=new pe;pe.serialize=pe.defaultInstance.serialize.bind(pe.defaultInstance);pe.deserialize=pe.defaultInstance.deserialize.bind(pe.defaultInstance);pe.stringify=pe.defaultInstance.stringify.bind(pe.defaultInstance);pe.parse=pe.defaultInstance.parse.bind(pe.defaultInstance);pe.registerClass=pe.defaultInstance.registerClass.bind(pe.defaultInstance);pe.registerSymbol=pe.defaultInstance.registerSymbol.bind(pe.defaultInstance);pe.registerCustom=pe.defaultInstance.registerCustom.bind(pe.defaultInstance);pe.allowErrorProps=pe.defaultInstance.allowErrorProps.bind(pe.defaultInstance);var $a=pe.serialize,Ho=pe.stringify;function Ko(e){return e.state.fetchStatus==="fetching"?"fetching":e.getObserversCount()?e.state.fetchStatus==="paused"?"paused":e.isStale()?"stale":"fresh":"inactive"}function Qo(e,s){return`${e}${s.charAt(0).toUpperCase()+s.slice(1)}`}function Wo({queryState:e,observerCount:s,isStale:n}){return e.fetchStatus==="fetching"?"blue":s?e.fetchStatus==="paused"?"purple":n?"yellow":"green":"gray"}function Yo({status:e,isPaused:s}){return s?"purple":e==="error"?"red":e==="pending"?"yellow":e==="success"?"green":"gray"}function Jo(e){return e==="fresh"?"green":e==="stale"?"yellow":e==="paused"?"purple":e==="inactive"?"gray":"blue"}var Xo=(e,s=!1)=>{const{json:n}=$a(e);return JSON.stringify(n,null,s?2:void 0)},rs=e=>e.state.fetchStatus!=="idle"?0:e.getObserversCount()?e.isStale()?2:1:3,Zo=(e,s)=>e.queryHash.localeCompare(s.queryHash),Va=(e,s)=>e.state.dataUpdatedAt<s.state.dataUpdatedAt?1:-1,ec=(e,s)=>rs(e)===rs(s)?Va(e,s):rs(e)>rs(s)?1:-1,tc={status:ec,"query hash":Zo,"last updated":Va},is=e=>e.state.isPaused?0:e.state.status==="error"?2:e.state.status==="pending"?1:3,Ha=(e,s)=>e.state.submittedAt<s.state.submittedAt?1:-1,sc=(e,s)=>is(e)===is(s)?Ha(e,s):is(e)>is(s)?1:-1,nc={status:sc,"last updated":Ha},ac=e=>e*parseFloat(getComputedStyle(document.documentElement).fontSize),rc=()=>{const[e,s]=Se("dark");return ha(()=>{const n=window.matchMedia("(prefers-color-scheme: dark)");s(n.matches?"dark":"light");const a=r=>{s(r.matches?"dark":"light")};n.addEventListener("change",a),Et(()=>n.removeEventListener("change",a))}),e},It=(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,It(a.get(r),i,n)),a}if(e instanceof Set){const a=It(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]=It(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]=It(a[r],i,n),a}return e},_t=(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,_t(n.get(a),r)),n}if(e instanceof Set){const n=_t(Array.from(e),s);return new Set(n)}if(Array.isArray(e)){const n=[...e];if(s.length===1)return n.filter((i,l)=>l.toString()!==s[0]);const[a,...r]=s;return n[a]=_t(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]=_t(n[a],r),n}return e},Ka=(e,s)=>{if(!e||document.querySelector("#_goober")||(s==null?void 0:s.querySelector("#_goober")))return;const a=document.createElement("style"),r=document.createTextNode("");a.appendChild(r),a.id="_goober",a.setAttribute("nonce",e),s?s.appendChild(a):document.head.appendChild(a)},ct,qt,zt,$t,st,Vt,ut,dt,mt,ht,ft,gt,Ht,kn,ic=(kn=class{constructor(e){ge(this,ct);ge(this,qt);ge(this,zt);ge(this,$t);ge(this,st,!1);ge(this,Vt);ge(this,ut);ge(this,dt);ge(this,mt);ge(this,ht);ge(this,ft);ge(this,gt);ge(this,Ht);const{client:s,queryFlavor:n,version:a,onlineManager:r,buttonPosition:i,position:l,initialIsOpen:c,errorTypes:u,styleNonce:d,shadowDOMTarget:h}=e;fe(this,ct,Se(s)),fe(this,zt,n),fe(this,$t,a),fe(this,qt,r),fe(this,Vt,d),fe(this,ut,h),fe(this,dt,Se(i)),fe(this,mt,Se(l)),fe(this,ht,Se(c)),fe(this,ft,Se(u))}setButtonPosition(e){X(this,dt)[1](e)}setPosition(e){X(this,mt)[1](e)}setInitialIsOpen(e){X(this,ht)[1](e)}setErrorTypes(e){X(this,ft)[1](e)}setClient(e){X(this,ct)[1](e)}mount(e){if(X(this,st))throw new Error("Devtools is already mounted");const s=wa(()=>{const n=this,[a]=X(this,dt),[r]=X(this,mt),[i]=X(this,ht),[l]=X(this,ft),[c]=X(this,ct);let u;return X(this,gt)?u=X(this,gt):(u=va(()=>Promise.resolve().then(()=>require("./HO4MOOFI-Av3UJGkm.cjs"))),fe(this,gt,u)),Ka(X(this,Vt),X(this,ut)),ln(u,on({get queryFlavor(){return X(n,zt)},get version(){return X(n,$t)},get onlineManager(){return X(n,qt)},get shadowDOMTarget(){return X(n,ut)}},{get client(){return c()},get buttonPosition(){return a()},get position(){return r()},get initialIsOpen(){return i()},get errorTypes(){return l()}}))},e);fe(this,st,!0),fe(this,Ht,s)}unmount(){var e;if(!X(this,st))throw new Error("Devtools is not mounted");(e=X(this,Ht))==null||e.call(this),fe(this,st,!1)}},ct=new WeakMap,qt=new WeakMap,zt=new WeakMap,$t=new WeakMap,st=new WeakMap,Vt=new WeakMap,ut=new WeakMap,dt=new WeakMap,mt=new WeakMap,ht=new WeakMap,ft=new WeakMap,gt=new WeakMap,Ht=new WeakMap,kn),xt,Kt,Qt,Wt,nt,Yt,pt,yt,jt,vt,bt,wt,St,Jt,Ln,lc=(Ln=class{constructor(e){ge(this,xt);ge(this,Kt);ge(this,Qt);ge(this,Wt);ge(this,nt,!1);ge(this,Yt);ge(this,pt);ge(this,yt);ge(this,jt);ge(this,vt);ge(this,bt);ge(this,wt);ge(this,St);ge(this,Jt);const{client:s,queryFlavor:n,version:a,onlineManager:r,buttonPosition:i,position:l,initialIsOpen:c,errorTypes:u,styleNonce:d,shadowDOMTarget:h,onClose:g}=e;fe(this,xt,Se(s)),fe(this,Qt,n),fe(this,Wt,a),fe(this,Kt,r),fe(this,Yt,d),fe(this,pt,h),fe(this,yt,Se(i)),fe(this,jt,Se(l)),fe(this,vt,Se(c)),fe(this,bt,Se(u)),fe(this,wt,Se(g))}setButtonPosition(e){X(this,yt)[1](e)}setPosition(e){X(this,jt)[1](e)}setInitialIsOpen(e){X(this,vt)[1](e)}setErrorTypes(e){X(this,bt)[1](e)}setClient(e){X(this,xt)[1](e)}setOnClose(e){X(this,wt)[1](()=>e)}mount(e){if(X(this,nt))throw new Error("Devtools is already mounted");const s=wa(()=>{const n=this,[a]=X(this,yt),[r]=X(this,jt),[i]=X(this,vt),[l]=X(this,bt),[c]=X(this,xt),[u]=X(this,wt);let d;return X(this,St)?d=X(this,St):(d=va(()=>Promise.resolve().then(()=>require("./HUY7CZI3-DqMa7qGt.cjs"))),fe(this,St,d)),Ka(X(this,Yt),X(this,pt)),ln(d,on({get queryFlavor(){return X(n,Qt)},get version(){return X(n,Wt)},get onlineManager(){return X(n,Kt)},get shadowDOMTarget(){return X(n,pt)}},{get client(){return c()},get buttonPosition(){return a()},get position(){return r()},get initialIsOpen(){return i()},get errorTypes(){return l()},get onClose(){return u()}}))},e);fe(this,nt,!0),fe(this,Jt,s)}unmount(){var e;if(!X(this,nt))throw new Error("Devtools is not mounted");(e=X(this,Jt))==null||e.call(this),fe(this,nt,!1)}},xt=new WeakMap,Kt=new WeakMap,Qt=new WeakMap,Wt=new WeakMap,nt=new WeakMap,Yt=new WeakMap,pt=new WeakMap,yt=new WeakMap,jt=new WeakMap,vt=new WeakMap,bt=new WeakMap,wt=new WeakMap,St=new WeakMap,Jt=new WeakMap,Ln);function oc(e){const s=D.useQueryClient(e.client),n=we.useRef(null),{buttonPosition:a,position:r,initialIsOpen:i,errorTypes:l,styleNonce:c,shadowDOMTarget:u}=e,[d]=we.useState(new ic({client:s,queryFlavor:"React Query",version:"5",onlineManager:D.onlineManager,buttonPosition:a,position:r,initialIsOpen:i,errorTypes:l,styleNonce:c,shadowDOMTarget:u}));return we.useEffect(()=>{d.setClient(s)},[s,d]),we.useEffect(()=>{a&&d.setButtonPosition(a)},[a,d]),we.useEffect(()=>{r&&d.setPosition(r)},[r,d]),we.useEffect(()=>{d.setInitialIsOpen(i||!1)},[i,d]),we.useEffect(()=>{d.setErrorTypes(l||[])},[l,d]),we.useEffect(()=>(n.current&&d.mount(n.current),()=>{d.unmount()}),[d]),t.jsx("div",{className:"tsqd-parent-container",ref:n})}function cc(e){const s=D.useQueryClient(e.client),n=we.useRef(null),{errorTypes:a,styleNonce:r,shadowDOMTarget:i}=e,[l]=we.useState(new lc({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 we.useEffect(()=>{l.setClient(s)},[s,l]),we.useEffect(()=>{l.setOnClose(e.onClose??(()=>{}))},[e.onClose,l]),we.useEffect(()=>{l.setErrorTypes(a||[])},[a,l]),we.useEffect(()=>(n.current&&l.mount(n.current),()=>{l.unmount()}),[l]),t.jsx("div",{style:{height:"500px",...e.style},className:"tsqd-parent-container",ref:n})}var uc=process.env.NODE_ENV!=="development"?function(){return null}:oc;process.env.NODE_ENV;const Qa=()=>t.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center w-screen h-screen bg-white/40",children:t.jsx("div",{className:"flex items-center justify-center bg-white rounded-full size-10",children:t.jsx(E.Loader2,{className:"size-5 animate-spin"})})}),dc=()=>{q.registerChaiFeatureFlag("dynamic-page-selector",{description:"Dynamic page selector"}),q.registerChaiFeatureFlag("realtime-page-lock",{description:"Realtime page lock"})},mc=()=>{const e=re(),s=J();return D.useQuery({queryKey:[Y,L.GET_COLLECTIONS],initialData:[],queryFn:async()=>s(e,{action:L.GET_COLLECTIONS})})},hc=()=>{const{data:e}=Te(),{data:s}=At(),{data:n}=Ze(),a=re(),r=J(),i=f.useMemo(()=>(n==null?void 0:n.fallbackLang)||"en",[n==null?void 0:n.fallbackLang]);return D.useMutation({mutationFn:async({block:l})=>r(a,{action:L.GET_BLOCK_ASYNC_PROPS,data:{block:l,lang:(s==null?void 0:s.lang)||i,pageProps:{slug:s==null?void 0:s.slug,searchParams:{},pageType:s==null?void 0:s.pageType,fallbackLang:i,lastSaved:s.lastSaved,pageId:e.id,primaryPageId:s.primaryPage||e.id,pageBaseSlug:s==null?void 0:s.slug,dynamic:e==null?void 0:e.dynamic,languagePageId:s.id}}})})},Wa=()=>{const e=en();return f.useCallback(({pageId:s})=>{e(s)},[e])},fc=60*5;function gc(){const{user:e,setUser:s,logout:n,isLoggedIn:a,isSessionExpired:r}=Ue(),i=js(),l=f.useRef(null),c=f.useCallback(async()=>{if(!(!m.has(e,"expiresAt")||!m.has(e,"accessToken")||!m.has(e,"refreshToken")))try{const u=await $s(i,{action:"REFRESH_TOKEN",data:{refreshToken:e.refreshToken,accessToken:e.accessToken}});if(!u.ok){n();return}const d=await u.json();m.has(d,"id")&&m.has(d,"email")&&m.has(d,"accessToken")&&m.has(d,"refreshToken")?s(d):n()}catch{n()}},[e,n,s,i]);return f.useEffect(()=>{a&&r&&c()},[r,a,c]),f.useEffect(()=>{if(!a||!m.has(e,"expiresAt")||!m.has(e,"refreshToken")||!m.has(e,"accessToken")){l.current&&(clearInterval(l.current),l.current=null);return}return l.current||(l.current=setInterval(()=>{if(!m.has(e,"expiresAt")||!m.has(e,"refreshToken")||!m.has(e,"accessToken"))return;const u=Math.floor(Date.now()/1e3),d=e.expiresAt-u;d<fc&&d>0&&c()},1e3)),()=>{l.current&&(clearInterval(l.current),l.current=null)}},[a,e==null?void 0:e.expiresAt,e==null?void 0:e.refreshToken,e==null?void 0:e.accessToken,i]),null}const xc=f.lazy(()=>Promise.resolve().then(()=>Lc));dc();nr.loadWebBlocks();q.registerChaiTopBar(Wi);jl();q.registerChaiMediaManager(xc);q.registerChaiSaveToLibrary(Gr);const pc=e=>{const s=f.useRef([]),[n]=_e(),a=n.get("page"),{data:r}=Te(),{data:i={role:"",permissions:null}}=aa();Zi(),jr();const{data:l,isFetching:c}=$n(),{blocks:u}=Xi(l),{data:d}=Pe(),{mutateAsync:h}=Mn(),g=Yi(),{onSave:b}=el(),{getPartialBlocks:y,getPartialBlockBlocks:p}=tl(),{aiContext:w,setAiContext:v}=Vs(),{mutateAsync:N}=Ur(),[C,B]=f.useState(!1),{data:S}=Ze(),P=Ks(),{data:O}=Qs(),{data:z}=mc(),{mutateAsync:$}=hc(),se=Wa();gr(),f.useEffect(()=>{const Q=()=>{document.hidden?B(!0):B(!1)};return window.addEventListener("visibilitychange",Q),()=>window.removeEventListener("visibilitychange",Q)},[]),s.current=u;const H=f.useMemo(()=>{const Q={};return i&&(Q.permissions=m.get(i,"permissions",null),Q.role=m.get(i,"role","user")),Q},[i]),K=f.useCallback(async(Q,ne)=>await N({pageType:Q,query:ne}),[N]),te=f.useMemo(()=>m.get(S,"theme",{})||{},[S]);return t.jsxs(t.Fragment,{children:[c&&t.jsx(Qa,{}),t.jsx(q.ChaiBuilderEditor,{gotoPage:se,collections:z??[],getBlockAsyncProps:$,pageExternalData:O,themePresets:e.themePresets??[],pageId:r==null?void 0:r.id,loading:c,fallbackLang:P,languages:(S==null?void 0:S.languages)||[],brandingOptions:(S==null?void 0:S.theme)||{},translations:e.translations||{},locale:e.locale||"en",htmlDir:e.htmlDir||"ltr",autoSaveSupport:!C&&(e.autoSaveSupport??!0),autoSaveInterval:e.autoSaveInterval??15,onError:e.onError||console.error,getPartialBlockBlocks:p,getPartialBlocks:y,blocks:c?[]:u,theme:m.cloneDeep(te),pageTypes:d,searchPageTypeItems:K,saveAiContextCallback:async Q=>{if(!a)return!0;const ne=s.current,_={_type:"@chai/ai-context",_value:m.isString(Q)?Q:""},U=[...ne,_];return await b({page:a,blocks:U}),v(Q),!0},aiContext:w,askAiCallBack:g,onSave:async({blocks:Q,theme:ne})=>{if(!a)return!0;s.current=Q;const _={_type:"@chai/ai-context",_value:m.isString(w)?w:""},U=[...Q,_];return await b({page:a,blocks:U}),s.current=U,m.isEqual(ne,te)||await h({settings:{theme:ne}}),!0},themePanelComponent:Wr,...H}),t.jsxs("div",{children:[t.jsx(Ar,{}),t.jsx(Tr,{})]})]})},yc=new D.QueryClient({defaultOptions:{queries:{refetchOnWindowFocus:!1,refetchOnReconnect:!1}}}),jc=e=>{gc();const{isLoggedIn:s,isSessionExpired:n}=Ue(),[,a]=On(),[r,i]=f.useState(!1);return f.useEffect(()=>(a(m.pick(e,["apiUrl","usersApiUrl","assetsApiUrl","getPreviewUrl","getLiveUrl","logo","onLogout","realtimeInstance"])),setTimeout(()=>{i(!0)},200),()=>{i(!1),a({})}),[e,a]),r?t.jsxs(D.QueryClientProvider,{client:yc,children:[s?n?t.jsx(Qa,{}):t.jsx(pc,{...e}):t.jsx(rl,{}),t.jsx(uc,{}),t.jsx(V.Toaster,{richColors:!0})]}):t.jsx("div",{})},vc=()=>{const e=re(),s=J(),{data:n}=At(),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:L.UPDATE_PAGE_METADATA,data:{id:n.id,metadata:r}})},onSuccess:()=>{a.invalidateQueries({queryKey:[Y,L.GET_BUILDER_PAGE_DATA]}),a.invalidateQueries({queryKey:[Y,L.GET_LANGUAGE_PAGES]})},onError:()=>{console.error("Failed to update metadata")}})},bc=()=>{const e=Xt(),s=D.useQueryClient(),n=J();return D.useMutation({mutationFn:async({file:a,folderId:r,name:i,optimize:l=!0})=>n(e,{action:L.UPLOAD_ASSET,data:{file:a,folderId:r,name:i,optimize:l}}),onSuccess:a=>{if(a!=null&&a.error)throw new Error(a==null?void 0:a.error);s.invalidateQueries({queryKey:[Y,L.GET_ASSETS]}),V.toast.success("Asset uploaded successfully")},onError:()=>{V.toast.error("Failed to upload asset")}})},wc=()=>{const e=Xt(),s=D.useQueryClient(),n=J();return D.useMutation({mutationFn:async a=>n(e,{action:L.DELETE_ASSET,data:{id:a}}),onSuccess:a=>{if(a!=null&&a.error)throw new Error(a==null?void 0:a.error);s.invalidateQueries({queryKey:[Y,L.GET_ASSETS]}),V.toast.success("Asset deleted successfully")},onError:()=>{V.toast.error("Failed to delete asset")}})},Sc=()=>{const e=Xt(),s=D.useQueryClient(),n=J();return D.useMutation({mutationFn:async a=>n(e,{action:L.UPDATE_ASSET,data:a}),onSuccess:a=>{if(a!=null&&a.error)throw new Error(a==null?void 0:a.error);s.invalidateQueries({queryKey:[Y,L.GET_ASSETS]}),V.toast.success("Asset updated successfully")},onError:()=>{V.toast.error("Failed to update asset")}})},Ec=(e={})=>{const s=Xt(),n=J(),{search:a,page:r=1,limit:i=30}=e;return D.useQuery({queryKey:[Y,L.GET_ASSETS,a,r,i],queryFn:async()=>{const l=await n(s,{action:L.GET_ASSETS,data:{search:a,page:r,limit:i}});return l.page=r,l.limit=i,l},staleTime:1e3*60*5,retry:1})},Nc=e=>{const s=Xt(),n=J();return D.useQuery({queryKey:[Y,L.GET_ASSET,e],queryFn:async()=>e?await n(s,{action:L.GET_ASSET,data:{id:e}}):null,staleTime:1e3*60*5,retry:1})};function Cc(e){const s=isNaN(e)?0:typeof e=="number"?e:parseInt(e);return s?s<1024?`${s.toFixed(2)} B`:s<1024*1024?`${(s/1024).toFixed(2)} KB`:`${(s/(1024*1024)).toFixed(2)} MB`:"0 B"}function Tn(e){if(!e)return"N/A";const s=new Date(e);return new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric",hour:"2-digit",minute:"2-digit"}).format(s)}function Pn(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 Ac=({assetId:e,onBack:s,onEdit:n,onSave:a,isSaving:r})=>{var g,b,y;const{data:i,isLoading:l,isError:c}=Nc(e||""),[u,d]=f.useState(""),h=async(p,w)=>{try{await navigator.clipboard.writeText(p),V.toast.success(`${w} copied to clipboard`)}catch(v){V.toast.error(`Failed to copy ${w}`,{description:v==null?void 0:v.message})}};return f.useEffect(()=>{i!=null&&i.description&&d(i.description)},[i]),l?t.jsx("div",{className:"flex-1 flex items-center justify-center",children:t.jsx(E.Loader,{className:"h-8 w-8 animate-spin"})}):c||!(i!=null&&i.id)?t.jsx("div",{className:"flex-1 flex items-center justify-center",children:t.jsxs("div",{className:"text-center max-w-md mx-auto p-6",children:[t.jsx("div",{className:"flex justify-center mb-4",children:t.jsx(E.AlertCircle,{className:"h-12 w-12 text-gray-400"})}),t.jsx("h3",{className:"text-lg font-medium text-gray-900 mb-2",children:"No Asset Found"}),t.jsx("p",{className:"text-sm text-gray-500 mb-6",children:c?"There was an error loading the asset. Please try again later.":"The asset you're looking for doesn't exist or has been removed."}),t.jsxs("div",{className:"flex justify-center gap-4",children:[t.jsx(o.Button,{variant:"outline",onClick:s,children:"Back to Assets"}),c&&t.jsx(o.Button,{variant:"default",onClick:()=>window.location.reload(),children:"Try Again"})]})]})}):t.jsxs("div",{className:"flex-1 flex flex-col gap-y-4 overflow-hidden",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsxs(o.Button,{variant:"outline",size:"sm",onClick:s,disabled:r,children:[t.jsx(E.ChevronLeft,{className:"h-4 w-4"}),"Back to Assets"]}),t.jsxs("div",{className:"flex gap-2",children:[t.jsx(o.Button,{variant:"outline",onClick:s,disabled:r,children:"Cancel"}),t.jsxs(o.Button,{variant:"outline",onClick:()=>h(i.url,"Asset URL"),disabled:r,children:[t.jsx(E.Copy,{className:"h-4 w-4 mr-2"}),"Copy URL"]}),t.jsxs(o.Button,{variant:"default",onClick:()=>n(i),disabled:r,children:[t.jsx(E.Pencil,{className:"h-4 w-4"}),"Edit Image"]})]})]}),t.jsxs("div",{className:"grid grid-cols-2 items-start gap-6 flex-1 overflow-hidden",children:[t.jsx("div",{className:"relative h-[calc(80vh-200px)] w-full flex items-start justify-center",children:t.jsx("img",{src:`${i.url}?v=${((g=i.metadata)==null?void 0:g.updatedAt)||i.createdAt}`,alt:i.name,className:"w-full h-full object-contain rounded-lg max-h-max max-w-max"})}),t.jsxs("div",{className:"space-y-6",children:[t.jsxs("div",{className:"grid gap-3 border rounded-md pt-2 bg-gray-100",children:[t.jsx(o.Label,{className:"w-full text-center",children:"Details"}),t.jsx("div",{className:"grid grid-cols-1 gap-2 text-sm border rounded-md p-2 bg-white",children:[{label:"File Name",value:i.name},{label:"Type",value:i.type,capitalize:!0},{label:"Format",value:((b=i.metadata)==null?void 0:b.format)||i.type,capitalize:!0},{label:"Size",value:Cc(i.size)},{label:"Dimensions",value:`${i.width||0} × ${i.height||0}`},{label:"Created",value:Tn(i.createdAt)},{label:"Updated",value:Tn(((y=i.metadata)==null?void 0:y.updatedAt)||i.createdAt)},{label:"URL",value:i.url,copyable:!0}].map(p=>t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(o.Label,{className:"w-max text-left px-2 w-1/4 font-normal text-gray-700",children:p.label}),":",t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("div",{className:"w-max text-left font-medium text-gray-900"+(p.capitalize?" capitalize":""),children:p.value}),p.copyable&&t.jsx(o.Button,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>h(p.value,p.label),children:t.jsx(E.Link,{className:"h-3 w-3"})})]})]},p.label))})]}),i.usedOn&&i.usedOn.length>0&&t.jsxs("div",{className:"grid gap-3",children:[t.jsx(o.Label,{children:"Used On"}),t.jsx("div",{className:"grid grid-cols-1 gap-2 text-sm border rounded-md p-2",children:i.usedOn.map((p,w)=>t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("div",{className:"w-max text-left font-medium text-gray-900",children:p.name}),t.jsxs("div",{className:"text-gray-500",children:["(",p.slug,")"]})]},w))})]}),t.jsxs("div",{className:"grid gap-3 border rounded-md pt-2 bg-gray-100 relative",children:[t.jsx(o.Label,{className:"w-full text-center",children:"Description"}),t.jsx(o.Textarea,{id:"description",value:u,placeholder:"Enter a description for the asset",onChange:p=>d(p.target.value),rows:3,disabled:r,className:"hover:border-black/40 bg-white"}),t.jsx("div",{className:"flex justify-end items-start absolute top-1.5 right-2",children:t.jsx("button",{type:"button",onClick:()=>a(u),disabled:r||!Pn(u,i),className:`py-0 bg-blue-500 text-white px-3 py-0.5 rounded-md text-sm ${r||!Pn(u,i)?"opacity-50 cursor-not-allowed":""}`,children:r?t.jsxs(t.Fragment,{children:[t.jsx(E.Loader,{className:"h-4 w-4 mr-2 animate-spin"}),"Saving..."]}):"Save"})})]})]})]})]})},Tc=f.lazy(()=>Promise.resolve().then(()=>require("./image-editor-BWLJT1mr.cjs")));function Pc(e){const s=isNaN(e)?0:typeof e=="number"?e:parseInt(e);return s?s<1024?`${s.toFixed(2)} B`:s<1024*1024?`${(s/1024).toFixed(2)} KB`:`${(s/(1024*1024)).toFixed(2)} MB`:"0 B"}const kc=({isUpdatingAsset:e,allowedTypes:s,maxFileSize:n,uploadAsset:a,isUploadingAsset:r,onUploaded:i})=>{const[l,c]=f.useState(()=>{const y=localStorage.getItem("chai_optimize_images");return y!==null?y==="true":!0});f.useEffect(()=>{localStorage.setItem("chai_optimize_images",l.toString())},[l]);const u=e||r,d=f.useCallback(async y=>new Promise((p,w)=>{const v=y[0],N=new FileReader;N.readAsDataURL(v),N.onload=async()=>{a({file:N.result,folderId:void 0,name:v.name,optimize:l},{onSuccess:C=>{i&&i(C),p(C)},onError:C=>{w(C)}})},N.onerror=C=>w(C)}),[a,l,i]),{getRootProps:h,getInputProps:g,isDragActive:b}=sr.useDropzone({onDrop:d,accept:{"image/*":s.includes("image")?[]:[]},maxSize:n*1024*1024,disabled:e||r});return t.jsx("div",{className:`flex flex-col items-center justify-center w-full border-2 hover:border-black/50 border-dashed p-0 rounded-lg border-slate-300 py-2 h-[60px] ${u?"opacity-90 bg-gray-100 pointer-events-none":"hover:border-black/50 bg-gray-100 hover:bg-gray-100"}`,children:t.jsxs("div",{...h(),className:q.mergeClasses("rounded-lg text-center cursor-pointer w-full h-max flex flex-col justify-center",u?"items-start":"items-center",b?"border-primary bg-primary/5":"border-muted-foreground/20"),children:[t.jsx("input",{...g()}),u?t.jsx("div",{className:"flex flex-col items-center px-6",children:t.jsxs("div",{className:"leading-tight flex items-center justify-center gap-2",children:[t.jsx("div",{className:"flex items-center justify-center rounded-full bg-indigo-100 p-2",children:t.jsx(E.Loader,{className:"h-4 w-4 text-indigo-500 animate-spin"})}),t.jsxs("div",{className:"text-left",children:[t.jsx("div",{className:"font-medium",children:e?"Updating file...":"Uploading file..."}),t.jsxs("div",{className:"text-xs text-muted-foreground font-light",children:["Please wait while we ",e?"update":"upload"," ","your file..."]})]})]})}):t.jsxs("div",{className:"flex items-center justify-between w-full px-6",children:[t.jsx("div",{className:"flex flex-col items-center",children:t.jsxs("div",{className:"leading-tight flex items-center justify-between gap-2",children:[t.jsx("div",{className:"flex items-center justify-center rounded-full bg-indigo-100 p-2 border border-indigo-500",children:t.jsx(E.Upload,{className:"h-4 w-4 text-indigo-500"})}),t.jsxs("div",{className:"text-left",children:[t.jsxs("div",{className:"font-medium",children:["Drop your file here or"," ",t.jsx("span",{className:"text-indigo-500 cursor-pointer hover:underline",children:"browse"})]}),t.jsxs("div",{className:"text-xs text-muted-foreground font-light",children:[t.jsxs("span",{className:"",children:["Accepted file types:"," ",t.jsx("span",{className:"capitalize text-indigo-400",children:s.join(", ")})," & "]}),t.jsxs("span",{children:["Max file size:"," ",t.jsxs("span",{className:"capitalize text-indigo-400",children:[n," MB"]})]})]})]})]})}),t.jsxs("div",{className:"text-xs text-muted-foreground flex items-center gap-2",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsxs("span",{className:"text-xs",children:["Optimization:"," ",t.jsx("span",{className:l?"text-indigo-600":"text-gray-400",children:l?"On":"Off"})]}),t.jsx(o.Switch,{checked:l,onCheckedChange:y=>{c(y)},onClick:y=>{y.stopPropagation()},className:"data-[state=checked]:bg-indigo-500"})]}),t.jsx(o.TooltipProvider,{children:t.jsxs(o.Tooltip,{children:[t.jsx(o.TooltipTrigger,{asChild:!0,children:t.jsx("span",{className:`text-amber-500 flex items-center cursor-help ${l?"invisible":""}`,children:t.jsx(E.AlertTriangle,{className:"h-4 w-4 mr-1"})})}),t.jsx(o.TooltipContent,{side:"top",children:t.jsxs("p",{className:"text-white text-xs",children:["Warning: Unoptimized images may affect ",t.jsx("br",{})," performance and page load times"]})})]})})]})]})]})})};function Ya({close:e,onSelect:s,mode:n="image",assetId:a}){const l=f.useMemo(()=>[n],[n]),[c,u]=f.useState(null),[d,h]=f.useState(null),[g,b]=f.useState(null),[y,p]=f.useState({show:!1,file:""}),[w,v]=f.useState(!1),[N,C]=f.useState(a?"details":"grid"),[B,S]=f.useState(""),[P,O]=f.useState(""),[z,$]=f.useState(1),[se]=f.useState(30),[H,K]=f.useState([]);f.useEffect(()=>{a&&(u(a),C("details"))},[a]),f.useEffect(()=>{const I=setTimeout(()=>{S(P),$(1)},300);return()=>clearTimeout(I)},[P]);const{data:te,isLoading:Q}=Ec({search:B.toLowerCase().trim(),page:z,limit:se}),ne=(te==null?void 0:te.assets)||[],_=(te==null?void 0:te.total)||0,U=Math.ceil(_/se),he=z<U,ye=z>1,ce=(ne==null?void 0:ne.length)>0,{mutate:j}=wc(),{mutate:x,isPending:A}=bc(),{mutate:M,isPending:G}=Sc(),T=f.useCallback(I=>{I>=1&&I<=U&&$(I)},[U]),W=f.useCallback(()=>{he&&T(z+1)},[z,he,T]),F=f.useCallback(()=>{ye&&T(z-1)},[z,ye,T]),Z=I=>{O(I.target.value)},de=f.useCallback(I=>{K(le=>m.find(le,{id:I.id})?[]:[I])},[!1]),ve=f.useCallback(()=>{K([])},[]),oe=I=>{(I==null?void 0:I.length)!==0&&(s(m.pick(m.first(I||H),["id","url","width","height","description"])),e())},R=async I=>{h(I)},be=async()=>{d&&(b(d==null?void 0:d.id),await j(d.id,{onSuccess:()=>{b(null),h(null)},onError:()=>{b(null)}}),h(null))},ie=I=>{u(I.id),C("details")},Ne=async(I,le)=>{try{const Ee=localStorage.getItem("chai_optimize_images")!=="false";le?(await x({file:I,folderId:void 0,name:y.name||"",optimize:Ee}),p({show:!1,file:""})):(await M({id:y.id||"",file:I}),p({show:!1,file:""}))}catch(Ee){console.error("Error saving edited image:",Ee)}},De=f.useCallback(I=>{K([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"}),N==="grid"?t.jsxs(t.Fragment,{children:[t.jsx(kc,{maxFileSize:10,allowedTypes:l,uploadAsset:x,isUpdatingAsset:G,isUploadingAsset:A,onUploaded:De}),t.jsxs("div",{className:"border p-2 rounded-lg flex-1 flex flex-col gap-y-3 overflow-hidden relative",children:[t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsxs("div",{className:"relative w-1/2 ",children:[t.jsx(E.Search,{strokeWidth:3,className:`absolute left-2 top-2.5 h-4 w-4 text-muted-foreground ${P.length>0?"text-indigo-800":""}`}),t.jsx(o.Input,{placeholder:"Search assets...",onChange:Z,value:P,className:"pl-8"})]}),H.length>0?t.jsx("div",{className:"flex justify-between items-center",children:t.jsxs("div",{className:"flex items-center gap-2",children:[H.length>0&&t.jsx(t.Fragment,{children:t.jsx(o.Button,{variant:"outline",size:"sm",onClick:()=>ve(),title:"Clear selection",children:"Clear"})}),t.jsx(o.Button,{size:"sm",onClick:()=>oe(H),disabled:H.length===0,children:"Select Asset"})]})}):null]}),t.jsx("div",{className:"flex-1 overflow-y-auto pb-[66px]",children:Q?t.jsxs("div",{className:"columns-1 gap-3 space-y-3 sm:columns-3 md:columns-5",children:[t.jsx("div",{className:"bg-gray-200 h-64 w-full animate-pulse rounded"}),t.jsx("div",{className:"bg-gray-200 h-64 w-full animate-pulse rounded"}),t.jsx("div",{className:"bg-gray-200 h-64 w-full animate-pulse rounded"}),t.jsx("div",{className:"bg-gray-200 h-64 w-full animate-pulse rounded"}),t.jsx("div",{className:"bg-gray-200 h-64 w-full animate-pulse rounded"}),t.jsx("div",{className:"bg-gray-200 h-64 w-full animate-pulse rounded"}),t.jsx("div",{className:"bg-gray-200 h-64 w-full animate-pulse rounded"}),t.jsx("div",{className:"bg-gray-200 h-64 w-full animate-pulse rounded"}),t.jsx("div",{className:"bg-gray-200 h-64 w-full animate-pulse rounded"}),t.jsx("div",{className:"bg-gray-200 h-64 w-full animate-pulse rounded"})]}):!Q&&!ce?t.jsxs("div",{className:"flex flex-col items-center justify-center h-full border rounded-lg",children:[t.jsx("div",{className:"text-muted-foreground",children:t.jsx(E.Archive,{className:"h-9 w-9 text-indigo-500"})}),t.jsx("div",{className:"text-muted-foreground text-lg",children:"No assets found"}),t.jsx("div",{className:"text-muted-foreground text-sm",children:B.length>0?"No assets found for your search: "+B:"Start uploading assets to get started"}),t.jsx("br",{})]}):t.jsx("div",{className:"flex flex-wrap gap-3 p-1",children:ne==null?void 0:ne.map(I=>t.jsxs("div",{className:q.mergeClasses("relative cursor-pointer overflow-hidden transition-all rounded-lg border-2 group max-w-[180px] max-h-[180px] flex flex-col justify-between",H.some(le=>le.id===I.id)?"border-blue-500":"hover:border-black/90",g&&(d==null?void 0:d.id)===I.id?"opacity-50 pointer-events-none":"",g===I.id?"opacity-50 pointer-events-none":""),onClick:()=>de(I),onDoubleClick:()=>oe([I]),children:[t.jsxs("div",{className:"aspect-square relative overflow-hidden",children:[g===I.id?t.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/50",children:t.jsx(E.Loader,{className:"h-8 w-8 animate-spin text-white"})}):null,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] ${H.some(le=>le.id===I.id)?"":"group-hover:blur group-hover:contrast-50"}`}):t.jsxs("div",{className:"flex items-center justify-center h-full",children:[t.jsx(E.Film,{className:"h-12 w-12 text-muted-foreground"}),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:Pc((I==null?void 0:I.size)||0)})})]}),!H.some(le=>le.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(o.TooltipProvider,{children:t.jsxs(o.Tooltip,{children:[t.jsx(o.TooltipTrigger,{asChild:!0,children:t.jsx(o.Button,{variant:"secondary",size:"icon",className:"h-8 w-8 rounded-full",onClick:le=>{le.stopPropagation(),ie(I)},children:t.jsx(E.ImageIcon,{className:"h-4 w-4"})})}),t.jsx(o.TooltipContent,{children:t.jsx("p",{children:"View Details"})})]})}),t.jsx(o.TooltipProvider,{children:t.jsxs(o.Tooltip,{children:[t.jsx(o.TooltipTrigger,{asChild:!0,children:t.jsx(o.Button,{variant:"secondary",size:"icon",className:"h-8 w-8 rounded-full",onClick:le=>{le.stopPropagation(),navigator.clipboard.writeText(I.url),V.toast.success("Asset URL copied to clipboard")},children:t.jsx(E.Copy,{className:"h-4 w-4"})})}),t.jsx(o.TooltipContent,{children:t.jsx("p",{children:"Copy URL"})})]})}),t.jsx(o.TooltipProvider,{children:t.jsxs(o.Tooltip,{children:[t.jsx(o.TooltipTrigger,{asChild:!0,children:t.jsx(o.Button,{variant:"secondary",size:"icon",className:"h-8 w-8 rounded-full",onClick:le=>{le.stopPropagation(),p({id:I.id,show:!0,file:I.url,name:I.name})},children:t.jsx(E.Edit,{className:"h-4 w-4"})})}),t.jsx(o.TooltipContent,{children:t.jsx("p",{children:"Edit Image"})})]})}),t.jsx(o.TooltipProvider,{children:t.jsxs(o.Tooltip,{children:[t.jsx(o.TooltipTrigger,{asChild:!0,children:t.jsx(o.Button,{variant:"destructive",size:"icon",className:"h-8 w-8 rounded-full",onClick:le=>{le.stopPropagation(),R(I)},children:t.jsx(E.Trash2,{className:"h-4 w-4"})})}),t.jsx(o.TooltipContent,{children:t.jsx("p",{children:"Delete Asset"})})]})})]})}),H.some(le=>le.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(E.Check,{className:"w-3 h-3 text-white",strokeWidth:5})})]},I.id))})}),U>1&&t.jsx("div",{className:"absolute bottom-0 left-0 right-0 bg-white border-t p-4",children:t.jsxs("div",{className:"flex items-center justify-center space-x-2",children:[t.jsx(o.Button,{variant:"outline",size:"sm",onClick:F,disabled:!ye,children:"Previous"}),Array.from({length:Math.min(5,U)},(I,le)=>{const Ee=le+1;return t.jsx(o.Button,{variant:z===Ee?"default":"outline",size:"sm",onClick:()=>T(Ee),children:Ee},Ee)}),U>5&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"text-muted-foreground",children:"..."}),t.jsx(o.Button,{variant:z===U?"default":"outline",size:"sm",onClick:()=>T(U),children:U})]}),t.jsx(o.Button,{variant:"outline",size:"sm",onClick:W,disabled:!he,children:"Next"})]})})]})]}):t.jsx(Ac,{assetId:c||a||"",onBack:()=>{C("grid"),u(null)},onEdit:I=>{p({id:I.id,show:!0,file:I.url,name:I.name})},onSave:async I=>{if(c){v(!0);try{const le=ne.find(Ee=>Ee.id===c);le&&await M(m.merge(le,{description:I}))}finally{v(!1)}}},isSaving:w})]}),y.show&&t.jsx(f.Suspense,{fallback:t.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:t.jsx(E.Loader,{className:"h-8 w-8 animate-spin"})}),children:t.jsx(Tc,{imageUrl:y.file,onSave:Ne,onClose:()=>p({show:!1,file:""}),defaultSavedImageName:y.name,isEditing:!!y.id})}),d&&t.jsx(o.Dialog,{open:!!d,onOpenChange:()=>h(null),children:t.jsxs(o.DialogContent,{children:[t.jsxs(o.DialogHeader,{children:[t.jsx(o.DialogTitle,{children:"Delete Asset"}),t.jsxs(o.DialogDescription,{children:['Are you sure you want to delete "',d.name,'"? This action cannot be undone.']})]}),t.jsxs(o.DialogFooter,{className:"gap-2 sm:gap-0",children:[t.jsx(o.Button,{variant:"outline",onClick:()=>h(null),children:"Cancel"}),t.jsx(o.Button,{variant:"destructive",onClick:be,children:"Delete"})]})]})})]})}const Lc=Object.freeze(Object.defineProperty({__proto__:null,default:Ya},Symbol.toStringTag,{value:"Module"})),Ja=({assetId:e,assetUrl:s,onChange:n,className:a="",placeholder:r="Select an image",disabled:i=!1})=>{const[l,c]=f.useState(!1),u=()=>{i||c(!0)},d=()=>{c(!1)},h=b=>{const y=Array.isArray(b)?b[0]:b;y!=null&&y.url&&n(m.pick(y,["url","id"])),c(!1)},g=()=>{n({url:"",id:""})};return t.jsxs("div",{className:`w-full ${a}`,children:[s?t.jsxs("div",{className:"relative border rounded-md overflow-hidden",children:[t.jsx("img",{onClick:u,src:s,alt:"Selected image",className:"w-full h-auto bg-gray-300 object-contain max-h-[100px]"}),t.jsxs("div",{className:"absolute top-2 right-2 flex gap-2",children:[t.jsx(o.Button,{type:"button",variant:"destructive",size:"icon",className:"h-8 w-8 rounded-full bg-white/80 text-red-500 hover:bg-white/90",onClick:g,disabled:i,children:t.jsx(E.Trash2,{className:"h-4 w-4"})}),t.jsx(o.Button,{type:"button",variant:"secondary",size:"icon",className:"h-8 w-8 rounded-full bg-white/80 hover:bg-white/90",onClick:u,disabled:i,children:t.jsx(E.ImageIcon,{className:"h-4 w-4"})})]})]}):t.jsx("div",{className:`flex items-center justify-center border border-dashed rounded-md p-6 cursor-pointer ${i?"opacity-50 cursor-not-allowed":"hover:border-gray-400"}`,onClick:u,children:t.jsxs("div",{className:"flex flex-col items-center gap-2",children:[t.jsx(E.ImageIcon,{className:"h-10 w-10 text-gray-400"}),t.jsx("p",{className:"text-sm text-gray-500",children:r})]})}),t.jsx(o.Dialog,{open:l,onOpenChange:c,children:t.jsxs(o.DialogContent,{className:"w-full max-w-7xl h-fit p-0 overflow-hidden",children:[t.jsxs(o.DialogHeader,{className:"px-4 py-2 border-b hidden",children:[t.jsx(o.DialogTitle,{children:"Select Image"}),t.jsx(o.Button,{type:"button",variant:"ghost",size:"icon",className:"absolute right-4 top-2",onClick:d,children:t.jsx(E.X,{className:"h-4 w-4"})})]}),t.jsx("div",{className:"flex-1 p-4 h-full",children:t.jsx(Ya,{close:d,onSelect:h,mode:"image",assetId:e})})]})})]})},Ic=()=>{const{user:e,logout:s}=Ue(),n=e==null?void 0:e.accessToken;return f.useCallback(async({url:a,method:r="GET",body:i={},headers:l={}})=>{if(!n)throw new Error("No auth token");if(!a)throw new Error("URL is required");try{const c=await fetch(a,{method:r,headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`,...l},body:JSON.stringify(i)});if(c.status===401)return console.log("Session expired",c),await s(),null;if(c.status===400)throw new Error((await c.json()).error);return await c.json()}catch(c){throw console.log("Something went wrong",c),c}},[n,s])};class _c{constructor(s){As(this,"client");As(this,"channel",null);this.client=s}listenEvent(s,n){var a;(a=this.channel)==null||a.on("broadcast",{event:s},({payload:r})=>{n(r)}).subscribe()}async joinPage(s,n){const a=`PAGE:${s}`;return this.channel&&(await this.channel.untrack({userId:n}),await this.channel.unsubscribe()),this.channel=this.client.channel(a,{config:{presence:{key:n}}}),new Promise(r=>{var i;(i=this.channel)==null||i.on("presence",{event:"sync"},()=>{const l=this.getOnlineUsers();l.length>0?l.length===1&&l.includes(n)?r(!0):r(!1):r(!0)}).subscribe(async l=>{var c;l==="SUBSCRIBED"&&await((c=this.channel)==null?void 0:c.track({userId:n,online_at:new Date}))})})}async leavePage(){this.channel&&await this.channel.untrack()}async requestTakeOver(s,n){return new Promise(a=>{var r;(r=this.channel)==null||r.send({type:"broadcast",event:"TAKE_OVER_REQUESTED",payload:{pageId:s,requesterUserId:n,userId:n}}).then(()=>{a()})})}acceptTakeOver(s,n){return new Promise(a=>{var r;(r=this.channel)==null||r.send({type:"broadcast",event:"TAKE_OVER_REQUEST_ACCEPTED",payload:{pageId:s,userId:n}}).then(()=>{this.leavePage(),a()})})}rejectTakeOver(s,n){return new Promise(a=>{var r;(r=this.channel)==null||r.send({type:"broadcast",event:"TAKE_OVER_REQUEST_REJECTED",payload:{pageId:s,userId:n}}).then(()=>{a()})})}getOnlineUsers(){var s;return Object.keys(((s=this.channel)==null?void 0:s.presenceState())||{})}}if(typeof window>"u")throw new Error("@chaibuilder/pages is not available on the server");exports.$TRACK=nn;exports.ChaiBuilderPages=jc;exports.ChaiBuilderPagesRealtime=_c;exports.Dynamic=xo;exports.For=ql;exports.ImagePicker=Ja;exports.Index=zl;exports.LanguageSwitcher=sn;exports.Match=Hl;exports.NestedPathSelector=We;exports.PermissionChecker=Ge;exports.Portal=go;exports.Show=$l;exports.SmartJsonInput=ia;exports.Switch=Vl;exports.addEventListener=Na;exports.batch=El;exports.className=Ea;exports.clearDelegatedEvents=ao;exports.convertRemToPixels=ac;exports.createComponent=ln;exports.createComputed=ma;exports.createContext=kl;exports.createEffect=an;exports.createMemo=Be;exports.createRenderEffect=Je;exports.createRoot=Ye;exports.createSignal=Se;exports.createUniqueId=Fl;exports.delegateEvents=Sa;exports.deleteNestedDataByPath=_t;exports.displayValue=Xo;exports.getMutationStatusColor=Yo;exports.getPreferredColorScheme=rc;exports.getQueryStatusColor=Wo;exports.getQueryStatusColorByLabel=Jo;exports.getQueryStatusLabel=Ko;exports.getSidedProp=Qo;exports.insert=ys;exports.mergeProps=on;exports.mutationSortFns=nc;exports.on=Nl;exports.onCleanup=Et;exports.onMount=ha;exports.registerLoginComponent=al;exports.serialize=$a;exports.setAttribute=ps;exports.sortFns=tc;exports.splitProps=ja;exports.spread=Ca;exports.stringify=Ho;exports.template=no;exports.untrack=Ae;exports.updateNestedDataByPath=It;exports.use=Aa;exports.useActivePage=At;exports.useBuilderPageData=Qs;exports.useChaiAuth=Ue;exports.useChaiFetch=Ic;exports.useChaiUserInfo=et;exports.useContext=Ll;exports.useCurrentPage=Te;exports.useFallbackLang=Ks;exports.useFetch=J;exports.useGotoPage=Wa;exports.useLanguagePages=Ke;exports.usePageTypes=Pe;exports.useTransition=Pl;exports.useUpdateActivePageMetadata=vc;exports.useUserRoleAndPermissions=aa;exports.useWebsitePages=Zt;exports.useWebsiteSetting=Ze;
|