@chaibuilder/pages 0.8.2 → 0.8.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,6 @@
1
+ "use strict";var pr=Object.defineProperty;var En=e=>{throw TypeError(e)};var yr=(e,s,n)=>s in e?pr(e,s,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[s]=n;var Gt=(e,s,n)=>yr(e,typeof s!="symbol"?s+"":s,n),Nn=(e,s,n)=>s.has(e)||En("Cannot "+n);var ae=(e,s,n)=>(Nn(e,s,"read from private field"),n?n.call(e):s.get(e)),pe=(e,s,n)=>s.has(e)?En("Cannot add the same private member more than once"):s instanceof WeakSet?s.add(e):s.set(e,n),xe=(e,s,n,a)=>(Nn(e,s,"write to private field"),a?a.call(e,n):s.set(e,n),n);const t=require("react/jsx-runtime"),f=require("lodash-es"),g=require("react"),we=require("jotai"),R=require("@tanstack/react-query"),J=require("sonner"),F=require("@chaibuilder/sdk"),c=require("@chaibuilder/sdk/ui"),_t=require("date-fns"),w=require("lucide-react"),Qn=require("@chaibuilder/runtime"),ms=require("zod"),jr=require("react-dropzone"),vr=require("@chaibuilder/sdk/web-blocks");function br(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 Se=br(g),Te={ab:"Abkhazian",aa:"Afar",af:"Afrikaans",ak:"Akan",sq:"Albanian",am:"Amharic",ar:"Arabic",an:"Aragonese",hy:"Armenian",as:"Assamese",av:"Avaric",ae:"Avestan",ay:"Aymara",az:"Azerbaijani",bm:"Bambara",ba:"Bashkir",eu:"Basque",be:"Belarusian",bn:"Bengali",bh:"Bihari",bi:"Bislama",bs:"Bosnian",br:"Breton",bg:"Bulgarian",my:"Burmese",ca:"Catalan",ch:"Chamorro",ce:"Chechen",ny:"Chichewa",zh:"Chinese","zh-Hans":"Chinese (Simplified)","zh-Hant":"Chinese (Traditional)",cv:"Chuvash",kw:"Cornish",co:"Corsican",cr:"Cree",hr:"Croatian",cs:"Czech",da:"Danish",dv:"Maldivian",nl:"Dutch",dz:"Dzongkha",en:"English",eo:"Esperanto",et:"Estonian",ee:"Ewe",fo:"Faroese",fj:"Fijian",fi:"Finnish",fr:"French",ff:"Fula, Pular",gl:"Galician",gd:"Gaelic (Scottish)",gv:"Manx",ka:"Georgian",de:"German",el:"Greek",kl:"Kalaallisut",gn:"Guarani",gu:"Gujarati",ht:"Haitian Creole",ha:"Hausa",he:"Hebrew",hz:"Herero",hi:"Hindi",ho:"Hiri Motu",hu:"Hungarian",is:"Icelandic",io:"Ido",ig:"Igbo",id:"Indonesian",ia:"Interlingua",ie:"Interlingue",iu:"Inuktitut",ik:"Inupiak",ga:"Irish",it:"Italian",ja:"Japanese",jv:"Javanese",kn:"Kannada",kr:"Kanuri",ks:"Kashmiri",kk:"Kazakh",km:"Khmer",ki:"Kikuyu",rw:"Kinyarwanda",rn:"Kirundi",ky:"Kyrgyz",kv:"Komi",kg:"Kongo",ko:"Korean",ku:"Kurdish",kj:"Kwanyama",lo:"Lao",la:"Latin",lv:"Latvian",li:"Limburgish",ln:"Lingala",lt:"Lithuanian",lu:"Luga-Katanga",lg:"Luganda, Ganda",lb:"Luxembourgish",mk:"Macedonian",mg:"Malagasy",ms:"Malay",ml:"Malayalam",mt:"Maltese",mi:"Maori",mr:"Marathi",mh:"Marshallese",mo:"Moldavian",mn:"Mongolian",na:"Nauru",nv:"Navajo",ng:"Ndonga",nd:"Northern Ndebele",ne:"Nepali",no:"Norwegian",nb:"Norwegian bokmål",nn:"Norwegian nynorsk",ii:"Sichuan Yi",oc:"Occitan",oj:"Ojibwe",cu:"Old Church Slavonic",or:"Oriya",om:"Oromo",os:"Ossetian",pi:"Pāli",ps:"Pashto, Pushto",fa:"Persian (Farsi)",pl:"Polish",pt:"Portuguese",pa:"Punjabi (Eastern)",qu:"Quechua",rm:"Romansh",ro:"Romanian",ru:"Russian",se:"Sami",sm:"Samoan",sg:"Sango",sa:"Sanskrit",sr:"Serbian",sh:"Serbo-Croatian",st:"Sesotho",tn:"Setswana",sn:"Shona",sd:"Sindhi",si:"Sinhalese",ss:"Swati",sk:"Slovak",sl:"Slovenian",so:"Somali",nr:"Southern Ndebele",es:"Spanish",su:"Sundanese",sw:"Swahili (Kiswahili)",sv:"Swedish",tl:"Tagalog",ty:"Tahitian",tg:"Tajik",ta:"Tamil",tt:"Tatar",te:"Telugu",th:"Thai",bo:"Tibetan",ti:"Tigrinya",to:"Tonga",ts:"Tsonga",tr:"Turkish",tk:"Turkmen",tw:"Twi",ug:"Uyghur",uk:"Ukrainian",ur:"Urdu",uz:"Uzbek",ve:"Venda",vi:"Vietnamese",vo:"Volapük",wa:"Wallon",cy:"Welsh",wo:"Wolof",fy:"Western Frisian",xh:"Xhosa",yi:"Yiddish",yo:"Yoruba",za:"Zhuang, Chuang",zu:"Zulu"},I={GENERATE_SEO_FIELD:"GENERATE_SEO_FIELD",UPDATE_PAGE_METADATA:"UPDATE_PAGE_METADATA",GET_BLOCK_ASYNC_PROPS:"GET_BLOCK_ASYNC_PROPS",ASK_AI:"ASK_AI",GET_DRAFT_PAGE:"GET_DRAFT_PAGE",CREATE_PAGE:"CREATE_PAGE",UPDATE_PAGE:"UPDATE_PAGE",DELETE_PAGE:"DELETE_PAGE",DUPLICATE_PAGE:"DUPLICATE_PAGE",CHANGE_SLUG:"CHANGE_SLUG",TAKE_OFFLINE:"TAKE_OFFLINE",PUBLISH_PAGE:"PUBLISH_PAGE",PUBLISH_CHANGES:"PUBLISH_CHANGES",ADD_NEW_LANGUAGE:"ADD_NEW_LANGUAGE",EDIT_LANGUAGE:"EDIT_LANGUAGE",DELETE_LANGUAGE:"DELETE_LANGUAGE",GET_CHANGES:"GET_CHANGES",GET_SERVER_BLOCK:"GET_SERVER_BLOCK",GET_LANGUAGE_PAGES:"GET_LANGUAGE_PAGES",GET_PROJECT_PAGES:"GET_PROJECT_PAGES",GET_WEBSITE_PAGES:"GET_WEBSITE_PAGES",UPDATE_WEBSITE_SETTINGS:"UPDATE_WEBSITE_SETTINGS",GET_COLLECTIONS:"GET_COLLECTIONS",GET_PAGE_TYPES:"GET_PAGE_TYPES",SEARCH_PAGES:"SEARCH_PAGES",GET_WEBSITE_DRAFT_SETTINGS:"GET_WEBSITE_DRAFT_SETTINGS",AI_CONTEXT:"AI_CONTEXT",GET_WEBSITE_DATA:"GET_WEBSITE_DATA",UPDATE_WEBSITE_DATA:"UPDATE_WEBSITE_DATA",GET_CHAI_USER:"GET_CHAI_USER",RELEASE_LOCK:"RELEASE_LOCK",GET_SEO_FIELDS:"GET_SEO_FIELDS",GET_BUILDER_PAGE_DATA:"GET_BUILDER_PAGE_DATA",GET_PAGE_REVISIONS:"GET_PAGE_REVISIONS",DELETE_PAGE_REVISION:"DELETE_PAGE_REVISION",RESTORE_PAGE_REVISION:"RESTORE_PAGE_REVISION",GET_ROLE_AND_PERMISSIONS:"GET_ROLE_AND_PERMISSIONS",UPSERT_LIBRARY_ITEM:"UPSERT_LIBRARY_ITEM",GET_LIBRARIES:"GET_LIBRARIES",GET_LIBRARY_ITEM:"GET_LIBRARY_ITEM",GET_LIBRARY_ITEMS:"GET_LIBRARY_ITEMS",DELETE_LIBRARY_ITEM:"DELETE_LIBRARY_ITEM",MARK_AS_TEMPLATE:"MARK_AS_TEMPLATE",UNMARK_AS_TEMPLATE:"UNMARK_AS_TEMPLATE",GET_TEMPLATES_BY_TYPE:"GET_TEMPLATES_BY_TYPE",GET_DYNAMIC_PAGES:"GET_DYNAMIC_PAGES",UPLOAD_ASSET:"UPLOAD_ASSET",DELETE_ASSET:"DELETE_ASSET",UPDATE_ASSET:"UPDATE_ASSET",GET_ASSETS:"GET_ASSETS",GET_ASSET:"GET_ASSET"},W="chaibuilder";let Sr=0;function Cn(e,s){const n=`atom${++Sr}`,a={toString(){return n}};return typeof e=="function"?a.read=e:(a.init=e,a.read=wr,a.write=Er),s&&(a.write=s),a}function wr(e){return e(this)}function Er(e,s,n){return s(this,typeof n=="function"?n(e(this)):n)}const Nr=Symbol(""),Cr=e=>typeof(e==null?void 0:e.then)=="function";function Ar(e=()=>{try{return window.localStorage}catch{return}},s){var n;let a,r;const i={getItem:(u,d)=>{var h,m;const b=y=>{if(y=y||"",a!==y){try{r=JSON.parse(y,s==null?void 0:s.reviver)}catch{return d}a=y}return r},j=(m=(h=e())==null?void 0:h.getItem(u))!=null?m:null;return Cr(j)?j.then(b):b(j)},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,m)=>u(d,b=>{let j;try{j=JSON.parse(b||"")}catch{j=m}h(j)});let o;try{o=(n=e())==null?void 0:n.subscribe}catch{}return!o&&typeof window<"u"&&typeof window.addEventListener=="function"&&window.Storage&&(o=(u,d)=>{if(!(e()instanceof window.Storage))return()=>{};const h=m=>{m.storageArea===e()&&m.key===u&&d(m.newValue)};return window.addEventListener("storage",h),()=>{window.removeEventListener("storage",h)}}),o&&(i.subscribe=l(o)),i}const Tr=Ar();function Wn(e,s,n=Tr,a){const r=Cn(s);return r.onMount=l=>{l(n.getItem(e,s));let o;return n.subscribe&&(o=n.subscribe(e,l,s)),o},Cn(l=>l(r),(l,o,u)=>{const d=typeof u=="function"?u(l(r)):u;return d===Nr?(o(r,s),n.removeItem(e)):d instanceof Promise?d.then(h=>(o(r,h),n.setItem(e,h))):(o(r,d),n.setItem(e,d))})}localStorage.removeItem("_chai_user");localStorage.removeItem("__chai__user");const Yn="__logged_in_user",kr=Wn(Yn,null),Ue=()=>{const[e,s]=we.useAtom(kr),n=g.useCallback(()=>{s(null),localStorage.removeItem(Yn)},[s]),a=g.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}},tn=async(e,s,n={})=>await fetch(e,{method:"POST",headers:{"Content-Type":"application/json",...n},body:JSON.stringify(s)}),Jn=()=>{const{user:e}=Ue(),n=qe("getAccessToken",async()=>(e==null?void 0:e.accessToken)||"");return{getAccessToken:g.useCallback(async()=>{try{return await n()}catch{return""}},[n])}},ee=()=>{const{logout:e}=Ue(),s=R.useQueryClient(),{getAccessToken:n}=Jn();return g.useCallback(async(a,r,i={})=>{const l=await n();if(!l)return null;try{const o=f.get(r,"action","").toLowerCase(),u=await tn(a+(o?`?action=${o}`:""),r,{...i,Authorization:`Bearer ${l}`});if(u.status===401)return console.log("401 Response",u),s.invalidateQueries({queryKey:[W]}),e(),window.location.reload(),null;if(!u.ok){const d=await u.json();throw console.error(`API Error (${u.status}):`,d),{status:u.status,statusText:u.statusText,...d,message:d.error||d.message||`Server error: ${u.status}`}}return await u.json()}catch(o){throw console.error("API request failed:",r,o),o}},[e,s,n])},Xn=()=>{const e=oe(),s=R.useQueryClient(),n=ee();return R.useMutation({mutationFn:async a=>n(e,{action:I.RELEASE_LOCK,data:a}),onSuccess:()=>{s.invalidateQueries({queryKey:[W,I.GET_DRAFT_PAGE]})}})},Zn=()=>{const e=oe(),s=R.useQueryClient(),n=ee();return R.useMutation({mutationFn:async a=>n(e,{action:I.UPDATE_WEBSITE_SETTINGS,data:a}),onSuccess:(a,r)=>{var i;s.invalidateQueries({queryKey:[W,I.GET_WEBSITE_DRAFT_SETTINGS]}),(i=r==null?void 0:r.settings)!=null&&i.theme||J.toast.success("Website settings updated successfully.")},onError:a=>{J.toast.error("Failed to update website settings",{description:a.message})}})},Pr=()=>{const e=oe(),s=R.useQueryClient(),n=ee();return R.useMutation({mutationFn:async a=>n(e,{action:I.UPDATE_WEBSITE_DATA,data:a}),onSuccess:()=>{s.invalidateQueries({queryKey:[W,I.GET_WEBSITE_DATA]}),J.toast.success("Website data updated successfully.")},onError:a=>{J.toast.error("Failed to update website data",{description:a.message})}})};function _e(){const[e,s]=g.useState(new URLSearchParams(window.location.search));return g.useEffect(()=>{const n=()=>{s(new URLSearchParams(window.location.search))};return window.addEventListener("popstate",n),()=>{window.removeEventListener("popstate",n)}},[]),[e,s]}const _r=we.atom({}),ea=()=>we.useAtom(_r),Ir=()=>{const[e]=_e(),s=e.get("page"),n=g.useRef(""),{mutate:a}=Xn();g.useEffect(()=>{!f.isEmpty(n.current)&&s!==n.current&&a({id:n.current}),n.current=s},[s,a,n])},qe=(e,s)=>{const[n]=ea();return g.useMemo(()=>f.get(n,e,s),[n,e,s])},oe=()=>qe("apiUrl","/chai/api"),Cs=()=>qe("usersApiUrl","/chai/users"),rs=()=>qe("assetsApiUrl","/chai/assets"),ta=()=>qe("realtimeInstance",null),Oe=e=>{const s=oe(),[n]=_e(),a=e??n.get("page"),r=ee();return R.useQuery({queryKey:[W,I.GET_LANGUAGE_PAGES,a],initialData:[],queryFn:async()=>{if(!a)return null;const i=await r(s,{action:I.GET_LANGUAGE_PAGES,data:{id:a}});return f.reverse(f.sortBy(i,"primaryPage"))},enabled:!!a})},He=()=>{const e=oe(),s=ee();return R.useQuery({queryKey:[W,I.GET_WEBSITE_DRAFT_SETTINGS],initialData:{theme:{},fallbackLang:"en",languages:[]},queryFn:async()=>s(e,{action:I.GET_WEBSITE_DRAFT_SETTINGS,data:{draft:!0}})})},sa=e=>{const{fallbackLang:s}=F.useLanguages(),{data:n}=He(),{data:a,isFetching:r}=Oe(),i=g.useMemo(()=>{const l={[s]:!0};return f.each(f.get(n,"languages"),o=>{const u=f.find(a,{lang:o});l[o]=!!u}),l},[s,a,n]);return r||f.isEmpty(e)||e&&i[e]},sn=()=>{const e=R.useQueryClient(),{data:s}=R.useQuery({queryKey:[W,I.AI_CONTEXT],initialData:"",queryFn:()=>"",staleTime:0});return{setAiContext:g.useCallback(a=>{e.setQueryData([W,I.AI_CONTEXT],a)},[e]),aiContext:s}},Lr=we.atom(null),na=()=>we.useAtom(Lr),nn=()=>{const[e]=na();return(e==null?void 0:e.slug)||""};function Dr(e,s){const[n,a]=g.useState(e);return g.useEffect(()=>{const r=setTimeout(()=>a(e),s);return()=>clearTimeout(r)},[e,s]),n}const Br=({query:e,uuid:s})=>{const{selectedLang:n,fallbackLang:a}=F.useLanguages(),{data:r}=Pe(),i=r==null?void 0:r.pageType,l=oe(),o=ee(),{data:u,isFetching:d}=R.useQuery({queryKey:[I.GET_DYNAMIC_PAGES,e,i,s],initialData:[],queryFn:async()=>await o(l,{action:I.GET_DYNAMIC_PAGES,data:{query:e,pageType:i,uuid:s}})||[],enabled:!!i}),h=g.useMemo(()=>n===""?u.filter(m=>m.lang===""||m.lang===a):u.filter(m=>m.lang===n),[n,a,u]);return{allLangPages:u,data:h,isFetching:d}},aa=()=>{const{selectedLang:e,fallbackLang:s}=F.useLanguages(),[n,a]=na(),[r,i]=g.useState(""),l=Dr(r,500),{allLangPages:o,data:u,isFetching:d}=Br({query:l}),h=g.useCallback(j=>a(j),[a]),m=g.useCallback(j=>i(j),[i]),b=g.useCallback(()=>{if(!n)return;const j=!(n!=null&&n.primaryPage),y=e.length===0,p=j?n==null?void 0:n.id:n==null?void 0:n.primaryPage,S=o.filter(C=>(C==null?void 0:C.primaryPage)===p||C.id===p).find(C=>y?C.lang===e||C.lang===s:C.lang===e);a(S||n)},[n,e,o,a,s]);return{isPending:d,dynamicPage:n,searchQuery:r,selectedLang:e,dynamicPages:u,allLangPages:o,updateDynamicPage:h,updateSearchQuery:m,onChangeLanguage:b}},Qe=()=>{const{data:e}=He();return g.useMemo(()=>(e==null?void 0:e.fallbackLang)||"en",[e])},ot=()=>{const e=ee(),s=oe();return R.useQuery({queryKey:[W,I.GET_WEBSITE_PAGES],staleTime:1e3*60*5,queryFn:async()=>e(s,{action:I.GET_WEBSITE_PAGES})||[],placeholderData:n=>n||[]})},Gr=e=>{const s=ee(),n=oe(),a=Qe();return R.useQuery({queryKey:[W,I.GET_WEBSITE_PAGES,e,a],staleTime:1e3*60*5,enabled:!!e&&a!==e,queryFn:async()=>{const r=await s(n,{action:I.GET_WEBSITE_PAGES,data:{lang:e}})||[];return f.keyBy(f.map(r,i=>({...i,lang:e})),"primaryPage")},placeholderData:r=>r||{}})},Mr=we.atom({lastSaved:void 0}),As=()=>we.useAtom(Mr),Pe=()=>{const[e]=_e(),s=e.get("page"),[n]=ra(),{data:a,isFetching:r}=ot();return{data:g.useMemo(()=>({...f.find(a,{id:s})||{},metadata:n}),[a,s,n]),isFetching:r}},tt=()=>{const[e]=_e(),s=e.get("lang")??"",{data:n,isFetching:a}=Oe();return{data:g.useMemo(()=>f.find(n,{lang:s})||{},[n,s]),isFetching:a}},Rr=we.atom({}),ra=()=>we.useAtom(Rr),ia=()=>{const{data:e}=tt(),s=nn(),n=e==null?void 0:e.slug,a=n?window.location.origin+(n.endsWith("/")?n.slice(0,-1):n):window.location.origin;return s?a+s:a},ct=e=>{const s=Cs(),n=ee();return R.useQuery({queryKey:[W,"chaiUserInfo",e],queryFn:async()=>{const r=await n(s,{action:I.GET_CHAI_USER,data:{userId:e}});return{...r,name:r.name||r.email}},enabled:!f.isEmpty(e)})},Ur=we.atom(void 0),an=we.atom({status:"checking",requestedBy:"",lockedBy:"",isTakeOverRequested:!1}),la=we.atom(""),ut=()=>{const[e]=_e(),s=e.get("page"),{user:n}=Ue(),[a,r]=we.useAtom(Ur),[i]=we.useAtom(an),l=F.useChaiFeatureFlag("realtime-page-lock"),[o,u]=we.useAtom(la);return g.useMemo(()=>({pageLock:i,isLocked:l?s&&i.status==="locked":s&&(n==null?void 0:n.id)!==a,lockingStatus:o,currentEditor:a,setCurrentEditor:d=>r(d),setLockingStatus:d=>u(d)}),[l,s,i,n==null?void 0:n.id,a,r,o,u])},Fr=()=>{const e=ta(),{data:s}=Pe(),{user:n}=Ue(),a=s==null?void 0:s.id,[r,i]=we.useAtom(an),[,l]=we.useAtom(la),o=g.useRef(!1),u=g.useRef(r),d=F.useChaiFeatureFlag("realtime-page-lock");return g.useEffect(()=>{u.current=r},[r]),g.useEffect(()=>{if(!(!d||!e||!a||!(n!=null&&n.id)))return()=>{o.current=!1,u.current={status:"checking",requestedBy:"",lockedBy:"",isTakeOverRequested:!1},i(u.current),l(""),e==null||e.leavePage(a,n==null?void 0:n.id)}},[a,e,n==null?void 0:n.id,d]),g.useEffect(()=>{if(!d||!e||!a||!(n!=null&&n.id)||o.current)return;o.current=!0;async function h(){e==null||e.joinPage(a,n==null?void 0:n.id,(m,b)=>{var j,y;switch(m){case"PAGE_LOCKED":i({...u==null?void 0:u.current,status:"locked",requestedBy:"",lockedBy:b==null?void 0:b.lockedBy});break;case"USER_JOINED":{if(((j=u==null?void 0:u.current)==null?void 0:j.status)==="editing")return;((y=u==null?void 0:u.current)==null?void 0:y.status)==="locked"&&l("can_edit_now"),i({...u==null?void 0:u.current,status:"editing",requestedBy:"",lockedBy:""});break}case"TAKE_OVER_REQUESTED":if((b==null?void 0:b.requestedBy)===(n==null?void 0:n.id))return;i({...u==null?void 0:u.current,requestedBy:b==null?void 0:b.requestedBy});break;case"TAKE_OVER_REQUEST_ACCEPTED":l("take_over_request_accepted"),J.toast.success("Your Page Take Over Request Accepted",{position:"top-center"}),i({...u==null?void 0:u.current,status:"checking",requestedBy:"",isTakeOverRequested:!1});break;case"TAKE_OVER_REQUEST_REJECTED":l("take_over_request_rejected"),i({...u==null?void 0:u.current,isTakeOverRequested:!1});break}})}h()},[a,d,o.current]),r==null?void 0:r.status},oa=()=>{const e=ta(),{data:s}=Pe(),{user:n}=Ue(),a=s==null?void 0:s.id,[r,i]=we.useAtom(an),{saveState:l,savePageAsync:o}=F.useSavePage(),u=g.useCallback(()=>{!e||!a||!(n!=null&&n.id)||(i({...r,isTakeOverRequested:!0}),e==null||e.sendEvent("TAKE_OVER_REQUESTED",{pageId:a,requestedBy:n==null?void 0:n.id}))},[e,a,n==null?void 0:n.id,i,r]),d=g.useCallback(async()=>{!e||!a||!(n!=null&&n.id)||(l!=="SAVED"&&await o(),e==null||e.sendEvent("TAKE_OVER_REQUEST_ACCEPTED",{pageId:a,userId:n==null?void 0:n.id}),i({requestedBy:"",status:"locked",isTakeOverRequested:!1,lockedBy:r==null?void 0:r.requestedBy}))},[a,e,n==null?void 0:n.id,i,o,l,r]),h=g.useCallback(()=>{!e||!a||!(n!=null&&n.id)||(e==null||e.sendEvent("TAKE_OVER_REQUEST_REJECTED",{pageId:a,userId:n==null?void 0:n.id}),i({...r,status:"editing",requestedBy:"",isTakeOverRequested:!1}))},[a,e,n==null?void 0:n.id,i,r]);return{pageLock:r,requestTakeOver:u,acceptTakeOver:d,rejectTakeOver:h}},ca=()=>{const[e]=_e(),s=e.get("page"),n=oe(),{setAiContext:a}=sn(),{setCurrentEditor:r}=ut(),[,i]=As(),[,l]=ra(),o=ee();return R.useQuery({queryKey:[W,I.GET_DRAFT_PAGE,s],staleTime:1/0,gcTime:1/0,queryFn:async()=>{r("");const u=await o(n,{action:I.GET_DRAFT_PAGE,data:{id:s,draft:!0}});r(u.currentEditor);const d=u.blocks??[],h=f.find(d,{_type:"@chai/ai-context"});return a(f.get(h,"_value","")||""),i(m=>({...m,lastSaved:u.lastSaved})),l(f.get(u,"metadata",{})),d},enabled:!!s})},rn=()=>{const{data:e}=Pe(),{data:s}=tt(),n=oe(),a=ee(),r=Qe(),i=nn();return R.useQuery({queryKey:[W,I.GET_BUILDER_PAGE_DATA,s==null?void 0:s.id,i],initialData:{},queryFn:async()=>a(n,{action:I.GET_BUILDER_PAGE_DATA,data:{pageType:e==null?void 0:e.pageType,lang:(s==null?void 0:s.lang)||r,dynamic:e==null?void 0:e.dynamic,pageProps:{slug:(s==null?void 0:s.slug)+i,searchParams:{},pageType:s==null?void 0:s.pageType,fallbackLang:r,lastSaved:s.lastSaved,pageId:e.id,primaryPageId:s.primaryPage||e.id,pageBaseSlug:s==null?void 0:s.slug,dynamic:e==null?void 0:e.dynamic,languagePageId:s.id}}}),enabled:!!(s!=null&&s.pageType)})},Or=({currentEditor:e})=>{const{user:s}=Ue(),{data:n}=ct(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(c.Tooltip,{children:[t.jsx(c.TooltipTrigger,{children:t.jsx(w.LockIcon,{className:"h-3 w-3"})}),t.jsx(c.TooltipContent,{children:t.jsxs("p",{children:[n.name," is editing"]})})]})})},qr=({userId:e})=>{const{data:s}=ct(e);return(s==null?void 0:s.name)||"Unknown"};function $r({avatar:e,name:s,email:n,lastSaved:a,onTakeOver:r,realtimePageLockEnabled:i,isRequestRejected:l,isFetchingUserInfo:o}){const[u,d]=g.useState(!1),[h,m]=g.useState(!1),b=()=>{d(!0),setTimeout(()=>{d(!1)},15e3),m(!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(c.Card,{className:"mx-auto w-full max-w-md",children:[t.jsx(c.CardHeader,{className:"space-y-1",children:t.jsxs(c.CardTitle,{className:"flex items-center gap-2 text-xl",children:[t.jsx(w.LockKeyhole,{className:"h-8 w-8 rounded-md bg-sky-500/20 p-1.5 text-sky-500"}),"Page is locked for editing"]})}),t.jsx(c.CardContent,{className:"w-md grid w-full pt-2",children:t.jsxs("div",{children:[t.jsxs("div",{className:"relative mx-auto flex w-96 items-center space-x-4 rounded-md border border-green-500 px-2 pb-2 pt-4",children:[t.jsx("div",{className:"absolute -top-2.5 left-3 w-max rounded-full bg-green-500 px-3 py-1 text-xs font-medium leading-3 text-white",children:"Locked By"}),e&&!o?t.jsx("img",{src:e,alt:s,className:"h-14 w-14 rounded-full border border-gray-300"}):t.jsx(w.UserIcon,{className:"h-14 w-14 flex-shrink-0 rounded-full bg-gradient-to-br from-purple-400 to-pink-500 p-2 text-white"}),t.jsxs("div",{className:o?"space-y-1.5":"space-y-0",children:[o?t.jsx(c.Skeleton,{className:"h-4 w-40 rounded"}):t.jsx("span",{className:"truncate font-medium text-black",children:s}),n&&!o?t.jsx("p",{className:"truncate text-sm text-muted-foreground",children:n}):t.jsx(c.Skeleton,{className:"h-4 w-60 rounded"}),a&&!o?t.jsxs("p",{className:"text-sm text-muted-foreground",children:["Last saved:"," ",_t.formatDistanceToNow(new Date(a),{addSuffix:!0})]}):t.jsx(c.Skeleton,{className:"h-4 w-40 rounded"})]})]}),t.jsx("div",{className:"mt-4 text-sm",children:t.jsxs("p",{className:"py-4 text-center text-gray-600",children:["This page is currently being edited by ",t.jsx("span",{className:"font-bold",children:s}),".",t.jsx("br",{}),i&&t.jsxs(t.Fragment,{children:[" ",t.jsx("br",{})," You can either wait until they finish editing or"," ",i?"request to":""," take over the page."]})]})}),l&&t.jsxs("div",{className:"mt-4 flex w-full items-center justify-center gap-x-2 rounded border border-red-500 bg-red-50 p-2 text-center font-medium text-red-500",children:[t.jsx(w.Info,{className:"h-5 w-5"})," Page take over request is rejected"]})]})}),t.jsx(c.CardFooter,{children:i?t.jsxs(c.Button,{disabled:u,onClick:b,className:"w-full",variant:"destructive",children:[t.jsx(w.KeyIcon,{className:"h-5 w-5"}),u?"Page take is requested.":l?"Request take over again":"Request take over"]}):t.jsxs(c.AlertDialog,{open:h,onOpenChange:m,children:[t.jsx(c.AlertDialogTrigger,{asChild:!0,children:t.jsxs("span",{className:"flex flex-col items-center",children:[t.jsx(c.Button,{className:"w-full",variant:"destructive",children:"Take over"}),t.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:"If you need to edit, you can take over the lock, but be aware that the other user might lose unsaved changes."})]})}),t.jsxs(c.AlertDialogContent,{className:"z-[99]",children:[t.jsxs(c.AlertDialogHeader,{children:[t.jsx(c.AlertDialogTitle,{children:"Are you sure you want to take over?"}),t.jsxs(c.AlertDialogDescription,{children:[t.jsxs("span",{className:"flex items-center space-x-2 text-yellow-500",children:[t.jsx(w.AlertTriangleIcon,{className:"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(c.AlertDialogFooter,{children:[t.jsx(c.AlertDialogCancel,{children:"Cancel"}),t.jsx(c.AlertDialogAction,{onClick:b,children:"Yes, Take Over"})]})]})]})})]})})}const Gs=({isChecking:e,lockingStatus:s,onContinue:n})=>{const a=(s==null?void 0:s.length)>0,{pageLock:r,acceptTakeOver:i,rejectTakeOver:l}=oa(),o=()=>{a?n():i()};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:e?null:t.jsxs(c.Card,{className:"mx-auto w-full max-w-md",children:[t.jsx(c.CardHeader,{className:"space-y-1",children:t.jsxs(c.CardTitle,{className:"flex items-center gap-2 text-xl font-medium",children:[a?t.jsx(w.CheckCircle,{className:"h-6 w-6 text-green-500"}):t.jsx(w.Target,{className:"h-6 w-6 text-green-500"}),a?"You can edit the page now.":"Page take over request"]})}),t.jsx(c.CardContent,{className:"grid gap-4",children:t.jsx("div",{children:a?t.jsx("p",{children:"This page is released by other user you can continue editing now."}):t.jsxs("p",{children:[t.jsxs("b",{children:[" ",t.jsx(qr,{userId:r==null?void 0:r.requestedBy})]})," ","has requested to take over this page.",t.jsx("br",{})," If you accept, your unsaved changes will be saved."]})})}),t.jsxs(c.CardFooter,{className:"flex items-center justify-end gap-2",children:[t.jsx(c.Button,{onClick:o,className:a?"":"bg-green-500 hover:bg-green-600",children:a?t.jsxs(t.Fragment,{children:[t.jsx(w.Edit,{className:"h-5 w-5"})," Continue to edit"]}):t.jsxs(t.Fragment,{children:[t.jsx(w.Check,{className:"h-5 w-5"})," Accept"]})}),!a&&t.jsxs(c.Button,{variant:"outline",onClick:l,children:[t.jsx(w.X,{className:"h-5 w-5"})," Reject"]})]})]})})},zr=()=>{const{pageLock:e,requestTakeOver:s}=oa(),{isLocked:n,currentEditor:a,lockingStatus:r,setLockingStatus:i}=ut(),l=F.useChaiFeatureFlag("realtime-page-lock"),{data:o,isFetching:u}=ct(l?e==null?void 0:e.lockedBy:a),[d]=_e(),h=d.get("page"),{mutate:m}=Xn(),{isFetching:b}=ca(),[j]=As(),y=R.useQueryClient(),p=g.useCallback(()=>{l?s():m({id:h})},[h,m,s,l]);return l&&(e==null?void 0:e.status)==="checking"?t.jsx(Gs,{isChecking:!0,lockingStatus:"",onContinue:()=>{}}):l&&(e!=null&&e.requestedBy)?t.jsx(Gs,{lockingStatus:"",onContinue:()=>{}}):(l?e.status!=="locked":!n||b)?r==="take_over_request_accepted"||r==="can_edit_now"?t.jsx(Gs,{lockingStatus:r,onContinue:()=>{y.invalidateQueries({queryKey:[W,I.GET_DRAFT_PAGE]}),i("")}}):null:t.jsx($r,{...o,isFetchingUserInfo:u,name:(o==null?void 0:o.name)||"Unknown User",email:(o==null?void 0:o.email)||"",lastSaved:(j==null?void 0:j.lastSaved)||"",onTakeOver:p,realtimePageLockEnabled:l,isRequestRejected:r==="take_over_request_rejected"})},Vr=()=>{const[e,s]=_e(),n=e.get("lang"),a=sa(n),{setSelectedLang:r}=F.useLanguages(),i=()=>{const o=new URLSearchParams(window.location.search);o.delete("lang");const u=o.toString(),d=`${window.location.pathname}${u?`?${u}`:""}`;window.history.pushState({},"",d),s(o),r(""),window.dispatchEvent(new PopStateEvent("popstate"))};if(a)return null;const l=f.get(Te,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(c.Card,{className:"mx-auto w-full max-w-md",children:[t.jsx(c.CardHeader,{className:"space-y-1",children:t.jsxs(c.CardTitle,{className:"flex items-center gap-2 text-2xl",children:[t.jsx(w.LockIcon,{className:"h-6 w-6 text-yellow-500"}),'Page missing for "',l,'" language.']})}),t.jsx(c.CardContent,{className:"grid gap-4",children:t.jsxs("div",{children:['Page is not available in the "',l,'" language. Either create the page in the "',l,'" language or switch to the base language.']})}),t.jsx(c.CardFooter,{children:t.jsx(c.Button,{onClick:i,className:"w-full",variant:"destructive",children:"Switch to default language"})})]})})},Kr=e=>{const s=oe(),n=ee();return R.useMutation({mutationFn:async a=>n(s,{action:I.UPSERT_LIBRARY_ITEM,data:a}),onSuccess:a=>{e(a)},onError:a=>{console.error("Error saving block:",a),J.toast.error("Failed to save block",{description:a instanceof Error?a.message:"Unknown error"})}})},Hr=e=>{const s=oe(),n=ee();return R.useQuery({queryKey:[W,"uiBlockDetails",e],enabled:!!e,queryFn:async()=>{if(!e)return null;try{return await n(s,{action:I.GET_LIBRARY_ITEM,data:{id:e}})}catch(a){throw console.error(a),new Error("The block could not be found on the server. It may have been deleted.")}},retry:!1})},Qr=e=>{const s=oe(),n=ee();return R.useMutation({mutationFn:async a=>n(s,{action:I.DELETE_LIBRARY_ITEM,data:{id:a}}),onSuccess:()=>{e()},onError:a=>{console.error("Error deleting block:",a),J.toast.error("Failed to delete block",{description:a instanceof Error?a.message:"Unknown error"})}})},Wr=({blockId:e,libBlockId:s,isOpen:n,onClose:a,blockName:r,trigger:i})=>{const[l,o]=g.useState(!1),u=F.useUpdateBlocksPropsRealtime(),d=Qr(()=>{u([e],{_libBlockId:void 0}),J.toast.success("Block deleted successfully"),o(!1),a()}),h=()=>{o(!0),d.mutate(s)},m=t.jsxs(c.Button,{type:"button",variant:"destructive",size:"sm",onClick:b=>b.preventDefault(),disabled:l,children:[t.jsx(w.Trash2,{className:"h-4 w-4 mr-2"}),"Delete"]});return t.jsxs(c.Popover,{open:n,onOpenChange:b=>!b&&a(),children:[t.jsx(c.PopoverTrigger,{asChild:!0,children:i||m}),t.jsx(c.PopoverContent,{className:"w-72 p-4 z-[9999]",sideOffset:5,align:"center",children:t.jsxs("div",{className:"space-y-3",children:[t.jsx("h4",{className:"font-medium",children:"Delete Block"}),t.jsxs("p",{className:"text-sm",children:["Are you sure you want to delete the block",t.jsxs("span",{className:"font-medium",children:[' "',r,'"']}),"?"]}),t.jsx("p",{className:"text-xs text-muted-foreground",children:"This block will be permanently removed from the library. This action cannot be undone."}),t.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[t.jsx(c.Button,{type:"button",variant:"outline",size:"sm",onClick:a,disabled:l,children:"Cancel"}),t.jsx(c.Button,{type:"button",variant:"destructive",size:"sm",onClick:h,disabled:l,children:l?"Deleting...":"Delete"})]})]})})]})},Yr=({blockId:e,libBlockId:s,blockName:n,size:a="sm",className:r="",close:i})=>{const[l,o]=g.useState(!1);return t.jsx(Wr,{blockId:e,libBlockId:s,isOpen:l,onClose:()=>{o(!1),i()},blockName:n,trigger:t.jsxs(c.Button,{type:"button",variant:"destructive",size:a,className:r,onClick:()=>o(!0),children:[t.jsx(w.Trash2,{className:"h-4 w-4 mr-2"}),"Delete"]})})},Jr=()=>{const e=oe(),s=ee(),n=R.useQueryClient(),{data:a=[],isLoading:r,error:i}=R.useQuery({queryKey:[W,"library-groups"],queryFn:async()=>{try{return await s(e,{action:"GET_LIBRARY_GROUPS"})||[]}catch(u){return console.error("Error fetching library groups:",u),[]}},initialData:[]}),{mutateAsync:l,isPending:o}=R.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:[W,"library-groups"]}),J.toast.success("Group created successfully")},onError:u=>{console.error("Error creating group:",u),J.toast.error("Failed to create group",{description:u instanceof Error?u.message:"Unknown error"})}});return{groups:a,isLoading:r,error:i,createGroup:l,isCreating:o}},Xr=({value:e,onChange:s})=>{const[n,a]=g.useState(!1),[r,i]=g.useState(""),l=g.useRef(null),{groups:o}=Jr(),[u,d]=g.useState([{id:"hero",name:"Hero"},{id:"feature",name:"Feature"},{id:"footer",name:"Footer"},{id:"content",name:"Content"},{id:"testimonial",name:"Testimonial"},{id:"pricing",name:"Pricing"},{id:"login",name:"Login"},{id:"logos",name:"Logos"},{id:"about",name:"About"},{id:"banner",name:"Banner"},{id:"blog",name:"Blog"},{id:"careers",name:"Careers"},{id:"casestudy",name:"Casestudy"},{id:"changelog",name:"Changelog"},{id:"compare",name:"Compare"},{id:"contact",name:"Contact"},{id:"cta",name:"Cta"},{id:"faq",name:"Faq"},{id:"gallery",name:"Gallery"},{id:"integration",name:"Integration"},{id:"list",name:"List"},{id:"navbar",name:"Navbar"},{id:"product",name:"Product"},{id:"signup",name:"Signup"},{id:"stats",name:"Stats"},{id:"team",name:"Team"},{id:"timeline",name:"Timeline"}]),h=g.useMemo(()=>[...o,...u.filter(j=>!o.some(y=>y.id===j.id))],[o,u]),m=()=>{const j=r.trim();if(!j)return;const y={id:j,name:j};d(p=>[...p,y]),s(y.id),i(""),a(!1)};g.useEffect(()=>{n&&l.current&&l.current.focus()},[n]);const b=j=>{j.key==="Enter"&&(j.preventDefault(),m())};return g.useEffect(()=>{e&&!h.some(j=>j.id===e)&&s("")},[e,h,s]),n?t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Input,{ref:l,placeholder:"Enter new group name",value:r,onChange:j=>i(j.target.value),onKeyDown:b}),t.jsxs("div",{className:"flex justify-end gap-2",children:[t.jsx(c.Button,{variant:"outline",size:"sm",onClick:()=>a(!1),children:"Cancel"}),t.jsx(c.Button,{size:"sm",onClick:m,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:j=>s(j.target.value),children:[t.jsx("option",{value:"",children:"Select a group"}),o.length>0&&t.jsx("optgroup",{label:"Library Groups",children:o.map(j=>t.jsx("option",{value:j.id,children:j.name},`lib-${j.id}`))}),u.length>0&&t.jsx("optgroup",{label:"Predefined Groups",children:u.filter(j=>!o.some(y=>y.id===j.id)).map(j=>t.jsx("option",{value:j.id,children:j.name},`local-${j.id}`))})]}),t.jsx(c.Button,{type:"button",size:"icon",variant:"outline",onClick:()=>a(!0),children:t.jsx(w.Plus,{className:"h-4 w-4"})})]})},Zr=10*1024*1024,ei=({value:e,onChange:s})=>{const[n,a]=g.useState(!1),r=g.useRef(null),i=g.useCallback(u=>{var h;const d=(h=u.target.files)==null?void 0:h[0];if(d){if(d.size>Zr){J.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 m=new FileReader;m.onloadend=()=>{s(m.result),a(!1)},m.readAsDataURL(d)}catch(m){console.error("Error reading file:",m),a(!1),J.toast.error("Failed to process image",{description:m instanceof Error?m.message:"Unknown error"})}}},[s]),l=()=>{s(""),r.current&&(r.current.value="")},o=()=>{var u;(u=r.current)==null||u.click()};return t.jsxs("div",{className:"space-y-2",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(c.Input,{type:"file",ref:r,onChange:i,accept:"image/*",className:"hidden"}),t.jsx(c.Button,{type:"button",variant:"outline",onClick:o,disabled:n,className:"w-full",children:n?t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsx("div",{className:"animate-spin h-4 w-4 border-2 border-current border-t-transparent rounded-full"}),"Uploading..."]}):t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsx(w.ImageIcon,{className:"h-4 w-4"}),"Select image"]})}),e&&t.jsx(c.Button,{type:"button",variant:"outline",size:"icon",onClick:l,children:t.jsx(w.X,{className:"h-4 w-4"})})]}),e&&t.jsx("div",{className:"rounded-md max-h-[200px] h-[200px] overflow-hidden border aspect-video",children:t.jsx("img",{src:e,alt:"Preview",className:"w-full h-full object-contain"})})]})},ve={...F.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"},ti=e=>{const{blocks:s,close:n,blockId:a}=e,{getPartailBlocks:r}=F.usePartailBlocksStore(),i=s.find(N=>N._id===a),l=i==null?void 0:i._libBlockId,o=!!l,u=g.useMemo(()=>s.some(N=>N._type==="PartialBlock"||N._type==="GlobalBlock"),[s]),d=g.useMemo(()=>{let N=[];for(const U of s)if(U._type==="PartialBlock"||U._type==="GlobalBlock"){let T=r(U.partialBlockId);U._parent&&(T==null?void 0:T.length)>0&&(T=T.map(O=>(f.isEmpty(O._parent)&&f.set(O,"_parent",U._parent),O))),N=[...N,...T]}else N.push(U);return N},[s,r]),[h,m]=g.useState(""),[b,j]=g.useState(""),[y,p]=g.useState(""),[v,S]=g.useState(""),[C,L]=g.useState({}),[k,D]=g.useState(!1),[G,X]=g.useState(o),[$,P]=g.useState(!1),{hasPermission:M}=F.usePermissions(),H=M(ve.DELETE_LIBRARY_BLOCK),K=F.useUpdateBlocksPropsRealtime(),Q=()=>{K([a],{_libBlockId:void 0}),J.toast.success("Block delinked from library"),n()},{data:Z,isLoading:_,isError:q}=Hr(l);g.useEffect(()=>{q&&o&&(P(!0),X(!1))},[q,o]),g.useEffect(()=>{Z&&!_&&(m(Z.name||""),j(Z.group||""),p(Z.description||""),S(Z.preview||""),X(!1))},[Z,_]),g.useEffect(()=>{const N=h.trim().length>=2,U=b.trim()!=="";D(N&&U)},[h,b]);const fe=()=>{const N={};return h.trim()?h.length<2&&(N.name="Name must be at least 2 characters"):N.name="Name is required",b||(N.group="Group is required"),L(N),Object.keys(N).length===0},{resetLibrary:be}=F.useLibraryBlocks({id:""}),ue=Kr(N=>{o||K([a],{_libBlockId:N.id}),J.toast.success(`Block ${o?"updated":"saved"} successfully`),be(N.library),n()}),E=async N=>{if(N.preventDefault(),!fe())return;const U=d.map(T=>(f.has(T,"_libBlockId")&&delete T._libBlockId,T));ue.mutate({name:h.trim(),group:b,blocks:U,description:y.trim(),...v&&v.startsWith("data:")?{previewImage:v}:{},...o?{id:l}:{}})},x=ue.isPending;return G||_?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(c.Button,{type:"button",variant:"outline",onClick:n,children:"Cancel"}),t.jsx(c.Button,{onClick:Q,variant:"destructive",children:"Delink Block"})]})]}):t.jsxs("div",{children:[u&&t.jsxs("div",{className:"mb-4 p-3 border border-destructive/50 bg-destructive/10 text-destructive rounded-md flex items-start gap-2",children:[t.jsx(w.AlertCircle,{className:"h-5 w-5 flex-shrink-0 mt-0.5"}),t.jsxs("div",{children:[t.jsx("p",{className:"font-medium",children:"Partial Blocks Detected"}),t.jsx("p",{className:"text-xs mt-1",children:"This block contains one or more Partial Blocks. Partial blocks will be merged into the library block"})]})]}),t.jsxs("form",{onSubmit:E,className:"space-y-4",children:[t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Label,{htmlFor:"name",className:C.name?"text-destructive":"",children:"Name"}),t.jsx(c.Input,{id:"name",placeholder:"Enter block name",value:h,onChange:N=>m(N.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(c.Label,{htmlFor:"group",className:C.group?"text-destructive":"",children:"Group"}),t.jsx(Xr,{value:b,onChange:j}),C.group&&t.jsx("p",{className:"text-xs text-destructive",children:C.group})]}),t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Label,{htmlFor:"description",children:"Description (optional)"}),t.jsx(c.Input,{id:"description",placeholder:"Enter a brief description",className:"resize-none",value:y,onChange:N=>p(N.target.value)})]}),t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Label,{htmlFor:"previewImage",children:"Preview Image (optional)"}),t.jsx(ei,{value:v,onChange:S})]}),t.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[o&&H&&t.jsx(Yr,{blockId:a,libBlockId:l,blockName:h,className:"mr-auto",close:n}),t.jsx(c.Button,{type:"button",variant:"outline",onClick:n,disabled:x,children:"Cancel"}),t.jsx(c.Button,{type:"submit",disabled:x||!k,children:x?"Saving...":o?"Update Block":"Save Block"})]})]})]})},le={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."},si={SLUG_ALREADY_USED:"This slug is already in use. Please choose a different one."},Ce=()=>{const e=oe(),s=ee();return R.useQuery({queryKey:[W,I.GET_PAGE_TYPES],initialData:[],queryFn:async()=>s(e,{action:I.GET_PAGE_TYPES})})},ua=e=>{const{data:s}=Ce();return g.useMemo(()=>s==null?void 0:s.find(n=>n.key===e),[s,e])},ni=()=>{const e=oe(),s=ee();return R.useMutation({mutationFn:async({pageType:n,query:a})=>{try{return s(e,{action:I.SEARCH_PAGES,data:{pageType:n,query:Array.isArray(a)&&a.length>0?a[0]:a}})||[]}catch(r){return console.error(r),[]}}})},da=()=>{const e=oe(),s=R.useQueryClient(),n=ee(),{data:a}=Ce();return R.useMutation({mutationFn:async r=>await n(e,{action:I.CREATE_PAGE,data:r}),onSuccess:(r,i)=>{var o;i&&(i!=null&&i.primaryPage)?(s.invalidateQueries({queryKey:[W,I.GET_LANGUAGE_PAGES,i==null?void 0:i.primaryPage]}),s.invalidateQueries({queryKey:[W,I.GET_WEBSITE_PAGES,i==null?void 0:i.lang]})):s.invalidateQueries({queryKey:[W,I.GET_WEBSITE_PAGES]});const l=i.template?`Page created from "${i.template.name}" template`:i.hasSlug===!1?"New "+((o=f.find(a,{key:i.pageType}))==null?void 0:o.name)+" added successfully":"New page added successfully";J.toast.success(l)},onError:(r,i)=>{const l=f.find(a,{key:i.pageType});J.toast.error(`Failed to add new ${l!=null&&l.hasSlug?"page":l.name}.`,{description:f.get(si,r.message,r.message)})}})},ln=()=>{const e=oe(),s=R.useQueryClient(),n=ee(),{data:a}=Ce();return R.useMutation({mutationFn:async r=>await n(e,{action:I.UPDATE_PAGE,data:r}),onSuccess:(r,i)=>{i&&(i!=null&&i.primaryPage||i!=null&&i.seo)?(s.invalidateQueries({queryKey:[W,I.GET_LANGUAGE_PAGES,i==null?void 0:i.primaryPage]}),s.invalidateQueries({queryKey:[W,I.GET_WEBSITE_PAGES]})):s.invalidateQueries({queryKey:[W,I.GET_WEBSITE_PAGES]})},onError:(r,i)=>{const l=f.find(a,{key:i.pageType});J.toast.error(`Failed to update ${l!=null&&l.hasSlug?"page":l.name}.`,{description:r.message})}})},ai=()=>{const e=oe(),s=R.useQueryClient(),n=ee(),{data:a}=Ce();return R.useMutation({mutationFn:async r=>n(e,{action:I.DELETE_PAGE,data:{id:r==null?void 0:r.id}}),onSuccess:(r,i)=>{if(r.code==="PAGE_LOCKED"){J.toast.error("Delete not allowed",{description:"Page is currently being edited by another user."});return}i&&(i!=null&&i.primaryPage)?(s.invalidateQueries({queryKey:[W,I.GET_LANGUAGE_PAGES,i==null?void 0:i.primaryPage]}),s.invalidateQueries({queryKey:[W,I.GET_WEBSITE_PAGES]})):s.invalidateQueries({queryKey:[W,I.GET_WEBSITE_PAGES]})},onError:(r,i)=>{const l=f.find(a,{key:i.pageType});J.toast.error(`Failed to delete ${l!=null&&l.hasSlug?"page":l.name}.`,{description:r.message})}})},ri=()=>{const e=oe(),s=R.useQueryClient(),n=ee(),{data:a}=Ce();return R.useMutation({mutationFn:async r=>n(e,{action:I.TAKE_OFFLINE,data:{id:r==null?void 0:r.id}}),onSuccess:(r,i)=>{i&&(i!=null&&i.primaryPage)?s.invalidateQueries({queryKey:[W,I.GET_LANGUAGE_PAGES,i==null?void 0:i.primaryPage]}):s.invalidateQueries({queryKey:[W,I.GET_WEBSITE_PAGES]});const l=f.find(a,{key:i.pageType});J.toast.success(l!=null&&l.hasSlug?le.PAGE_UNPUBLISH_SUCCESS:"New "+l.name+" added successfully.")},onError:(r,i)=>{const l=f.find(a,{key:i.pageType});J.toast.error(`Failed to take offline ${l!=null&&l.hasSlug?"page":l.name}.`,{description:r.message})}})},ii=()=>{const{savePageAsync:e,saveState:s}=F.useSavePage();return async n=>s!=="SAVED"&&(n.includes("THEME")?n.length>1:n.length>0)?(await e(),!0):!1},on=()=>{const e=oe(),s=ee(),n=R.useQueryClient(),{data:a}=Pe(),r=ii();return R.useMutation({mutationFn:async({ids:i})=>(await r(i),s(e,{action:I.PUBLISH_CHANGES,data:{ids:i}})),onSuccess:()=>{n.invalidateQueries({queryKey:[W,I.GET_CHANGES]}),n.invalidateQueries({queryKey:[W,I.GET_WEBSITE_PAGES]}),n.invalidateQueries({queryKey:[W,I.GET_LANGUAGE_PAGES,a==null?void 0:a.id]})},onError:i=>{console.log("##",i),J.toast.error("Failed to publish pages.")}})},li=()=>{const e=oe(),s=ee(),n=R.useQueryClient();return R.useMutation({mutationFn:async a=>{var r;return s(e,{action:I.MARK_AS_TEMPLATE,data:{id:(r=a.page)==null?void 0:r.id,name:a.name,description:a.description,pageType:a.pageType,previewImage:a.previewImage}})},onSuccess:()=>{n.invalidateQueries({queryKey:[W,I.GET_WEBSITE_PAGES]}),J.toast.success("Page marked as template successfully.")},onError:()=>{J.toast.error("Failed to mark page as template.")}})},oi=()=>{const e=oe(),s=ee(),n=R.useQueryClient();return R.useMutation({mutationFn:async a=>s(e,{action:I.UNMARK_AS_TEMPLATE,data:{id:a==null?void 0:a.id}}),onSuccess:()=>{n.invalidateQueries({queryKey:[W,I.GET_WEBSITE_PAGES]}),J.toast.success("Page unmarked as template successfully.")},onError:()=>{J.toast.error("Failed to unmark page as template.")}})},ci=()=>{const e=oe(),s=ee(),n=R.useQueryClient();return R.useMutation({mutationFn:async({id:a,slug:r})=>s(e,{action:I.CHANGE_SLUG,data:{id:a,slug:r}}),onSuccess:(a,{primaryPage:r})=>{J.toast.success(le.SLUG_CHANGE_SUCCESS),r?n.invalidateQueries({queryKey:[W,I.GET_LANGUAGE_PAGES,r]}):n.invalidateQueries({queryKey:[W,I.GET_WEBSITE_PAGES]})},onError:()=>{J.toast.error("Failed to change slug")}})};var cn={};(function e(s,n,a,r){var i=!!(s.Worker&&s.Blob&&s.Promise&&s.OffscreenCanvas&&s.OffscreenCanvasRenderingContext2D&&s.HTMLCanvasElement&&s.HTMLCanvasElement.prototype.transferControlToOffscreen&&s.URL&&s.URL.createObjectURL),l=typeof Path2D=="function"&&typeof DOMMatrix=="function",o=function(){if(!s.OffscreenCanvas)return!1;var E=new OffscreenCanvas(1,1),x=E.getContext("2d");x.fillRect(0,0,1,1);var N=E.transferToImageBitmap();try{x.createPattern(N,"no-repeat")}catch{return!1}return!0}();function u(){}function d(E){var x=n.exports.Promise,N=x!==void 0?x:s.Promise;return typeof N=="function"?new N(E):(E(u,u),null)}var h=function(E,x){return{transform:function(N){if(E)return N;if(x.has(N))return x.get(N);var U=new OffscreenCanvas(N.width,N.height),T=U.getContext("2d");return T.drawImage(N,0,0),x.set(N,U),U},clear:function(){x.clear()}}}(o,new Map),m=function(){var E=Math.floor(16.666666666666668),x,N,U={},T=0;return typeof requestAnimationFrame=="function"&&typeof cancelAnimationFrame=="function"?(x=function(O){var se=Math.random();return U[se]=requestAnimationFrame(function V(ie){T===ie||T+E-1<ie?(T=ie,delete U[se],O()):U[se]=requestAnimationFrame(V)}),se},N=function(O){U[O]&&cancelAnimationFrame(U[O])}):(x=function(O){return setTimeout(O,E)},N=function(O){return clearTimeout(O)}),{frame:x,cancel:N}}(),b=function(){var E,x,N={};function U(T){function O(se,V){T.postMessage({options:se||{},callback:V})}T.init=function(V){var ie=V.transferControlToOffscreen();T.postMessage({canvas:ie},[ie])},T.fire=function(V,ie,de){if(x)return O(V,null),x;var Y=Math.random().toString(36).slice(2);return x=d(function(te){function me(z){z.data.callback===Y&&(delete N[Y],T.removeEventListener("message",me),x=null,h.clear(),de(),te())}T.addEventListener("message",me),O(V,Y),N[Y]=me.bind(null,{data:{callback:Y}})}),x},T.reset=function(){T.postMessage({reset:!0});for(var V in N)N[V](),delete N[V]}}return function(){if(E)return E;if(!a&&i){var T=["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{E=new Worker(URL.createObjectURL(new Blob([T])))}catch(O){return typeof console!==void 0&&typeof console.warn=="function"&&console.warn("🎊 Could not load worker",O),null}U(E)}return E}}(),j={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 y(E,x){return x?x(E):E}function p(E){return E!=null}function v(E,x,N){return y(E&&p(E[x])?E[x]:j[x],N)}function S(E){return E<0?0:Math.floor(E)}function C(E,x){return Math.floor(Math.random()*(x-E))+E}function L(E){return parseInt(E,16)}function k(E){return E.map(D)}function D(E){var x=String(E).replace(/[^0-9a-f]/gi,"");return x.length<6&&(x=x[0]+x[0]+x[1]+x[1]+x[2]+x[2]),{r:L(x.substring(0,2)),g:L(x.substring(2,4)),b:L(x.substring(4,6))}}function G(E){var x=v(E,"origin",Object);return x.x=v(x,"x",Number),x.y=v(x,"y",Number),x}function X(E){E.width=document.documentElement.clientWidth,E.height=document.documentElement.clientHeight}function $(E){var x=E.getBoundingClientRect();E.width=x.width,E.height=x.height}function P(E){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=E,x}function M(E,x,N,U,T,O,se,V,ie){E.save(),E.translate(x,N),E.rotate(O),E.scale(U,T),E.arc(0,0,1,se,V,ie),E.restore()}function H(E){var x=E.angle*(Math.PI/180),N=E.spread*(Math.PI/180);return{x:E.x,y:E.y,wobble:Math.random()*10,wobbleSpeed:Math.min(.11,Math.random()*.1+.05),velocity:E.startVelocity*.5+Math.random()*E.startVelocity,angle2D:-x+(.5*N-Math.random()*N),tiltAngle:(Math.random()*(.75-.25)+.25)*Math.PI,color:E.color,shape:E.shape,tick:0,totalTicks:E.ticks,decay:E.decay,drift:E.drift,random:Math.random()+2,tiltSin:0,tiltCos:0,wobbleX:0,wobbleY:0,gravity:E.gravity*3,ovalScalar:.6,scalar:E.scalar,flat:E.flat}}function K(E,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 N=x.tick++/x.totalTicks,U=x.x+x.random*x.tiltCos,T=x.y+x.random*x.tiltSin,O=x.wobbleX+x.random*x.tiltCos,se=x.wobbleY+x.random*x.tiltSin;if(E.fillStyle="rgba("+x.color.r+", "+x.color.g+", "+x.color.b+", "+(1-N)+")",E.beginPath(),l&&x.shape.type==="path"&&typeof x.shape.path=="string"&&Array.isArray(x.shape.matrix))E.fill(fe(x.shape.path,x.shape.matrix,x.x,x.y,Math.abs(O-U)*.1,Math.abs(se-T)*.1,Math.PI/10*x.wobble));else if(x.shape.type==="bitmap"){var V=Math.PI/10*x.wobble,ie=Math.abs(O-U)*.1,de=Math.abs(se-T)*.1,Y=x.shape.bitmap.width*x.scalar,te=x.shape.bitmap.height*x.scalar,me=new DOMMatrix([Math.cos(V)*ie,Math.sin(V)*ie,-Math.sin(V)*de,Math.cos(V)*de,x.x,x.y]);me.multiplySelf(new DOMMatrix(x.shape.matrix));var z=E.createPattern(h.transform(x.shape.bitmap),"no-repeat");z.setTransform(me),E.globalAlpha=1-N,E.fillStyle=z,E.fillRect(x.x-Y/2,x.y-te/2,Y,te),E.globalAlpha=1}else if(x.shape==="circle")E.ellipse?E.ellipse(x.x,x.y,Math.abs(O-U)*x.ovalScalar,Math.abs(se-T)*x.ovalScalar,Math.PI/10*x.wobble,0,2*Math.PI):M(E,x.x,x.y,Math.abs(O-U)*x.ovalScalar,Math.abs(se-T)*x.ovalScalar,Math.PI/10*x.wobble,0,2*Math.PI);else if(x.shape==="star")for(var ne=Math.PI/2*3,Ae=4*x.scalar,De=8*x.scalar,B=x.x,ce=x.y,Ne=5,Fe=Math.PI/Ne;Ne--;)B=x.x+Math.cos(ne)*De,ce=x.y+Math.sin(ne)*De,E.lineTo(B,ce),ne+=Fe,B=x.x+Math.cos(ne)*Ae,ce=x.y+Math.sin(ne)*Ae,E.lineTo(B,ce),ne+=Fe;else E.moveTo(Math.floor(x.x),Math.floor(x.y)),E.lineTo(Math.floor(x.wobbleX),Math.floor(T)),E.lineTo(Math.floor(O),Math.floor(se)),E.lineTo(Math.floor(U),Math.floor(x.wobbleY));return E.closePath(),E.fill(),x.tick<x.totalTicks}function Q(E,x,N,U,T){var O=x.slice(),se=E.getContext("2d"),V,ie,de=d(function(Y){function te(){V=ie=null,se.clearRect(0,0,U.width,U.height),h.clear(),T(),Y()}function me(){a&&!(U.width===r.width&&U.height===r.height)&&(U.width=E.width=r.width,U.height=E.height=r.height),!U.width&&!U.height&&(N(E),U.width=E.width,U.height=E.height),se.clearRect(0,0,U.width,U.height),O=O.filter(function(z){return K(se,z)}),O.length?V=m.frame(me):te()}V=m.frame(me),ie=te});return{addFettis:function(Y){return O=O.concat(Y),de},canvas:E,promise:de,reset:function(){V&&m.cancel(V),ie&&ie()}}}function Z(E,x){var N=!E,U=!!v(x||{},"resize"),T=!1,O=v(x,"disableForReducedMotion",Boolean),se=i&&!!v(x||{},"useWorker"),V=se?b():null,ie=N?X:$,de=E&&V?!!E.__confetti_initialized:!1,Y=typeof matchMedia=="function"&&matchMedia("(prefers-reduced-motion)").matches,te;function me(ne,Ae,De){for(var B=v(ne,"particleCount",S),ce=v(ne,"angle",Number),Ne=v(ne,"spread",Number),Fe=v(ne,"startVelocity",Number),Ls=v(ne,"decay",Number),Ds=v(ne,"gravity",Number),Bs=v(ne,"drift",Number),Dt=v(ne,"colors",k),Bt=v(ne,"ticks",Number),st=v(ne,"shapes"),ls=v(ne,"scalar"),os=!!v(ne,"flat"),A=G(ne),he=B,Be=[],Ie=E.width*A.x,Me=E.height*A.y;he--;)Be.push(H({x:Ie,y:Me,angle:ce,spread:Ne,startVelocity:Fe,color:Dt[he%Dt.length],shape:st[C(0,st.length)],ticks:Bt,decay:Ls,gravity:Ds,drift:Bs,scalar:ls,flat:os}));return te?te.addFettis(Be):(te=Q(E,Be,ie,Ae,De),te.promise)}function z(ne){var Ae=O||v(ne,"disableForReducedMotion",Boolean),De=v(ne,"zIndex",Number);if(Ae&&Y)return d(function(Fe){Fe()});N&&te?E=te.canvas:N&&!E&&(E=P(De),document.body.appendChild(E)),U&&!de&&ie(E);var B={width:E.width,height:E.height};V&&!de&&V.init(E),de=!0,V&&(E.__confetti_initialized=!0);function ce(){if(V){var Fe={getBoundingClientRect:function(){if(!N)return E.getBoundingClientRect()}};ie(Fe),V.postMessage({resize:{width:Fe.width,height:Fe.height}});return}B.width=B.height=null}function Ne(){te=null,U&&(T=!1,s.removeEventListener("resize",ce)),N&&E&&(document.body.contains(E)&&document.body.removeChild(E),E=null,de=!1)}return U&&!T&&(T=!0,s.addEventListener("resize",ce,!1)),V?V.fire(ne,B,Ne):me(ne,B,Ne)}return z.reset=function(){V&&V.reset(),te&&te.reset()},z}var _;function q(){return _||(_=Z(null,{useWorker:!0,resize:!0})),_}function fe(E,x,N,U,T,O,se){var V=new Path2D(E),ie=new Path2D;ie.addPath(V,new DOMMatrix(x));var de=new Path2D;return de.addPath(ie,new DOMMatrix([Math.cos(se)*T,Math.sin(se)*T,-Math.sin(se)*O,Math.cos(se)*O,N,U])),de}function be(E){if(!l)throw new Error("path confetti are not supported in this browser");var x,N;typeof E=="string"?x=E:(x=E.path,N=E.matrix);var U=new Path2D(x),T=document.createElement("canvas"),O=T.getContext("2d");if(!N){for(var se=1e3,V=se,ie=se,de=0,Y=0,te,me,z=0;z<se;z+=2)for(var ne=0;ne<se;ne+=2)O.isPointInPath(U,z,ne,"nonzero")&&(V=Math.min(V,z),ie=Math.min(ie,ne),de=Math.max(de,z),Y=Math.max(Y,ne));te=de-V,me=Y-ie;var Ae=10,De=Math.min(Ae/te,Ae/me);N=[De,0,0,De,-Math.round(te/2+V)*De,-Math.round(me/2+ie)*De]}return{type:"path",path:x,matrix:N}}function ue(E){var x,N=1,U="#000000",T='"Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji", "EmojiOne Color", "Android Emoji", "Twemoji Mozilla", "system emoji", sans-serif';typeof E=="string"?x=E:(x=E.text,N="scalar"in E?E.scalar:N,T="fontFamily"in E?E.fontFamily:T,U="color"in E?E.color:U);var O=10*N,se=""+O+"px "+T,V=new OffscreenCanvas(O,O),ie=V.getContext("2d");ie.font=se;var de=ie.measureText(x),Y=Math.ceil(de.actualBoundingBoxRight+de.actualBoundingBoxLeft),te=Math.ceil(de.actualBoundingBoxAscent+de.actualBoundingBoxDescent),me=2,z=de.actualBoundingBoxLeft+me,ne=de.actualBoundingBoxAscent+me;Y+=me+me,te+=me+me,V=new OffscreenCanvas(Y,te),ie=V.getContext("2d"),ie.font=se,ie.fillStyle=U,ie.fillText(x,z,ne);var Ae=1/N;return{type:"bitmap",bitmap:V.transferToImageBitmap(),matrix:[Ae,0,0,Ae,-Y*Ae/2,-te*Ae/2]}}n.exports=function(){return q().apply(this,arguments)},n.exports.reset=function(){q().reset()},n.exports.create=Z,n.exports.shapeFromPath=be,n.exports.shapeFromText=ue})(function(){return typeof window<"u"?window:typeof self<"u"?self:this||{}}(),cn,!1);const ui=cn.exports;cn.exports.create;const di={particleCount:350,spread:120,origin:{y:.6},angle:90},hi={TOP_RIGHT:{angle:225,origin:{x:.9,y:0}},BOTTOM_RIGHT:{angle:100,origin:{x:.9,y:.9}}},Ot=e=>{let s=hi[e];s||(s={});const n={...di,...s};ui(n)},mi=()=>{const[e]=F.useTheme(),{mutate:s,isPending:n}=on(),{mutateAsync:a,isPending:r}=Zn(),i=()=>{a({settings:{theme:e}})},l=async()=>{await a({settings:{theme:e}}),s({ids:["THEME"]},{onSuccess:()=>{Ot("BOTTOM_RIGHT")}})};return t.jsxs("div",{className:"flex items-center justify-center gap-x-3 border-t bg-white py-3",children:[t.jsx(c.Button,{size:"sm",variant:"outline",disabled:n||r,onClick:i,children:"Save draft"}),t.jsx(c.Button,{size:"sm",disabled:n||r,onClick:l,children:"Publish"})]})},Ts=we.atom(null),fi=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}},Ze=e=>{if(!e)return e;const{base:s}=fi(e);return s};function gi(e,s){const n=(e||"").split("/").filter(Boolean);let a="",r=!0;if(s.slug==="/"){const i=n.pop()||"";if(Te[i])r=!0;else{a=i;const l=n.pop()||"";r=!!Te[l]}}else if(s.parent)n.length&&(a=n.pop()||"");else if(n.length){a=n.pop()||"";const i=n.pop()||"";r=!!Te[i]}return{initSlug:a,prefix:r}}const xi=e=>e&&Ze(e),An=(e,s)=>{const n=Ze(e||"");return!n||n==="/"?`/${s}`:`${n}/${s}`};function un({value:e,onChange:s,placeholder:n,parentSlug:a,onValidationChange:r,disabled:i=!1,fullSlug:l}){const[o,u]=g.useState(e),[d,h]=g.useState(null);g.useEffect(()=>{u(e)},[e]);const m=b=>{const y=b.target.value.replace(/\//g,"").replace(/\s+/g,"-").replace(/[^a-zA-Z0-9-_.]/g,"-").replace(/-+/g,"-").replace(/^-+/,"").toLowerCase(),p=(y.match(/\./g)||[]).length,v=p<=1;p>1?h("Invalid slug. Only one dot (.) is allowed in the slug"):h(null),r&&r(v),u(y),s(y)};return t.jsxs("div",{children:[a&&t.jsx("div",{className:"mb-1 flex items-center",children:t.jsxs("span",{className:"text-xs text-gray-500",children:["Parent: ",t.jsx("span",{className:"font-mono text-gray-900",children:xi(a)})]})}),t.jsxs("div",{className:"relative",children:[t.jsx(c.Input,{disabled:i,value:o,onChange:m,placeholder:n,className:d?"border-red-500":""}),d&&t.jsx("div",{className:"mt-1 text-xs text-red-500",children:d})]}),l&&l!=="undefined"&&t.jsx("div",{className:"mt-1 flex items-center",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 ha=({edit:e,lang:s,languages:n,name:a,setLang:r,setName:i,primaryPageObject:l})=>t.jsxs("div",{className:"space-y-1",children:[t.jsx(c.Label,{htmlFor:"lang",children:le.LANGUAGE}),t.jsxs("select",{value:e?"":s,disabled:e||!n.length,onChange:o=>{const u=o.target.value;r(u),!e&&(f.startsWith(a,l==null?void 0:l.name)||a.length===0)&&i(`${l==null?void 0:l.name} - ${Te[u]}`)},className:"col-span-3 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",children:[t.jsx("option",{value:"",disabled:!0,children:e?Te[s]||s:n.length?le.CHOOSE_LANGUAGE:le.ALL_AVAILABLE_LANGUAGE_PAGE}),n.map(o=>t.jsx("option",{value:o,children:Te[o]||o},o))]})]}),ma=({lang:e,name:s,setName:n,parentHasSelectedLanguagePage:a})=>t.jsxs("div",{className:"space-y-1",children:[t.jsx(c.Label,{htmlFor:"name",children:le.PAGE_NAME}),t.jsx(c.Input,{id:"name",value:e?s:"",onChange:r=>n(r.target.value),required:!0,placeholder:e?le.ENTER_PAGE_NAME:le.CHOOSE_LANGUAGE_TO_ADD_SLUG,disabled:!a||!e})]}),pi=({dynamic:e,isNonSlugPageType:s,isRootPage:n,lang:a,useLanguagePrefix:r,setUseLanguagePrefix:i,isHomePage:l,parentSlug:o,parentHasSelectedLanguagePage:u,slug:d,setSlug:h,setIsSlugValid:m,getSlug:b})=>s?null:t.jsxs("div",{className:"space-y-1",children:[n&&a&&t.jsxs("div",{className:"flex items-center space-x-2 pb-1",children:[t.jsx("input",{type:"checkbox",id:"useLanguagePrefix",checked:r,onChange:j=>i(j.target.checked),className:"rounded border-gray-300"}),t.jsxs(c.Label,{htmlFor:"useLanguagePrefix",className:"text-sm font-normal leading-tight",children:["Add language code (",t.jsxs("span",{className:"font-mono text-gray-900",children:["/",a]}),") as slug prefix"]})]}),t.jsx(c.Label,{htmlFor:"slug",children:le.SLUG}),e?t.jsx(c.Alert,{variant:"default",className:"p-2 text-xs font-medium italic text-muted-foreground",children:"This page will use dynamic slug as defined in primary page"}):t.jsx(un,{disabled:!a||!u,value:d,onChange:h,placeholder:a?l&&r?"Leave empty for home page":le.ENTER_PAGE_SLUG:le.CHOOSE_LANGUAGE_TO_ADD_SLUG,parentSlug:o,onValidationChange:m,fullSlug:b()})]}),fa=({parentHasSelectedLanguagePage:e,name:s,lang:n,slug:a,edit:r,id:i,primaryPageObject:l,pages:o,isNonSlugPageType:u,isHomePage:d,useLanguagePrefix:h,isSlugValid:m,isPending:b})=>{const j=b||!s||!n||o.some(y=>(r?y.id!==i:!0)&&y.parent===(l==null?void 0:l.id)&&y.lang===n)||!u&&!(d&&h)&&(!m||!a);return t.jsx(c.DialogFooter,{children:e?t.jsxs(t.Fragment,{children:[t.jsx(c.Button,{type:"submit",disabled:j&&!l.dynamic,children:b?t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsx("span",{className:"loader mr-2"}),r?le.UPDATING:le.ADDING]}):r?le.UPDATE:le.ADD_NEW_LANGUAGE}),o.some(y=>(r?y.id!==i:!0)&&y.parent===(l==null?void 0:l.id)&&y.lang===n)&&t.jsx("p",{className:"mt-2 text-xs text-red-500",children:"A page for this language already exists."})]}):n&&t.jsx(c.Alert,{variant:"destructive",children:t.jsxs("p",{className:"mx-auto w-5/6 text-center",children:["You need to create the ",t.jsx("span",{className:"font-medium",children:Te[n]})," page in the parent to add here."]})})})},yi=({onSubmit:e,edit:s,lang:n,languages:a,name:r,setLang:i,setName:l,primaryPageObject:o,parentHasSelectedLanguagePage:u,id:d,pages:h,isNonSlugPageType:m,isHomePage:b,useLanguagePrefix:j,slug:y,isSlugValid:p,isPending:v})=>t.jsxs("form",{onSubmit:e,children:[t.jsxs("div",{className:"grid gap-4 py-4",children:[t.jsx(ha,{edit:s,lang:n,languages:a,name:r,setLang:i,setName:l,primaryPageObject:o}),t.jsx(ma,{lang:n,name:r,setName:l,parentHasSelectedLanguagePage:u})]}),t.jsx(fa,{parentHasSelectedLanguagePage:u,name:r,lang:n,slug:y,edit:s,id:d,primaryPageObject:o,pages:h,isNonSlugPageType:m,isHomePage:b,useLanguagePrefix:j,isSlugValid:p,isPending:v})]}),ji=({loading:e,onSubmit:s,edit:n,lang:a,languages:r,name:i,setLang:l,setName:o,primaryPageObject:u,parentHasSelectedLanguagePage:d,isNonSlugPageType:h,isRootPage:m,useLanguagePrefix:b,setUseLanguagePrefix:j,isHomePage:y,parentSlug:p,slug:v,setSlug:S,isSlugValid:C,setIsSlugValid:L,getSlug:k,isPending:D,id:G,pages:X})=>e?t.jsx("div",{className:"flex h-80 items-center justify-center",children:t.jsx(w.Loader,{className:"animate-spin"})}):h?t.jsx(yi,{onSubmit:s,edit:n,lang:a,languages:r,name:i,setLang:l,setName:o,primaryPageObject:u,parentHasSelectedLanguagePage:d,id:G,pages:X,isNonSlugPageType:h,isHomePage:y,useLanguagePrefix:b,slug:v,isSlugValid:C,isPending:D}):t.jsxs("form",{onSubmit:s,children:[t.jsxs("div",{className:"grid gap-4 py-4",children:[t.jsx(ha,{edit:n,lang:a,languages:r,name:i,setLang:l,setName:o,primaryPageObject:u}),t.jsx(ma,{lang:a,name:i,setName:o,parentHasSelectedLanguagePage:d}),t.jsx(pi,{dynamic:u==null?void 0:u.dynamic,isNonSlugPageType:h,isRootPage:m,lang:a,useLanguagePrefix:b,setUseLanguagePrefix:j,isHomePage:y,parentSlug:p,parentHasSelectedLanguagePage:d,slug:v,setSlug:S,isSlugValid:C,setIsSlugValid:L,getSlug:k})]}),t.jsx(fa,{parentHasSelectedLanguagePage:d,name:i,lang:a,slug:v,edit:n,id:G,primaryPageObject:u,pages:X,isNonSlugPageType:h,isHomePage:y,useLanguagePrefix:b,isSlugValid:C,isPending:D})]}),vi=({id:e,isOpen:s,onClose:n,primaryPage:a,edit:r=!1,preselectedLang:i})=>{const{data:l=[]}=ot(),o=g.useMemo(()=>l.find(Y=>Y.id===a),[l,a]),[u,d]=g.useState(""),[h,m]=g.useState(""),[b,j]=g.useState(""),[y,p]=g.useState(!0),[v,S]=g.useState(!0),{mutate:C,isPending:L}=da(),{mutate:k,isPending:D}=ln(),G=L||D,{data:X,isFetching:$}=He(),P=Qe(),{data:M,isFetching:H}=Oe(a),{data:K=[],isFetching:Q}=Oe(o==null?void 0:o.parent),{data:Z=[],isFetching:_}=Ce(),{setSelectedLang:q}=F.useLanguages(),[,fe]=_e(),[,be]=F.useSidebarActivePanel(),ue=$||H||Q||_,E=g.useMemo(()=>f.filter(X==null?void 0:X.languages,Y=>!f.find(M,{lang:Y})),[X,M]),x=g.useMemo(()=>Z.find(Y=>Y.key===(o==null?void 0:o.pageType)),[Z,o==null?void 0:o.pageType]),N=!(x!=null&&x.hasSlug),U=(o==null?void 0:o.slug)==="/";g.useEffect(()=>{if(!r&&o&&i&&(m(i),d(`${o.name} - ${Te[i]}`)),!r||!o)return;const Y=M==null?void 0:M.find(ne=>ne.id===e);if(!Y)return;d(Y.name),m(Y.lang);const te=Y.slug||"",{initSlug:me,prefix:z}=gi(te,o);j(me),S(z)},[r,e,M,o,i]),g.useEffect(()=>{i&&m(i)},[i]);const{parentSlug:T,isRootPage:O}=g.useMemo(()=>{if(U||!h)return{parentSlug:void 0,isRootPage:!(o!=null&&o.parent)};if(!(o!=null&&o.parent))return{parentSlug:v?`/${h}`:void 0,isRootPage:!0};const Y=K==null?void 0:K.find(te=>te.lang===h);return{parentSlug:Y==null?void 0:Y.slug,isRootPage:!1}},[o==null?void 0:o.parent,K,v,h,U]),se=g.useMemo(()=>O?!0:!!(K!=null&&K.some(Y=>(Y==null?void 0:Y.lang)===h)),[h,K,O]),V=()=>{let Y="";return O?Y=`/${v?[h,b].filter(Boolean).join("/"):b}`:Y=`${Ze(T)}/${b}`,Y.replace(/\/{2,}/g,"/").replace(/\/$/,"")},ie=Y=>{const te=new URLSearchParams(window.location.search);P&&Y===P?te.delete("lang"):te.set("lang",Y),fe(te),window.dispatchEvent(new PopStateEvent("popstate"))},de=Y=>{Y.preventDefault();const te={name:u,lang:h,primaryPage:o==null?void 0:o.id,slug:N?"":V(),pageType:o==null?void 0:o.pageType,...r&&{id:e}},me=()=>{!r&&h&&(q(h),ie(h)),be("outline"),n()};r?k(te,{onSuccess:me}):C(te,{onSuccess:me})};return t.jsx(c.Dialog,{open:s,onOpenChange:n,children:t.jsxs(c.DialogContent,{className:"text-slate-600 sm:max-w-[425px]",children:[t.jsxs(c.DialogHeader,{children:[t.jsx(c.DialogTitle,{children:r?le.EDIT_LANGUAGE:le.ADD_NEW_LANGUAGE}),t.jsx(c.DialogDescription,{className:"font-light",children:le.ENTER_LANGUAGE_DETAILS})]}),t.jsx(ji,{id:e,pages:l,loading:ue,onSubmit:de,edit:r,lang:h,languages:E,name:u,setLang:m,setName:d,primaryPageObject:o,parentHasSelectedLanguagePage:se,isNonSlugPageType:N,isRootPage:O,useLanguagePrefix:v,setUseLanguagePrefix:S,isHomePage:U,parentSlug:T,slug:b,setSlug:j,isSlugValid:y,setIsSlugValid:p,getSlug:V,isPending:G})]})})};function bi({value:e,onChange:s,placeholder:n="Enter custom slug part",dynamicPattern:a,onValidationChange:r}){const[i,l]=g.useState(null),o=g.useRef(null),[u,d]=g.useState(a+e);g.useEffect(()=>{d(a+e)},[e,a]);const h=j=>{const y=j.target.value;if(!y.startsWith(a)){const k=y.replace(a,""),D=a+k;d(D),s(k);return}const v=y.substring(a.length).replace(/\//g,"").replace(/\s+/g,"-").replace(/[^a-zA-Z0-9-_.]/g,"-").replace(/-+/g,"-").replace(/^-+/,"").toLowerCase(),S=(v.match(/\./g)||[]).length,C=S<=1;S>1?l("Invalid slug. Only one dot (.) is allowed in the slug"):l(null),r&&r(C);const L=a+v;d(L),s(v)},m=()=>{if(o.current){const j=o.current;setTimeout(()=>{const y=a.length;j.setSelectionRange(y,y)},0)}},b=j=>{const y=j.currentTarget;(y.selectionStart||0)<=a.length&&setTimeout(()=>{const v=a.length;y.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(c.Input,{ref:o,value:u,onChange:h,onFocus:m,onClick:b,placeholder:n,className:i?"border-red-500":""}),i&&t.jsx("div",{className:"text-red-500 text-xs mt-1",children:i})]})})}const gs=({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(c.CommandList,{...n,onWheel:a,children:e})},Ms=(...e)=>e.filter(Boolean).join(" ");function Si({pages:e,selectedParentId:s,onChange:n,className:a,id:r="parentPage"}){const[i,l]=g.useState(!1),[o,u]=g.useState(""),d=F.useChaiFeatureFlag("enable-add-page-dropdown");d||(a="w-full rounded-md border border-gray-300 px-3 py-2");const h=g.useMemo(()=>!e||e.length===0?[]:e.filter(S=>!f.isEmpty(S.slug)).filter(S=>S.slug!=="/").sort((S,C)=>S.slug.localeCompare(C.slug)),[e]),m=g.useMemo(()=>{if(!o.trim())return h;const v=o.toLowerCase();return h.filter(S=>S.name.toLowerCase().includes(v)||S.slug.toLowerCase().includes(v))},[h,o]),b=v=>Math.max(0,(v.match(/\//g)||[]).length-1),j=v=>"    ".repeat(v),y=v=>{if(v==="/")return"/";const S=v.split("/").filter(Boolean);if(S.length<=1){const C=S[0]||"";return`/${Ze(C)}`}return`/${Ze(S[S.length-1])}`},p=()=>{if(!s||s==="none")return"None";const v=h.find(S=>S.id===s);return v?`${v.name} (${y(v.slug)})`:"None"};return t.jsxs("div",{className:"space-y-0.5",children:[t.jsx(c.Label,{htmlFor:r,className:"text-sm",children:"Parent"}),d?t.jsxs(c.Popover,{open:i,onOpenChange:l,children:[t.jsx(c.PopoverTrigger,{asChild:!0,children:t.jsxs(c.Button,{id:r,variant:"outline",role:"combobox",className:Ms("w-full justify-between",a),"data-testid":"parent-page-selector",children:[p(),t.jsx(w.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),t.jsx(c.PopoverContent,{className:"w-[var(--radix-popover-trigger-width)] p-0",align:"start",children:t.jsxs(c.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(w.Search,{strokeWidth:2,className:"absolute left-2 top-2 h-4 w-4 text-gray-400"}),t.jsx(c.Input,{placeholder:"Search pages...",className:"h-8 pl-8 text-xs",value:o,onChange:v=>u(v.target.value)})]})})}),t.jsxs(gs,{className:"max-h-[300px] overflow-y-auto",children:[t.jsx(c.CommandEmpty,{children:"No pages found."}),t.jsxs(c.CommandGroup,{children:[t.jsxs(c.CommandItem,{value:"none",onSelect:()=>{n(""),l(!1),u("")},className:"flex cursor-pointer items-center justify-between",children:[t.jsx("span",{children:"None"}),t.jsx(w.Check,{className:Ms("mr-2 h-4 w-4",s?"opacity-0":"opacity-100")})]}),m.map(v=>{const S=j(b(v.slug)),C=y(v.slug),L=t.jsxs("span",{className:"flex items-center text-sm",children:[S,v.name,t.jsxs("span",{className:"text-xs text-gray-500",children:[" (",C,")"]})]});return t.jsxs(c.CommandItem,{value:v.id,onSelect:()=>{n(v.id),l(!1),u("")},className:"flex cursor-pointer items-center justify-between whitespace-pre-wrap",children:[t.jsx("span",{children:L}),t.jsx(w.Check,{className:Ms("mr-2 h-4 w-4 shrink-0",s===v.id?"opacity-100":"opacity-0")})]},v.id)})]})]})]})})]}):t.jsxs("select",{id:r,value:s||"none",onChange:v=>n(v.target.value),className:a,"data-testid":"parent-page-selector",children:[t.jsx("option",{value:"none",children:"None"}),h.map(v=>{const S=b(v.slug),C=S>0?j(S):"",L=y(v.slug);return t.jsxs("option",{value:v.id,children:[C,v.name," (",L,")"]},v.id)})]})]})}const wi=(...e)=>e.filter(Boolean).join(" "),Ei=({templates:e,selectedTemplateId:s,onSelectTemplate:n,isLoading:a=!1})=>{const[r,i]=g.useState(""),[l,o]=g.useState(!1),[u,d]=g.useState(""),h=F.useChaiFeatureFlag("enable-add-page-dropdown");if(g.useEffect(()=>{if(s){const p=e.find(v=>v.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 m={};e.forEach(p=>{const v=p.libraryName;m[v]||(m[v]=[]),m[v].push(p)});const b=Object.entries(m).reduce((p,[v,S])=>{const C=S.filter(L=>L.name.toLowerCase().includes(u.toLowerCase())||v.toLowerCase().includes(u.toLowerCase()));return C.length>0&&(p[v]=C),p},{}),j=e.find(p=>p.id===s),y=j?f.startCase(j.name):"No Template";return t.jsxs("div",{className:"space-y-4",children:[h?t.jsxs(c.Popover,{open:l,onOpenChange:o,children:[t.jsx(c.PopoverTrigger,{asChild:!0,children:t.jsxs(c.Button,{variant:"outline",role:"combobox",className:"w-full justify-between",children:[y,t.jsx(w.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),t.jsx(c.PopoverContent,{className:"w-[var(--radix-popover-trigger-width)] p-0",align:"start",children:t.jsxs(c.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(w.Search,{strokeWidth:2,className:"absolute left-2 top-2 h-4 w-4 text-gray-400"}),t.jsx(c.Input,{placeholder:"Search templates...",className:"h-8 pl-8 text-xs",value:u,onChange:p=>d(p.target.value)})]})}),t.jsxs(gs,{className:"max-h-[300px] overflow-y-auto",children:[t.jsx(c.CommandEmpty,{children:"No templates found."}),Object.entries(b).map(([p,v])=>t.jsx(c.CommandGroup,{heading:p,children:v.map(S=>t.jsxs(c.CommandItem,{value:S.id,onSelect:()=>{n(S.id),o(!1),d("")},className:"flex cursor-pointer items-center justify-between",children:[f.startCase(S.name),t.jsx(w.Check,{className:wi("mr-2 h-4 w-4",s===S.id?"opacity-100":"opacity-0")})]},S.id))},p))]})]})})]}):t.jsxs("select",{className:"w-full rounded-md border border-gray-300 px-3 py-2",value:s,onChange:p=>n(p.target.value),children:[t.jsx("option",{value:"",children:"No Template"}),Object.entries(m).map(([p,v])=>t.jsx("optgroup",{label:p,children:v.map(S=>t.jsx("option",{value:S.id,children:f.startCase(S.name)},S.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=oe(),s=ee();return R.useQuery({queryKey:[W,I.GET_LIBRARIES],queryFn:async()=>await s(e,{action:I.GET_LIBRARIES})||[]})},Ci=e=>{const s=oe(),n=ee();return R.useQuery({queryKey:[W,I.GET_TEMPLATES_BY_TYPE,e],enabled:!!e,queryFn:async()=>{const a=await n(s,{action:I.GET_TEMPLATES_BY_TYPE,data:{pageType:e}});return(e?f.filter(a,{pageType:e}):a)||[]}})},Ai=e=>{const{data:s=[],isLoading:n}=Ci(e),{data:a=[],isLoading:r}=Ni(),i=g.useMemo(()=>n||r?[]:s.map(o=>{const u=f.find(a,{id:o.library});return{...o,libraryName:(u==null?void 0:u.type)!=="shared"?"Site Library":(u==null?void 0:u.name)+" Library",libraryType:u==null?void 0:u.type}}),[s,a,n,r]),l=g.useMemo(()=>f.groupBy(i,"libraryName"),[i]);return{data:i,groupedData:l,isLoading:n||r}},dn=()=>{const[,e]=_e();return g.useCallback((s,n)=>{const r=new URLSearchParams(window.location.search).get("lang"),i=new URLSearchParams({page:s});r&&i.set("lang",r),window.history.pushState({},"",`?${i.toString()}`),e(i),window.dispatchEvent(new PopStateEvent("popstate")),n==null||n()},[e])},xs=(e,s)=>{const n={seo:{keyword:"",title:"",description:"",noIndex:!1,noFollow:!1,canonicalUrl:"",ogTitle:"",ogDescription:"",jsonLD:""},jsonLD:{}};e!=null&&e.defaultSeo&&(f.has(e.defaultSeo,s)&&f.isObject(e.defaultSeo[s])?n.seo={...n.seo,...e.defaultSeo[s]}:n.seo={...n.seo,...e.defaultSeo});let a={};return e!=null&&e.defaultJSONLD&&(f.has(e.defaultJSONLD,s)&&f.isObject(e.defaultJSONLD[s])?(a=e.defaultJSONLD[s],f.set(n,"seo.jsonLD",JSON.stringify(a))):(a=e.defaultJSONLD,f.set(n,"seo.jsonLD",JSON.stringify(a)))),{seo:n.seo,jsonLD:a}},nt=(...e)=>e.filter(Boolean).join(" ");function Ti({addEditPage:e,additionalPageTypes:s=[],close:n,closePanel:a}){var ls,os;const r=dn(),i=!!(e!=null&&e.id),{data:l}=ot(),{mutate:o,isPending:u}=da(),{mutate:d,isPending:h}=ln(),[m,b]=g.useState(null),[j,y]=g.useState(!0),[p,v]=g.useState((e==null?void 0:e.pageType)??"page"),{hasPermission:S}=F.usePermissions(),C=S(ve.CHANGE_PAGE_TYPE),[L,k]=g.useState(!1),[D,G]=g.useState(""),{selectedLang:X,fallbackLang:$}=F.useLanguages(),P=X||$,[M,H]=g.useState(""),[K,Q]=g.useState(!1),Z=g.useMemo(()=>{const A=s.find(he=>he.key===p);return(A==null?void 0:A.hasSlug)===!1},[p,s]),[_,q]=g.useState((e==null?void 0:e.parent)??""),[fe,be]=g.useState((e==null?void 0:e.name)??""),[ue,E]=g.useState((e==null?void 0:e.dynamic)??!1),[x,N]=g.useState(ue?"":((e==null?void 0:e.slug)??"").split("/").pop()||""),[U,T]=g.useState((e==null?void 0:e.dynamicSlugCustom)??""),[O,se]=g.useState(!0),[V,ie]=g.useState(""),{data:de,isLoading:Y}=Ai(p),te=u||h,me=F.useChaiFeatureFlag("enable-add-page-dropdown"),z=s.find(A=>A.key===p),ne=A=>{if(i&&p!==A){G(A),k(!0),H(""),Q(!1);return}v(A),H(""),Q(!1)},Ae=()=>{v(D),k(!1),E(!1)},De=A=>{E(A),A?N(""):T("")},B=A=>{if(q(A),A&&A!=="none"){const he=l==null?void 0:l.find(Ie=>Ie.id===A),Be=(he==null?void 0:he.slug)||"";if(x.startsWith(Be)){const Ie=x.slice(Be.length).replace(/^\/+/,"");N(Ie)}else N(x.replace(/^\/+/,""))}else N(x?`${x}`:"")},ce=A=>{ie(A)},Ne=()=>fe.trim()?ue&&!f.isEmpty(x)?(b("Slug must be empty when using dynamic slug"),!1):ue&&!O?(b("Dynamic slug is invalid"),!1):!0:(J.toast.error("Name is required"),!1),Fe=()=>{const A={pageType:z==null?void 0:z.key,name:fe,slug:"",hasSlug:!1};i?d({id:e==null?void 0:e.id,name:fe},{onSuccess:()=>{J.toast.success((z==null?void 0:z.name)+" updated successfully"),n()}}):o(A,{onSuccess:he=>{n(),r(he.page.id,a)}})},Ls=(A,he)=>{if(!A.trim()&&!ue)return b("Child page slug is required"),!1;const Be=Ze(he),Ie=An(Be,A);return Object.keys(Te).some(cs=>Ie===`/${cs}`||(Ie==null?void 0:Ie.startsWith(`/${cs}/`)))?(b("Slugs cannot start with a language code for primary page"),!1):!0},Ds=(A,he)=>{const Be=Ze(he),Ie=An(Be,A),Me={pageType:p,name:fe,slug:Ie.replace(/\/$/,""),parent:_,dynamic:ue,hasSlug:!0,template:V||void 0,tracking:{},seo:{},jsonLD:{}};if(ue&&(Me.dynamicSlugCustom=U),i)d({id:e==null?void 0:e.id,...Me},{onSuccess:()=>{J.toast.success("Page updated successfully"),n()}});else{const Ve=f.find(s,{key:p});Ve!=null&&Ve.trackingDefault&&(Me.tracking=Ve.trackingDefault);const{seo:cs,jsonLD:gr}=xs(Ve,P);f.set(Me,"seo",cs),f.set(Me,"jsonLD",gr),o(Me,{onSuccess:xr=>{n(),r(xr.page.id,a)}})}},Bs=()=>{const A={pageType:p,name:fe,slug:x===""?"/":`/${x.replace(/\/$/,"")}`,template:V||void 0,parent:null,tracking:{}};if(i)d({id:e==null?void 0:e.id,...A},{onSuccess:()=>{J.toast.success("Page updated successfully"),n()}});else{const he=f.find(s,{key:p});he!=null&&he.trackingDefault&&(A.tracking=he.trackingDefault);const{seo:Be,jsonLD:Ie}=xs(he,P);f.set(A,"seo",Be),f.set(A,"jsonLD",Ie),o(A,{onSuccess:Me=>{var Ve;(Ve=Me==null?void 0:Me.page)!=null&&Ve.id&&r(Me.page.id,a),n()}})}},Dt=A=>{if(A.preventDefault(),b(null),!!Ne()){if(!(z!=null&&z.hasSlug)){Fe();return}if(_&&_!=="none"){const he=l==null?void 0:l.find(Ie=>Ie.id===_),Be=(he==null?void 0:he.slug)||"";if(!Ls(x,Be))return;Ds(x,Be)}else Bs()}},{pagesType:Bt,partialsType:st}=g.useMemo(()=>{const A=he=>M?he.name.toLowerCase().includes(M.toLowerCase())||he.key.toLowerCase().includes(M.toLowerCase()):!0;return{pagesType:s.filter(he=>he.hasSlug!==!1&&A(he)),partialsType:s.filter(he=>he.hasSlug===!1&&A(he))}},[s,M]);return z!=null&&z.hasSlug?t.jsxs("form",{onSubmit:Dt,className:"mx-auto w-full max-w-md space-y-4",children:[t.jsxs("div",{className:"space-y-0.5",children:[t.jsx(c.Label,{htmlFor:"pageType",className:"text-sm",children:"Type"}),me?t.jsxs(c.Popover,{open:K,onOpenChange:Q,children:[t.jsx(c.PopoverTrigger,{asChild:!0,children:t.jsxs(c.Button,{variant:"outline",role:"combobox",disabled:i&&!C,className:nt("w-full justify-between",i&&!C?"cursor-not-allowed text-gray-500":""),children:[(z==null?void 0:z.name)||"Select page type",t.jsx(w.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),t.jsx(c.PopoverContent,{className:"w-[var(--radix-popover-trigger-width)] p-0",align:"start",children:t.jsxs(c.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(w.Search,{strokeWidth:2,className:"absolute left-2 top-2 h-4 w-4 text-gray-400"}),t.jsx(c.Input,{placeholder:"Search page types...",className:"h-8 pl-8 text-xs",value:M,onChange:A=>H(A.target.value)})]})}),t.jsxs(gs,{className:"overflow-y-auto",children:[t.jsx(c.CommandEmpty,{children:"No page type found."}),i?Z?t.jsx(c.CommandGroup,{heading:"Partials",children:st.map(A=>t.jsxs(c.CommandItem,{value:A.key,onSelect:()=>ne(A.key),className:"flex cursor-pointer items-center justify-between",children:[A.name,t.jsx(w.Check,{className:nt("mr-2 h-4 w-4",p===A.key?"opacity-100":"opacity-0")})]},A.key))}):t.jsx(c.CommandGroup,{heading:"Pages",children:Bt.map(A=>t.jsxs(c.CommandItem,{value:A.key,onSelect:()=>ne(A.key),className:"flex cursor-pointer items-center justify-between",children:[A.name,t.jsx(w.Check,{className:nt("mr-2 h-4 w-4",p===A.key?"opacity-100":"opacity-0")})]},A.key))}):t.jsxs(t.Fragment,{children:[Bt.length>0&&t.jsx(c.CommandGroup,{heading:"Pages",children:Bt.map(A=>t.jsxs(c.CommandItem,{value:A.key,onSelect:()=>ne(A.key),className:"flex cursor-pointer items-center justify-between",children:[A.name,t.jsx(w.Check,{className:nt("mr-2 h-4 w-4",p===A.key?"opacity-100":"opacity-0")})]},A.key))}),st.length>0&&t.jsx(c.CommandGroup,{heading:"Partials",children:st.map(A=>t.jsxs(c.CommandItem,{value:A.key,onSelect:()=>ne(A.key),className:"flex cursor-pointer items-center justify-between",children:[A.name,t.jsx(w.Check,{className:nt("mr-2 h-4 w-4",p===A.key?"opacity-100":"opacity-0")})]},A.key))})]})]})]})})]}):t.jsx("select",{id:"pageType",value:p,disabled:i&&!C,onChange:A=>ne(A.target.value),className:`w-full rounded-md border border-gray-300 px-3 py-2 ${i&&!C?"cursor-not-allowed text-gray-500":""}`,children:i?Z?t.jsx("optgroup",{label:"Partials",children:s.filter(A=>A.hasSlug===!1).map(A=>t.jsx("option",{value:A.key,children:A.name},A.key))}):t.jsx("optgroup",{label:"Pages",children:s.filter(A=>A.hasSlug!==!1).map(A=>t.jsx("option",{value:A.key,children:A.name},A.key))}):t.jsxs(t.Fragment,{children:[t.jsx("optgroup",{label:"Pages",children:s.filter(A=>A.hasSlug!==!1).map(A=>t.jsx("option",{value:A.key,children:A.name},A.key))}),t.jsx("optgroup",{label:"Partials",children:s.filter(A=>A.hasSlug===!1).map(A=>t.jsx("option",{value:A.key,children:A.name},A.key))})]})}),L&&t.jsxs("div",{className:"mt-2 rounded-md border border-yellow-200 bg-yellow-50 p-3",children:[t.jsx("p",{className:"text-sm text-yellow-800",children:"Changing the page type may impact the page data. Are you sure you want to proceed?"}),t.jsxs("div",{className:"mt-2 flex gap-2",children:[t.jsx(c.Button,{variant:"outline",size:"sm",onClick:()=>k(!1),children:"Cancel"}),t.jsx(c.Button,{variant:"default",size:"sm",onClick:Ae,children:"Confirm"})]})]})]}),!i&&(z==null?void 0:z.hasSlug)&&de.length>0&&t.jsxs("div",{className:"space-y-1",children:[t.jsx(c.Label,{className:"mb-1 block text-sm",children:"Template"}),t.jsx(Ei,{templates:de,selectedTemplateId:V,onSelectTemplate:ce,isLoading:Y})]}),t.jsx(Si,{pages:l,selectedParentId:_,onChange:B}),t.jsxs("div",{className:"space-y-0.5",children:[t.jsx(c.Label,{htmlFor:"name",className:"text-sm",children:"Name"}),t.jsx(c.Input,{id:"name",value:fe,onChange:A=>be(A.target.value),required:!0,"aria-required":"true",placeholder:"Enter page name"})]}),(z==null?void 0:z.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:ue,onChange:A=>De(A.target.checked),className:"rounded border-gray-300"}),t.jsx(c.Label,{htmlFor:"useDynamicSlug",className:"text-sm",children:"Use Dynamic Slug"})]}),ue&&t.jsx("div",{className:"space-y-2",children:t.jsx("div",{className:"space-y-0.5",children:t.jsx(bi,{value:U,onChange:T,dynamicPattern:(z==null?void 0:z.dynamicSlug)||"{{id}}",placeholder:"Enter custom slug part (optional)",onValidationChange:se})})})]}),(!(z!=null&&z.dynamicSegments)||!ue)&&t.jsxs("div",{className:"space-y-0.5",children:[t.jsx(c.Label,{htmlFor:"slug",className:"text-sm",children:"Slug"}),t.jsx(un,{value:x,onChange:N,placeholder:_&&_!=="none"?"Enter page slug":p==="page"?"Leave empty for home page":"Required - e.g. your-slug",parentSlug:_&&_!=="none"?(os=l==null?void 0:l.find(A=>A.id===_))==null?void 0:os.slug:void 0,onValidationChange:y}),m&&t.jsx("p",{className:"text-xs text-red-500",children:m})]}),t.jsx(c.Button,{disabled:te||!j&&(!(z!=null&&z.dynamicSegments)||!ue)||ue&&!O,type:"submit",className:"w-full",children:i?te?"Updating...":"Update page":te?"Creating...":"Create Page"})]}):t.jsxs("form",{onSubmit:Dt,className:"mx-auto w-full max-w-md space-y-4",children:[t.jsxs("div",{className:"space-y-0.5",children:[t.jsx(c.Label,{htmlFor:"pageType",className:"text-sm",children:"Type"}),me?t.jsxs(c.Popover,{open:K,onOpenChange:Q,children:[t.jsx(c.PopoverTrigger,{asChild:!0,children:t.jsxs(c.Button,{variant:"outline",role:"combobox",disabled:i&&!C,className:nt("w-full justify-between",i&&!C?"cursor-not-allowed text-gray-500":""),children:[(z==null?void 0:z.name)||"Select page type",t.jsx(w.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),t.jsx(c.PopoverContent,{className:"w-[var(--radix-popover-trigger-width)] p-0",align:"start",children:t.jsxs(c.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(w.Search,{strokeWidth:2,className:"absolute left-2 top-2 h-4 w-4 text-gray-400"}),t.jsx(c.Input,{placeholder:"Search page types...",className:"h-8 pl-8 text-xs",value:M,onChange:A=>H(A.target.value)})]})}),t.jsxs(gs,{className:"max-h-[200px] overflow-y-auto",children:[t.jsx(c.CommandEmpty,{children:"No page type found."}),t.jsx(c.CommandGroup,{heading:"Partials",children:st.map(A=>t.jsxs(c.CommandItem,{value:A.key,onSelect:()=>{ne(A.key),Q(!1)},className:"flex cursor-pointer items-center justify-between",children:[A.name,t.jsx(w.Check,{className:nt("mr-2 h-4 w-4",p===A.key?"opacity-100":"opacity-0")})]},A.key))})]})]})})]}):t.jsx("select",{id:"pageType",value:p,disabled:i&&!C,onChange:A=>ne(A.target.value),className:`w-full rounded-md border border-gray-300 px-3 py-2 ${i&&!C?"cursor-not-allowed text-gray-500":""}`,children:t.jsx("optgroup",{label:"Partials",children:s.filter(A=>A.hasSlug===!1).map(A=>t.jsx("option",{value:A.key,children:A.name},A.key))})}),L&&t.jsxs("div",{className:"mt-2 rounded-md border border-yellow-200 bg-yellow-50 p-3",children:[t.jsx("p",{className:"text-sm text-yellow-800",children:"Changing the page type may impact the page data. Are you sure you want to proceed?"}),t.jsxs("div",{className:"mt-2 flex gap-2",children:[t.jsx(c.Button,{variant:"outline",size:"sm",onClick:()=>k(!1),children:"Cancel"}),t.jsx(c.Button,{variant:"default",size:"sm",onClick:Ae,children:"Confirm"})]})]}),t.jsx("p",{className:"text-xs text-gray-500",children:(ls=s.find(A=>A.key===p))==null?void 0:ls.helpText})]}),t.jsxs("div",{className:"space-y-0.5",children:[t.jsx(c.Label,{htmlFor:"name",className:"text-sm",children:"Name"}),t.jsx(c.Input,{id:"name",value:fe,onChange:A=>be(A.target.value),required:!0,"aria-required":"true"})]}),t.jsx(c.Button,{disabled:te,type:"submit",className:"w-full",children:i?te?"Updating...":"Update "+(z==null?void 0:z.name):te?"Creating...":"Create "+(z==null?void 0:z.name)})]})}const hn=({addEditPage:e,setAddEditPage:s,closePanel:n})=>{const{data:a}=Ce(),r=!!(e!=null&&e.id);return t.jsx(c.Dialog,{open:!!e,onOpenChange:()=>s(void 0),children:t.jsxs(c.DialogContent,{className:"sm:max-w-[425px]",children:[t.jsxs(c.DialogHeader,{children:[t.jsxs(c.DialogTitle,{children:[r?"Edit":"Add New"," "]}),t.jsx(c.DialogDescription,{children:r?"Update your page name":"Enter details to create a new page"})]}),t.jsx(Ti,{closePanel:n,addEditPage:e,close:()=>s(void 0),additionalPageTypes:a??[]})]})})};function ks({page:e,onClose:s}){const[,n]=_e(),{mutate:a,isPending:r}=ai(),{data:i}=Ce(),{setSelectedLang:l,fallbackLang:o}=F.useLanguages(),[,u]=F.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(o),u("outline"),s()}})},h=i==null?void 0:i.find(m=>m.key===(e==null?void 0:e.pageType));return t.jsx(c.Dialog,{open:!!e,onOpenChange:s,children:t.jsxs(c.DialogContent,{children:[t.jsxs(c.DialogHeader,{children:[t.jsx(c.DialogTitle,{children:"Confirm Deletion"}),t.jsxs(c.DialogDescription,{className:"py-4 text-slate-500",children:[t.jsxs("div",{children:["Are you sure you want to remove ",t.jsx("b",{children:(e==null?void 0:e.name)??(e==null?void 0:e.slug)})," ",h!=null&&h.hasSlug?(h==null?void 0:h.name)+"?":`page? ${e!=null&&e.primaryPage?"":"This will also delete all associated language pages."}`]}),e.lang&&t.jsxs("div",{className:"py-2 text-sm",children:["Language:"," ",t.jsx("span",{className:"font-medium text-gray-500",children:f.get(Te,e.lang,e.lang)})]})]})]}),t.jsxs(c.DialogFooter,{children:[t.jsx(c.Button,{variant:"outline",onClick:s,children:"Cancel"}),t.jsx(c.Button,{variant:"destructive",disabled:r,onClick:d,children:r?"Deleting...":"Delete"})]})]})})}const ki=()=>{const e=oe(),s=R.useQueryClient(),n=ee();return R.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:[W,I.GET_WEBSITE_PAGES]}),J.toast.success("Page duplicated successfully")},onError:a=>{J.toast.error("Failed to duplicate page",{description:a.message||"An error occurred while duplicating the page"})}})},mn=({page:e,onClose:s})=>{const{mutate:n,isPending:a}=ki(),[r,i]=g.useState(null),[l,o]=g.useState(`${e.name} (Copy)`),u=f.isEmpty(e.slug),[d,h]=g.useState(u?"":`${e.slug.split("/").pop()}-copy`),m=u?"":f.initial(e.slug.split("/")).join("/"),[b,j]=g.useState(!1),y=p=>{if(p.preventDefault(),!l.trim()){i("Name is required");return}if(!u&&!d.trim()){i("Slug is required");return}i(null),j(!0);const v={pageId:e.id,name:l};u||(v.slug=`${m}/${d}`),n(v,{onSuccess:()=>{j(!1),s()},onError:S=>{j(!1),S.code==="SLUG_EXISTS"?i("A page with this slug already exists. Please choose a different slug."):S.code==="INVALID_SLUG"?i("The slug format is invalid. Please use only lowercase letters, numbers, and hyphens."):S.code==="PERMISSION_DENIED"?i("You don't have permission to duplicate this page."):i(S.message||"Failed to duplicate page. Please try again later.")}})};return t.jsx(c.Dialog,{open:!!e,onOpenChange:s,children:t.jsxs(c.DialogContent,{className:"sm:max-w-[425px]",children:[t.jsxs(c.DialogHeader,{children:[t.jsx(c.DialogTitle,{children:"Duplicate Page"}),t.jsx(c.DialogDescription,{children:"Create a copy of the page with a new name and slug"})]}),t.jsxs("div",{className:"bg-gray-50 p-3 rounded-md mb-4",children:[t.jsx("h3",{className:"text-sm font-medium mb-1",children:"Duplicating:"}),t.jsxs("div",{className:"text-sm text-gray-700 flex flex-col gap-1",children:[t.jsxs("div",{children:[t.jsx("span",{className:"font-medium",children:"Name:"})," ",e.name]}),!u&&t.jsxs("div",{children:[t.jsx("span",{className:"font-medium",children:"Slug:"})," ",e.slug]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-medium",children:"Type:"})," ",e.pageType]})]})]}),t.jsxs("form",{onSubmit:y,className:"space-y-4",children:[t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Label,{htmlFor:"name",className:"text-sm",children:"Name"}),t.jsx(c.Input,{id:"name",value:l,onChange:p=>o(p.target.value),required:!0})]}),!u&&t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Label,{htmlFor:"slug",className:"text-sm",children:"Slug"}),t.jsx(un,{value:d,onChange:p=>h(p),parentSlug:m,onValidationChange:p=>{i(p?null:"Invalid slug")}})]}),r&&t.jsxs(c.Alert,{variant:"destructive",className:"py-2",children:[t.jsx(w.AlertCircle,{className:"h-4 w-4"}),t.jsx("span",{className:"text-sm",children:r})]}),t.jsxs("div",{className:"flex justify-end gap-2",children:[t.jsx(c.Button,{type:"button",variant:"outline",onClick:s,disabled:a,children:"Cancel"}),t.jsx(c.Button,{type:"submit",disabled:!l.trim()||!u&&!d.trim()||a||b,children:a||b?"Duplicating...":"Duplicate"})]})]})]})})},Pi=1*1024*1024,fn=({page:e,onClose:s})=>{const[n,a]=g.useState(!1),[r,i]=g.useState(""),[l,o]=g.useState(""),[u,d]=g.useState(!1),h=g.useRef(null),m=li(),{data:b}=Ce(),j=b==null?void 0:b.find(L=>L.key===e.pageType),y=(j==null?void 0:j.name)||f.startCase(e.pageType),p=g.useCallback(L=>{var D;const k=(D=L.target.files)==null?void 0:D[0];if(k){if(k.size>Pi){J.toast.error("File too large",{description:`Maximum file size is 1MB. Selected file is ${(k.size/1024).toFixed(2)}KB.`}),h.current&&(h.current.value="");return}try{d(!0);const G=new FileReader;G.onloadend=()=>{o(G.result),d(!1)},G.readAsDataURL(k)}catch(G){console.error("Error reading file:",G),d(!1),J.toast.error("Failed to process image",{description:G instanceof Error?G.message:"Unknown error"})}}},[]),v=()=>{o(""),h.current&&(h.current.value="")},S=()=>{var L;(L=h.current)==null||L.click()},C=()=>{a(!0),m.mutate({page:e,name:e.name,description:r.trim()||void 0,pageType:e.pageType,...l?{previewImage:l}:{}},{onSuccess:()=>{a(!1),s()},onError:()=>{a(!1)}})};return t.jsx(c.Dialog,{open:!0,onOpenChange:s,children:t.jsxs(c.DialogContent,{children:[t.jsxs(c.DialogHeader,{children:[t.jsx(c.DialogTitle,{children:"Mark as template"}),t.jsxs(c.DialogDescription,{className:"py-4 text-slate-500 space-y-1 text-xs",children:["Are you sure you want to mark this page as a template?",t.jsx("br",{}),"Templates can be used to create new pages with the same content."]})]}),t.jsxs("div",{className:"space-y-4 mb-4 text-xs",children:[t.jsxs("div",{className:"p-4 border rounded bg-slate-50 space-y-3",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(w.Tag,{className:"w-4 h-4 text-slate-500"}),t.jsx("span",{className:"font-medium text-slate-500",children:"Page Name:"}),t.jsx("span",{className:"font-semibold",children:f.startCase(e.name)})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(w.File,{className:"w-4 h-4 text-slate-500"}),t.jsx("span",{className:"font-medium text-slate-500",children:"Type:"}),t.jsx("span",{className:"font-semibold",children:y})]})]}),t.jsxs("div",{children:[t.jsx(c.Label,{htmlFor:"description",className:"text-xs font-medium",children:"Description (Optional)"}),t.jsx(c.Textarea,{id:"description",placeholder:"Describe this template's purpose",className:"text-xs resize-none h-24 mt-1",value:r,onChange:L=>i(L.target.value)})]}),t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Label,{htmlFor:"previewImage",className:"text-xs font-medium",children:"Preview Image (Optional)"}),t.jsxs("div",{className:"space-y-2",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(c.Input,{type:"file",id:"previewImage",ref:h,onChange:p,accept:"image/*",className:"hidden"}),t.jsx(c.Button,{type:"button",variant:"outline",onClick:S,disabled:u,className:"w-full",children:u?t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsx("div",{className:"animate-spin h-4 w-4 border-2 border-current border-t-transparent rounded-full"}),"Uploading..."]}):t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsx(w.ImageIcon,{className:"h-4 w-4"}),"Select image"]})}),l&&t.jsx(c.Button,{type:"button",variant:"outline",size:"icon",onClick:v,children:t.jsx(w.X,{className:"h-4 w-4"})})]}),l&&t.jsx("div",{className:"rounded-md overflow-hidden border aspect-video",children:t.jsx("img",{src:l,alt:"Preview",className:"w-full h-full max-h-[200px] object-contain"})}),t.jsx("p",{className:"text-xs text-muted-foreground",children:"max 1mb"})]})]})]}),t.jsxs(c.DialogFooter,{className:n?"opacity-75 pointer-events-none":"",children:[t.jsx(c.Button,{variant:"outline",onClick:L=>{L.stopPropagation(),s()},children:"Cancel"}),t.jsx(c.Button,{variant:"default",disabled:n,onClick:C,children:"Mark as template"})]})]})})},gn=({page:e,setDuplicatePage:s,setAddEditPage:n,setUnpublishPage:a,setDeletePage:r,setMarkAsTemplate:i,setUnmarkAsTemplate:l,children:o,isLanguagePage:u})=>{const{hasPermission:d}=F.usePermissions(),{data:h}=Ce(),m=g.useMemo(()=>f.find(h,{key:e.pageType}),[h,e.pageType]),b=g.useMemo(()=>!!e.isTemplate,[e.isTemplate]),j=g.useMemo(()=>!!(m!=null&&m.hasSlug),[m==null?void 0:m.hasSlug]);return!d(ve.EDIT_PAGE)&&!d(ve.DELETE_PAGE)&&!d(ve.UNPUBLISH_PAGE)||!e?null:t.jsxs(c.DropdownMenu,{children:[t.jsx(c.DropdownMenuTrigger,{asChild:!0,onClick:p=>p.stopPropagation(),children:o}),t.jsxs(c.DropdownMenuContent,{align:"center",className:"text-sm",children:[d(ve.ADD_PAGE)&&!u&&t.jsxs(c.DropdownMenuItem,{className:"flex cursor-pointer items-center gap-2",onClick:p=>{p.stopPropagation(),s(e)},children:[t.jsx(w.CopyPlusIcon,{className:"size-3"}),"Duplicate page"]}),d(ve.EDIT_PAGE)&&t.jsxs(c.DropdownMenuItem,{className:"flex cursor-pointer items-center gap-2",onClick:p=>{p.stopPropagation(),n({...e,global:!(m!=null&&m.hasSlug)})},children:[t.jsx(w.Pencil,{className:"size-3"}),"Edit"]}),(e==null?void 0:e.online)&&d(ve.UNPUBLISH_PAGE)&&t.jsxs(c.DropdownMenuItem,{className:"flex cursor-pointer items-center gap-2",onClick:p=>{p.stopPropagation(),a(e)},children:[t.jsx(w.Power,{className:"size-3"}),le.UNPUBLISH]}),d(ve.DELETE_PAGE)&&t.jsxs(c.DropdownMenuItem,{className:"flex cursor-pointer items-center gap-2",onClick:p=>{p.stopPropagation(),r(e)},children:[t.jsx(w.Trash,{className:"size-3"}),le.DELETE]}),d(ve.MARK_AS_TEMPLATE)&&j&&!u&&t.jsx(t.Fragment,{children:b?t.jsxs(c.DropdownMenuItem,{className:"flex cursor-pointer items-center gap-2",onClick:p=>{p.stopPropagation(),l(e)},children:[t.jsx(w.SquareLibrary,{className:"size-3"}),le.UNMARK_AS_TEMPLATE]}):t.jsxs(c.DropdownMenuItem,{className:"flex cursor-pointer items-center gap-2",onClick:p=>{p.stopPropagation(),i(e)},children:[t.jsx(w.SquareLibrary,{className:"size-3"}),le.MARK_AS_TEMPLATE]})})]})]})},xn=({page:e,onClose:s})=>{const[n,a]=g.useState(!1),r=oi(),i=()=>{a(!0),r.mutate(e,{onSuccess:()=>{a(!1),s()},onError:()=>{a(!1)}})};return t.jsx(c.Dialog,{open:!0,onOpenChange:s,children:t.jsxs(c.DialogContent,{children:[t.jsxs(c.DialogHeader,{children:[t.jsx(c.DialogTitle,{children:"Unmark as template"}),t.jsx(c.DialogDescription,{className:"py-4 text-slate-500 space-y-1 text-xs",children:"Are you sure you want to unmark this page as a template?"})]}),t.jsxs(c.DialogFooter,{className:n?"opacity-75 pointer-events-none":"",children:[t.jsx(c.Button,{variant:"outline",onClick:l=>{l.stopPropagation(),s()},children:"Cancel"}),t.jsx(c.Button,{variant:"default",disabled:n,onClick:i,children:"Unmark as template"})]})]})})},is=({page:e,onClose:s})=>{const{mutate:n,isPending:a}=ri(),r=async()=>{n(e,{onSuccess:s})};return t.jsx(c.Dialog,{open:!!e,onOpenChange:s,children:t.jsxs(c.DialogContent,{children:[t.jsxs(c.DialogHeader,{children:[t.jsx(c.DialogTitle,{children:"Confirm action"}),t.jsxs(c.DialogDescription,{children:[le.UNPUBLISH_MSG," ",t.jsx("b",{children:(e==null?void 0:e.name)??(e==null?void 0:e.slug)}),"?"]})]}),t.jsxs(c.DialogFooter,{children:[t.jsx(c.Button,{variant:"outline",onClick:s,children:"Cancel"}),t.jsx(c.Button,{variant:"destructive",disabled:a,onClick:r,children:a?le.UPDATING:le.UNPUBLISH})]})]})})},_i=Wn("expandedPagesState",[]),pn=e=>f.flatMap(e,s=>[s,...s.children?pn(s.children):[]]),Ii=(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 o=n(i.children,l);if(o)return o}}return null};return n(e)||[]},ga=(e,s)=>{if(!s)return[];const n=pn(e),a=f.find(n,r=>r.id===s);if(a){if(a.parent)return[...ga(e,a.parent),s];const r=Ii(e,s);if(!f.isEmpty(r))return r}return[s]},Li=e=>{const s=new Set,n=(a,r=[])=>{a.forEach(i=>{const l=[...r,i.id];i.shouldExpandOnSearch&&l.forEach(o=>s.add(o)),i.children&&!f.isEmpty(i.children)&&n(i.children,l)})};return n(e),Array.from(s)},It=e=>{const[s,n]=we.useAtom(_i),a=e?f.includes(s,e):!1,r=g.useCallback(()=>{n(d=>a?f.filter(d,h=>h!==e):[...d,e])},[n,a,e]),i=g.useCallback((d,h)=>{if(!h||f.isEmpty(d))return;const m=pn(d),b=ga(m,h);if(!Array.isArray(b)||f.isEmpty(b))return;const j=b.slice(0,-1);f.isEmpty(j)||n(y=>f.uniq([...y,...j]))},[n]),l=g.useCallback(d=>{if(f.isEmpty(d))return;const h=Li(d);f.isEmpty(h)||n(m=>f.union(m,h))},[n]),o=g.useCallback(d=>{if(f.isEmpty(d))return;const h=f.flatMap(d,m=>{const b=j=>[j.id,...j.children?f.flatMap(j.children,b):[]];return b(m)});n(h)},[n]),u=g.useCallback(()=>{n([])},[n]);return{isExpanded:a,toggleExpanded:r,updateForSelectedPage:i,expandedPages:s,expandPagesOnSearch:l,setExpandedPages:n,expandAll:o,collapseAll:u}},Tn=(e,s)=>!e||!Array.isArray(e)?[]:f.isEmpty(s)?e:f.compact(f.filter(e,n=>{const a=f.toLower(s);return f.includes(f.toLower((n==null?void 0:n.name)||""),a)||f.includes(f.toLower((n==null?void 0:n.slug)||""),a)})),Di=(e,s)=>{const n=new Set,a=f.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])},qs=(e,s,n)=>f.isEmpty(s)?e:e.map(a=>{if(!n(a.pageType))return{...a,shouldExpandOnSearch:!0,children:a.children?qs(a.children,s,n):[]};const r=a.children&&a.children.some(i=>f.includes(f.toLower(i.name||""),f.toLower(s))||f.includes(f.toLower(i.slug||""),f.toLower(s)));return{...a,shouldExpandOnSearch:r,children:a.children?qs(a.children,s,n):[]}}),Bi=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},xa=e=>!e||!e.length?[]:[...e].sort((n,a)=>(n.name||"").localeCompare(a.name||"")).map(n=>({...n,children:n.children?xa(n.children):[]})),pa=(e,s,n,a)=>{if(!e||!e.length)return[];let r=e;if(n!=="all"&&(r=f.compact(f.filter(e,{pageType:n}))),f.isEmpty(s))r=Tn(r,s);else{const h=Tn(r,s),m=Di(e,h);r=f.uniqBy([...h,...m],"id")}const i=xa(Bi(r)),l=qs(i,s,a),o=f.filter(l,h=>a(h.pageType)).sort((h,m)=>(h.name||"").localeCompare(m.name||"")),u=f.filter(l,h=>!a(h.pageType));let d=[];if(n==="all"){const h=f.keyBy(u,"pageType");d=Object.values(f.mapValues(h,(m,b)=>({...m,id:b,name:f.startCase(b),isPartialGroup:!0,children:l.filter(j=>j.pageType===b)})))}else d=u.sort((h,m)=>(h.name||"").localeCompare(m.name||""));return[...o,...d]},Gi=({parentSlug:e,page:s,active:n,closePanel:a,setUnpublishPage:r,setDeletePage:i,setAddEditPage:l,setMarkAsTemplate:o,setUnmarkAsTemplate:u,setDuplicatePage:d,hasChildren:h,isExpanded:m,onToggleExpand:b})=>{const j=dn(),{data:y}=Ce(),[,p]=F.useSidebarActivePanel(),v=g.useMemo(()=>f.find(y,{key:s.pageType}),[y,s.pageType]),S=g.useMemo(()=>{const D=f.get(s,"slug",""),G=e?Ze(e):"",X=G?D.replace(G,""):D;return X||"/"},[s,e]),C=g.useMemo(()=>!!s.isTemplate,[s.isTemplate]),L=g.useCallback(()=>{p("outline"),j(f.get(s,"id"),a)},[j,a,s,p]),k=g.useCallback(D=>{D.stopPropagation(),b()},[b]);return t.jsxs("div",{onClick:s.isPartialGroup?k:L,className:`flex cursor-pointer items-center justify-between rounded p-1.5 px-3 py-1.5 leading-none ${n?"bg-gray-200":"hover:bg-gray-100"}`,children:[t.jsxs("div",{className:"flex items-center gap-x-2",children:[t.jsx("button",{onClick:k,disabled:!h,className:`flex h-5 w-4 items-center justify-center text-gray-400 transition-colors hover:text-gray-500 ${h?"hover:text-blue-400":"opacity-0"}`,children:t.jsx(w.ChevronRight,{size:16,className:`h-5 w-4 transition-transform duration-200 ${m?"rotate-90":""}`})}),s.dynamic?t.jsx("div",{className:"h-4 w-4 stroke-[1] text-slate-500",children:t.jsx(w.StarsIcon,{className:"h-4 w-4 text-yellow-400"})}):v!=null&&v.icon?t.jsx("div",{className:"h-4 w-4 stroke-[1] text-slate-500",dangerouslySetInnerHTML:{__html:v.icon}}):v!=null&&v.hasSlug?t.jsx(w.File,{className:"h-4 w-4 stroke-[1] text-slate-500"}):t.jsx(w.Globe,{className:"h-4 w-4 stroke-[1] text-slate-500"}),!s.isPartialGroup&&t.jsx("div",{className:`h-2.5 w-2.5 rounded-full ${s.online?"bg-green-300":"bg-gray-300"}`}),t.jsx("span",{className:"truncate font-light leading-none text-slate-800",children:s.name}),v!=null&&v.hasSlug?t.jsxs(c.Badge,{variant:"outline",className:`ml-2 max-w-full rounded-full border py-px text-xs font-normal leading-tight text-gray-400 ${n?"border-gray-300":"border-gray-200"}`,children:[S,s.dynamic&&t.jsxs("span",{className:"text-xs font-light leading-none text-slate-500",children:[f.endsWith(S,"/")?`${v==null?void 0:v.dynamicSlug}`:`/${v==null?void 0:v.dynamicSlug}`,s.dynamicSlugCustom]})]}):s.isPartialGroup?null:t.jsx(c.Badge,{variant:"outline",className:`ml-2 max-w-full rounded-full border py-px text-xs font-normal leading-tight text-gray-400 ${n?"border-gray-300":"border-gray-200"}`,children:v==null?void 0:v.name}),C&&t.jsx(c.Badge,{variant:"outline",className:"ml-2 border border-blue-200 bg-blue-50 py-0 text-xs font-normal text-blue-500",children:"Template"})]}),!s.isPartialGroup&&t.jsxs("div",{className:"flex items-center space-x-4",children:[t.jsx(Or,{currentEditor:s.currentEditor}),t.jsx(gn,{page:s,setDuplicatePage:d,setAddEditPage:l,setUnpublishPage:r,setDeletePage:i,setMarkAsTemplate:o,setUnmarkAsTemplate:u,children:t.jsx("div",{className:"m-0 cursor-pointer rounded p-0.5 duration-100 hover:bg-white",children:t.jsx(w.MoreHorizontal,{className:"h-4 w-4",onClick:D=>D.stopPropagation()})})})]})]})},Mi=({close:e})=>{const[,s]=g.useState([]),[n,a]=g.useState(null),[r,i]=g.useState(""),[l,o]=g.useState(""),[u,d]=g.useState(null),h=T=>l?String(f.get(T,"name","")).toLowerCase().includes(l.toLowerCase())||String(f.get(T,"key","")).toLowerCase().includes(l.toLowerCase()):!0,[m,b]=g.useState(null),[j,y]=g.useState(null),[p,v]=g.useState(null),[S,C]=g.useState(null),{data:L,isFetching:k}=ot(),[D,G]=g.useState(""),{hasPermission:X}=F.usePermissions(),{updateForSelectedPage:$,expandPagesOnSearch:P,expandAll:M,collapseAll:H}=It(null),[K,Q]=_e(),Z=K.get("page"),_=g.useRef(null),{data:q}=Ce(),fe=F.useChaiFeatureFlag("enable-add-page-dropdown"),be=g.useCallback(T=>{var O;return(O=f.find(q,{key:T}))==null?void 0:O.hasSlug},[q]);g.useEffect(()=>{if(!f.isEmpty(D))return;const T=sessionStorage.getItem("pageTypeFilter")||"all";!f.isEmpty(q)&&T&&(f.find(q,{key:T})?G(T):G("all"))},[q,D]);const ue=T=>{G(T),sessionStorage.setItem("pageTypeFilter",T),o("")},E=g.useCallback(T=>{const se=new URLSearchParams(window.location.search).get("lang"),V=new URLSearchParams({page:T});se&&V.set("lang",se),window.history.pushState({},"",`?${V.toString()}`),Q(V),window.dispatchEvent(new PopStateEvent("popstate")),e()},[Q,e]);g.useEffect(()=>{if(Z&&!k){const T=f.find(L,{id:Z});T&&(T!=null&&T.pageType)?s(O=>[...O,T==null?void 0:T.pageType]):(window.history.replaceState(null,"","/"),Q(new URLSearchParams({})),window.dispatchEvent(new PopStateEvent("popstate")))}},[L,Z,k,Q]);const x=g.useMemo(()=>L?pa(L,r,D,be):[],[L,r,D,be]);g.useEffect(()=>{Z&&!k&&!f.isEmpty(x)&&($(x,Z),_.current&&_.current.scrollIntoView({behavior:"smooth",block:"end"}))},[Z,k,x,$]),g.useEffect(()=>{!f.isEmpty(r)&&!f.isEmpty(x)&&P(x)},[r,x,P]);const N=g.useCallback(()=>{M(x)},[M,x]),U=g.useCallback(()=>{H()},[H]);return t.jsxs("div",{className:"flex h-full flex-col justify-between",children:[t.jsxs("div",{className:"flex h-full flex-col space-y-6",children:[t.jsxs("div",{className:"flex items-center justify-between gap-1",children:[t.jsxs("div",{className:"item-center relative flex flex-1 gap-x-4",children:[t.jsx(w.Search,{strokeWidth:2.5,className:"absolute left-3 top-2.5 h-4 w-4 text-gray-400"}),t.jsx(c.Input,{placeholder:"Search pages...",className:"pl-9 pr-24 text-xs font-medium leading-none text-gray-700 placeholder:text-gray-400",value:r,onChange:T=>i(T.target.value)}),!f.isEmpty(D)&&t.jsxs(c.Select,{value:D,onValueChange:ue,children:[t.jsx(c.SelectTrigger,{className:`${D==="all"?"bg-gray-50 hover:bg-gray-100":"bg-gray-100 hover:bg-gray-50"} absolute right-1.5 top-1.5 -mt-px h-max w-max min-w-[120px] whitespace-nowrap p-0 py-1 pl-2 pr-1 text-xs text-gray-600 shadow-none ring-0 focus:ring-0`,children:t.jsx(c.SelectValue,{placeholder:"Select page type"})}),t.jsxs(c.SelectContent,{align:"end",children:[fe&&t.jsx("div",{className:"sticky top-0 z-10 bg-white px-3 py-2",children:t.jsxs("div",{className:"relative",children:[t.jsx(w.Search,{strokeWidth:2,className:"absolute left-2 top-2 h-4 w-4 text-gray-400"}),t.jsx(c.Input,{placeholder:"Search page types...",className:"h-8 pl-8 text-xs",value:l,onChange:T=>o(T.target.value),onKeyDown:T=>T.stopPropagation()})]})}),t.jsx(c.SelectItem,{value:"all",children:"All"},"all"),!f.isEmpty(f.filter(q,T=>T.hasSlug&&h(T)))&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"mt-2 border-t px-2 py-1.5 pt-2 text-xs font-semibold text-gray-500",children:"Pages"}),f.map([...f.filter(q,T=>T.hasSlug&&h(T))].sort((T,O)=>f.get(T,"name","").localeCompare(f.get(O,"name",""))),T=>t.jsx(c.SelectItem,{value:f.get(T,"key"),children:f.get(T,"name")},f.get(T,"key")))]}),!f.isEmpty(f.filter(q,T=>!T.hasSlug&&h(T)))&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"mt-2 border-t px-2 py-1.5 pt-2 text-xs font-semibold text-gray-500",children:"Partials"}),f.map([...f.filter(q,T=>!T.hasSlug&&h(T))].sort((T,O)=>f.get(T,"name","").localeCompare(f.get(O,"name",""))),T=>t.jsx(c.SelectItem,{value:f.get(T,"key"),children:f.get(T,"name")},f.get(T,"key")))]}),f.isEmpty(f.filter(q,h))&&t.jsx("div",{className:"px-3 py-2 text-center text-sm text-gray-500",children:"No matching page types found"})]})]})]}),t.jsxs("div",{className:"flex gap-1",children:[t.jsx(c.Button,{variant:"outline",size:"icon",onClick:N,className:"p-1 text-gray-500",children:t.jsx(w.ChevronsUpDown,{})}),t.jsx(c.Button,{variant:"outline",size:"icon",onClick:U,className:"p-1 text-gray-500",children:t.jsx(w.ChevronsDownUp,{})})]})]}),k?t.jsx("div",{className:"space-y-2",children:f.map([...Array(5).keys()],T=>t.jsx("div",{className:"h-9 w-full animate-pulse rounded bg-gray-200"},T))}):f.isEmpty(x)?t.jsxs("div",{className:"flex h-[70vh] flex-col items-center justify-center gap-y-1 text-sm font-medium text-slate-500",children:[t.jsx(w.File,{className:"h-6 w-6 stroke-[1]"}),"Empty List!",t.jsx("span",{className:"font-light",children:"Add new page to start"})]}):t.jsx("div",{className:"h-[70vh] space-y-2 overflow-y-auto text-sm text-slate-700",children:f.map(x,T=>{const O=T.id===Z;return t.jsx("div",{ref:O?_:null,children:t.jsx(ya,{item:T,currentPage:Z,close:e,setUnpublishPage:b,setDeletePage:d,setAddEditPage:y,setMarkAsTemplate:v,setUnmarkAsTemplate:C,setDuplicatePage:a,level:0})},`page-item-${T.id}`)})})]}),X(ve.ADD_PAGE)&&t.jsxs(c.Button,{className:"flex gap-x-2 text-sm",onClick:()=>{y({slug:"",name:"",pageType:D==="all"?"page":D})},children:[t.jsx(w.Plus,{className:"h-4 w-4"})," Add New"]}),j&&t.jsx(hn,{closePanel:e,editPage:E,addEditPage:j,setAddEditPage:y}),u&&t.jsx(ks,{page:u,onClose:()=>d(null)}),m&&t.jsx(is,{page:m,onClose:()=>b(null)}),p&&t.jsx(fn,{page:p,onClose:()=>v(null)}),S&&t.jsx(xn,{page:S,onClose:()=>C(null)}),n&&t.jsx(mn,{page:n,onClose:()=>a(null)})]})},ya=({item:e,currentPage:s,close:n,setUnpublishPage:a,setDeletePage:r,setAddEditPage:i,setMarkAsTemplate:l,setUnmarkAsTemplate:o,setDuplicatePage:u,parentSlug:d,level:h=0})=>{const m=!f.isEmpty(e==null?void 0:e.children),{isExpanded:b,toggleExpanded:j}=It(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:o,setDuplicatePage:u,active:s===e.id,page:e,parentSlug:d,hasChildren:m,isExpanded:b,onToggleExpand:j}),m&&b&&t.jsx("div",{className:"bg-white pl-6 pt-2",children:f.map(f.get(e,"children",[]),y=>t.jsx(ya,{item:y,currentPage:s,close:n,setUnpublishPage:a,setDeletePage:r,setAddEditPage:i,setMarkAsTemplate:l,setUnmarkAsTemplate:o,setDuplicatePage:u,parentSlug:e.slug,level:h+1},y.id||`child-${h}-${y.key}`))})]},e.id||`level-${h}-${e.key}`)},Ri=({selectedPageType:e,setSelectedPageType:s})=>{const[n,a]=g.useState(""),{data:r}=Ce(),i=l=>{if(!n)return!0;const o=n.toLowerCase(),u=d=>String(f.get(l,d,"")).toLowerCase().includes(o);return u("name")||u("key")};return t.jsxs(c.Select,{onValueChange:s,value:e,children:[t.jsx(c.SelectTrigger,{className:`${e===""?"bg-gray-100/30 hover:bg-gray-100":"gap-x-1 bg-gray-100 hover:bg-gray-50"} h-max w-max min-w-[120px] whitespace-nowrap rounded p-0 py-1 pl-2 pr-1 text-xs text-gray-600 shadow-none ring-0 focus:ring-0`,children:t.jsx(c.SelectValue,{placeholder:"Select page type"})}),t.jsxs(c.SelectContent,{children:[t.jsx("div",{className:"sticky top-0 z-10 bg-white pb-2",children:t.jsxs("div",{className:"relative",children:[t.jsx(w.Search,{strokeWidth:2,className:"absolute left-2 top-2.5 h-3.5 w-3.5 text-gray-400"}),t.jsx(c.Input,{placeholder:"Search page types...",className:"h-8 w-full rounded border pl-8 text-xs shadow-none",value:n,onChange:l=>a(l.target.value),onKeyDown:l=>l.stopPropagation()})]})}),t.jsx(c.SelectItem,{value:"all",children:"All"}),!f.isEmpty(f.filter(r,l=>l.hasSlug&&i(l)))&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"mt-2 border-t px-2 py-1.5 pt-2 text-xs font-semibold text-gray-500",children:"Pages"}),f.map([...f.filter(r,l=>l.hasSlug&&i(l))].sort((l,o)=>f.get(l,"name","").localeCompare(f.get(o,"name",""))),l=>t.jsx(c.SelectItem,{value:f.get(l,"key"),children:f.get(l,"name")},f.get(l,"key")))]}),!f.isEmpty(f.filter(r,l=>!l.hasSlug&&i(l)))&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"mt-2 border-t px-2 py-1.5 pt-2 text-xs font-semibold text-gray-500",children:"Partials"}),f.map([...f.filter(r,l=>!l.hasSlug&&i(l))].sort((l,o)=>f.get(l,"name","").localeCompare(f.get(o,"name",""))),l=>t.jsx(c.SelectItem,{value:f.get(l,"key"),children:f.get(l,"name")},f.get(l,"key")))]}),f.isEmpty(f.filter(r,i))&&t.jsx("div",{className:"px-3 py-2 text-center text-sm text-gray-500",children:"No matching page types found"})]})]})},Ui=({search:e,setSearch:s,selectedPageType:n,setSelectedPageType:a})=>t.jsxs("div",{className:"relative flex h-9 flex-1 items-center gap-2 rounded-md border pl-3 pr-1",children:[t.jsx("label",{htmlFor:"page-search-input",className:"sr-only",children:"Search Pages"}),t.jsx(w.Search,{className:"pointer-events-none h-4 w-4 text-muted-foreground","aria-hidden":"true"}),t.jsx(c.Input,{id:"page-search-input",placeholder:"Search pages",value:e,onChange:r=>s(r.target.value),className:"border-none px-1.5 shadow-none outline-none ring-0 transition-none focus:outline-none focus:ring-0 focus-visible:ring-0",autoComplete:"off"}),t.jsx(Ri,{selectedPageType:n,setSelectedPageType:a})]}),Fi=({pages:e})=>{const{expandAll:s,collapseAll:n,expandedPages:a}=It(null);return t.jsxs("div",{className:"flex gap-1",children:[t.jsxs(c.Tooltip,{children:[t.jsx(c.TooltipTrigger,{children:t.jsx(c.Button,{variant:"outline",size:"icon",onClick:()=>s(e),className:"rounded p-1 text-gray-500",children:t.jsx(w.ChevronsUpDown,{})})}),t.jsx(c.TooltipContent,{children:"Expand All"})]}),t.jsxs(c.Tooltip,{children:[t.jsx(c.TooltipTrigger,{children:t.jsx(c.Button,{disabled:a.length===0,variant:"outline",size:"icon",onClick:()=>n(),className:"rounded p-1 text-gray-500",children:t.jsx(w.ChevronsDownUp,{})})}),t.jsx(c.TooltipContent,{children:"Collapse All"})]})]})},ja=({languages:e,selectedLanguage:s,setSelectedLanguage:n})=>{const a=Qe();return t.jsx("div",{className:"scrollbar-hide flex gap-1 overflow-x-auto pb-1",children:e.map(r=>t.jsxs(c.Button,{variant:s===r?"default":"outline",size:"sm",className:`h-6 flex-shrink-0 whitespace-nowrap rounded px-3 text-xs font-normal ${s===r?"bg-black text-white hover:bg-black":"text-gray-500"}`,onClick:()=>n(r.toLowerCase()),children:[r===a&&t.jsx(w.Star,{size:4,className:`p-0.5 ${s===a?"fill-white":"fill-black"}`}),Te[r]||""]},r))})},kn=()=>{const e=R.useQueryClient();return t.jsxs(c.Tooltip,{children:[t.jsx(c.TooltipTrigger,{children:t.jsx(c.Button,{size:"sm",variant:"ghost",onClick:()=>e.invalidateQueries({queryKey:[W,I.GET_WEBSITE_PAGES]}),className:"h-6 w-6",children:t.jsx(w.RefreshCw,{})})}),t.jsx(c.TooltipContent,{side:"bottom",children:"Refresh pages list"})]})},Oi=({pages:e,search:s,setSearch:n,languages:a,onAddPage:r,selectedLanguage:i,setSelectedLanguage:l,selectedPageType:o,setSelectedPageType:u})=>{const d=a.length>1;return t.jsxs("div",{className:"space-y-3 border-b border-b-gray-200 px-4",children:[t.jsxs("div",{className:"flex items-center gap-x-2",children:[t.jsx(Ui,{search:s,setSearch:n,selectedPageType:o,setSelectedPageType:u}),t.jsx(Fi,{pages:e}),t.jsxs(c.Button,{variant:"default",onClick:r,className:"rounded px-3 font-normal",children:[t.jsx(w.Plus,{strokeWidth:2,className:"stroke-white stroke-[3]"}),t.jsx("span",{className:"font-normal text-white",children:"Add Page"})]}),!d&&t.jsx(kn,{})]}),d?t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx(ja,{languages:a,selectedLanguage:i,setSelectedLanguage:l}),t.jsx(kn,{})]}):t.jsx("div",{className:"flex items-center justify-between gap-2"})]})};function lt({children:e,content:s,side:n="bottom",delayDuration:a=700,showTooltip:r=!0}){return r?t.jsx(c.TooltipProvider,{children:t.jsxs(c.Tooltip,{delayDuration:a,children:[t.jsx(c.TooltipTrigger,{asChild:!0,children:e}),t.jsx(c.TooltipContent,{side:n,sideOffset:10,children:t.jsx("p",{children:s})})]})}):e}const qi=({page:e})=>{var a,r;const{isExpanded:s,toggleExpanded:n}=It(e==null?void 0:e.id);return t.jsx("button",{onClick:i=>{i.stopPropagation(),n()},disabled:!((a=e==null?void 0:e.children)!=null&&a.length),className:`flex h-[calc(100%-2px)] w-5 items-center justify-center rounded text-gray-400 transition-colors hover:bg-gray-200 hover:px-1 hover:text-gray-500 ${(r=e==null?void 0:e.children)!=null&&r.length?"hover:text-blue-400":"opacity-0"}`,children:t.jsx(w.ChevronRight,{size:12,className:`stroke-[4] transition-transform duration-200 ${s?"rotate-90":""}`})})},$i=({page:e,pageType:s})=>t.jsx("div",{className:"flex h-full items-center justify-center gap-x-1",children:e.dynamic?t.jsx(w.StarsIcon,{size:12,className:"text-yellow-400"}):s!=null&&s.icon?t.jsx("div",{className:"flex h-4 max-h-4 w-4 max-w-4 items-center justify-center stroke-[1] text-slate-500",dangerouslySetInnerHTML:{__html:s.icon}}):s!=null&&s.hasSlug?t.jsx(w.File,{size:12,className:"stroke-[1] text-slate-500"}):t.jsx(w.Globe,{size:12,className:"stroke-[1] text-slate-500"})}),zi=({isOnline:e})=>t.jsx("div",{className:`h-2 w-2 rounded-full ${e?"bg-green-300":"bg-gray-300"}`}),Vi=({page:e,pageTypes:s,currentPage:n,onClickAction:a,languagePages:r,selectedLanguage:i})=>{const l=Qe(),o=n===e.id,u=!!e.isTemplate,d=g.useMemo(()=>f.find(s,{key:e.pageType}),[s,e.pageType]);let h=f.get(r,e==null?void 0:e.id);h=f.get(h,"lang")===i?h:null;const m=i===l||!!h,b=(h==null?void 0:h.name)||(e==null?void 0:e.name)||"No name";let j=(h==null?void 0:h.slug)||(e==null?void 0:e.slug)||"";j.startsWith("/")&&j.startsWith(`/${e.lang}`)&&(j=`/${j.split("/").pop()}`);const y=g.useMemo(()=>{const p="flex h-7 min-w-0 flex-1 cursor-pointer select-none items-center gap-x-1.5 rounded px-px text-xs duration-300 border-[1px]",v=`${o?"border-primary/30 bg-primary/5":"border-transparent hover:border-gray-200 hover:bg-gray-100"}`;return m?`${p} ${v}`:`${p} bg-gray-100 opacity-50 group-hover:border-gray-200 border-transparent group-hover:bg-blue-100`},[m,o]);return t.jsxs("div",{className:"group relative",children:[t.jsxs("div",{onClick:()=>!e.isPartialGroup&&m&&a("select",e==null?void 0:e.id),className:y,children:[t.jsx(qi,{page:e}),!e.isPartialGroup&&t.jsx(zi,{isOnline:e.online}),t.jsx($i,{page:e,pageType:d}),t.jsx(lt,{content:b,side:"top",delayDuration:0,showTooltip:b.length>35,children:t.jsx("span",{className:"max-w-[40%] truncate font-medium text-black",children:b})}),j&&t.jsx(lt,{content:j,side:"top",delayDuration:0,showTooltip:j.length>35,children:t.jsxs("span",{className:"max-w-[40%] truncate font-mono text-xs text-muted-foreground",children:[j,e.dynamic&&(d==null?void 0:d.dynamicSlug)&&t.jsxs("span",{className:"text-xs text-gray-500",children:["/",d.dynamicSlug]})]})}),u&&t.jsx(lt,{content:"Template",side:"top",delayDuration:0,children:t.jsx("span",{className:"text-blue-500",children:t.jsx(w.NotepadText,{size:16})})}),!e.isPartialGroup&&m&&t.jsx("div",{className:"duration absolute right-0.5 top-[3px]",children:t.jsx(gn,{isLanguagePage:!!h,page:h||e,setDuplicatePage:p=>a("duplicate",p),setAddEditPage:p=>a("edit",h||p),setUnpublishPage:p=>a("unpublish",p),setDeletePage:p=>a("delete",h||p),setMarkAsTemplate:p=>a("markAsTemplate",p),setUnmarkAsTemplate:p=>a("unmarkAsTemplate",p),children:t.jsx("div",{className:"m-0 cursor-pointer rounded border border-transparent p-0.5 duration-100 hover:border-gray-400 hover:bg-white",children:t.jsx(w.MoreHorizontal,{className:"h-4 w-4",onClick:p=>p.stopPropagation()})})})})]}),t.jsx(t.Fragment,{children:!m&&!e.isPartialGroup&&t.jsxs("button",{onClick:p=>{p.stopPropagation(),a("addLanguagePage",{language:i,page:e})},className:"absolute left-1/2 top-1 flex -translate-x-1/2 items-center gap-x-1 rounded bg-blue-500 px-2 py-0.5 text-xs text-white opacity-0 duration-200 hover:bg-blue-700 group-hover:opacity-100",children:[t.jsx(w.Plus,{size:12,className:"stroke-[3]"})," ",t.jsxs("span",{className:"text-[10px]",children:["Add ",f.get(Te,i)," Page"]})]})})]})},va=({pages:e,tier:s,pageTypes:n,currentPage:a,onClickAction:r,languagePages:i,selectedLanguage:l})=>{const{expandedPages:o}=It();return t.jsx("div",{className:"space-y-0.5",style:{paddingLeft:`${s*10}px`},children:e.map(u=>t.jsxs(t.Fragment,{children:[t.jsx(Vi,{page:u,pageTypes:n,currentPage:a,onClickAction:r,languagePages:i,selectedLanguage:l}),u.children&&u.children.length>0&&(o==null?void 0:o.includes(u.id))&&t.jsx(va,{pages:u.children,tier:s+1,pageTypes:n,currentPage:a,onClickAction:r,languagePages:i,selectedLanguage:l})]},u.id))})},Ki=({close:e})=>{const{languages:s,setSelectedLang:n,selectedLang:a}=F.useLanguages(),{data:r}=Ce(),{data:i,isFetching:l}=ot(),[o,u]=_e(),{updateForSelectedPage:d}=It(null),h=Qe(),m=o.get("page"),[b,j]=g.useState(""),[y,p]=g.useState(null),[v,S]=g.useState(null),[C,L]=g.useState(null),[k,D]=g.useState(null),[G,X]=g.useState(""),[$,P]=g.useState(null),[M,H]=g.useState(null),[K,Q]=g.useState(a||h),[,Z]=we.useAtom(Ts),{data:_,isFetching:q}=Gr(K),fe=g.useCallback(x=>{var N;return(N=f.find(r,{key:x}))==null?void 0:N.hasSlug},[r]),be=g.useMemo(()=>i?pa(i,b,G,fe):[],[i,fe,b,G]);g.useEffect(()=>{if(!f.isEmpty(G))return;const x=sessionStorage.getItem("pageTypeFilter")||"all";!f.isEmpty(r)&&x&&(f.find(r,{key:x})?X(x):X("all"))},[r,G]),g.useEffect(()=>{m&&!l&&(f.find(i,{id:m})||(window.history.replaceState(null,"","/"),u(new URLSearchParams({})),window.dispatchEvent(new PopStateEvent("popstate"))))},[i,m,l,u]),g.useEffect(()=>{m&&!l&&!f.isEmpty(be)&&d(be,m)},[m,l,be,d]);const ue=g.useCallback(x=>{const N=new URLSearchParams({page:x});K!==h&&N.set("lang",K),n(K),window.history.pushState({},"",`?${N.toString()}`),u(N),window.dispatchEvent(new PopStateEvent("popstate")),e()},[e,u,K,n,h]),E=(x,N)=>{var U;if(N)switch(x){case"add":S(N);break;case"select":ue(N);break;case"edit":K!==h?Z({edit:!0,id:N==null?void 0:N.id,primaryPage:N==null?void 0:N.primaryPage}):S(N);break;case"delete":p(N);break;case"unpublish":L(N);break;case"markAsTemplate":D(N);break;case"unmarkAsTemplate":H(N);break;case"duplicate":P(N);break;case"addLanguagePage":Z({edit:!1,primaryPage:((U=N==null?void 0:N.page)==null?void 0:U.id)||"",preselectedLang:(N==null?void 0:N.language)||K});break}};return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex h-full flex-col justify-between",children:[t.jsx(Oi,{pages:be,search:b,setSearch:j,languages:[h,...s],selectedLanguage:K,setSelectedLanguage:Q,selectedPageType:G,setSelectedPageType:X,onAddPage:x=>E("add",x)}),t.jsx("div",{className:"flex-1 overflow-y-auto px-4 pb-6 pt-2",children:l||q?t.jsx("div",{className:"space-y-2",children:f.map([...Array(15).keys()],x=>t.jsx("div",{className:"h-7 w-full animate-pulse rounded border border-gray-300 bg-gray-200"},x))}):f.isEmpty(be)?t.jsxs("div",{className:"flex h-[70vh] flex-col items-center justify-center gap-y-1 text-sm font-medium text-slate-500",children:[t.jsx(w.File,{className:"h-6 w-6 stroke-[1]"}),"Empty List!",t.jsx("span",{className:"font-light",children:"Add new page to start"})]}):t.jsx(va,{tier:0,pages:be,pageTypes:r,currentPage:m||"",onClickAction:E,languagePages:_,selectedLanguage:K})})]}),v&&t.jsx(hn,{closePanel:e,editPage:ue,addEditPage:v,setAddEditPage:S}),y&&t.jsx(ks,{page:y,onClose:()=>p(null)}),C&&t.jsx(is,{page:C,onClose:()=>L(null)}),k&&t.jsx(fn,{page:k,onClose:()=>D(null)}),M&&t.jsx(xn,{page:M,onClose:()=>H(null)}),$&&t.jsx(mn,{page:$,onClose:()=>P(null)})]})},Hi=()=>{const e=qe("logo",null);return e?t.jsx("div",{className:"max-h-9 w-full overflow-hidden pr-2",children:g.createElement(e,{})}):null},Qi=()=>{const[e]=_e(),s=e.get("page"),{data:n,isFetching:a}=Pe(),[r,i]=g.useState(!1),{savePage:l}=F.useSavePage(),o=!!s&&!f.isEmpty(n),u=!s||!a&&f.isEmpty(n)||r,d=F.useChaiFeatureFlag("enable-page-manager-v2");return t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"flex items-center gap-x-1",children:t.jsx("div",{className:"relative",children:t.jsxs(c.Tooltip,{children:[t.jsx(c.TooltipTrigger,{asChild:!0,children:t.jsx(c.Button,{variant:"outline",className:"flex w-full items-center space-x-2 py-1",onClick:()=>{l(),i(!0)},children:t.jsx(w.LogsIcon,{className:"h-4 w-4"})},"template-viewer")}),t.jsx(c.TooltipContent,{side:"right",children:t.jsx("p",{children:"Open pages manager"})})]})})}),t.jsx(c.Sheet,{open:u,onOpenChange:h=>!h&&o&&i(!1),children:t.jsxs(c.SheetContent,{side:"left","aria-describedby":"pages-manager-description",className:`${d?"!min-w-[50vh] !max-w-[800px] p-0":"w-full !max-w-screen-md"} z-50 border-border ${o?"":"sheet-hide-close-btn"}`,children:[t.jsxs(c.SheetHeader,{className:`mb-3 ${d?"px-4 pt-4":""}`,children:[t.jsxs(c.SheetTitle,{className:"flex items-center gap-2 text-sm font-semibold",children:[t.jsx("div",{className:"flex h-9 w-9 items-center justify-center rounded-lg bg-primary text-primary-foreground",children:t.jsx(w.Folder,{className:"h-4 w-4"})}),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 font-normal text-muted-foreground",children:"Manage your site structure"})]})]}),t.jsx(c.SheetDescription,{className:"sr-only",children:"Manage your site structure"})]}),t.jsx("div",{className:`${u?"h-[calc(100vh-80px)] overflow-y-auto":"h-[calc(100vh-70px)] overflow-y-auto"}`,children:d?u&&t.jsx(Ki,{close:()=>i(!1)}):t.jsx(Mi,{close:()=>i(!1)})})]})})]})},yn=({showAdd:e=!0,variant:s="ghost"})=>{const{fallbackLang:n,languages:a,selectedLang:r,setSelectedLang:i}=F.useLanguages(),l=f.isEmpty(r)?n:r,[,o]=_e(),{isLocked:u}=ut();g.useEffect(()=>{const p=new URLSearchParams(window.location.search),v=p.get("lang");v&&(a.includes(v)?i(v):(p.delete("lang"),o(p),i("")))},[a,o,i]);const[,d]=we.useAtom(Ts),{data:h}=Pe(),{data:m}=He(),{data:b}=Oe(),j=g.useMemo(()=>{const p=f.compact(f.map(f.get(m,"languages"),v=>{const S=f.find(b,{lang:v});return{key:v,value:f.get(Te,v,v),isLangPageAdded:!!S}})).filter(Boolean);return[{key:n,value:f.get(Te,n),isLangPageAdded:!0},...p]},[n,b,m]),y=p=>{i(p);const v=new URLSearchParams(window.location.search);p===n?v.delete("lang"):v.set("lang",p);const S=v.toString(),C=`${window.location.pathname}${S?`?${S}`:""}`;window.history.pushState({},"",C),o(v),window.dispatchEvent(new PopStateEvent("popstate"))};return f.isEmpty(a)?null:u?t.jsxs(c.Button,{variant:"ghost",size:"sm",className:"ml-px h-max cursor-not-allowed gap-2 py-1.5 opacity-50",children:[t.jsx(w.Languages,{className:"h-4 w-4"}),f.get(Te,l,l),t.jsx(w.ChevronDown,{className:"h-4 w-4"})]}):t.jsx(t.Fragment,{children:t.jsxs(c.DropdownMenu,{children:[t.jsx(c.DropdownMenuTrigger,{asChild:!0,className:"focus:outline-none",children:t.jsxs(c.Button,{disabled:!!u,variant:s,size:"sm",className:"ml-px h-max gap-2 py-1.5",children:[t.jsx(w.Languages,{className:"h-4 w-4"}),f.get(Te,l,l),t.jsx(w.ChevronDown,{className:"h-4 w-4"})]})}),t.jsxs(c.DropdownMenuContent,{className:"space-y-1 border-border",children:[f.map(j.filter(p=>p.isLangPageAdded),p=>t.jsxs(c.DropdownMenuItem,{className:F.mergeClasses("flex cursor-pointer items-center justify-between text-xs font-medium text-gray-800",p.key===l&&"!bg-gray-200 text-gray-700"),onClick:()=>y(p.key),children:[t.jsx("div",{className:"text-slate-600",children:p.value}),p.key===n&&t.jsxs("small",{className:"flex items-center gap-x-1 text-[9px] leading-none text-orange-500",children:[t.jsx(w.Star,{fill:"orange",className:"h-2 w-2"}),"Primary"]})]},p.value)),e&&!f.isEmpty(j.filter(p=>!p.isLangPageAdded))&&t.jsxs(t.Fragment,{children:[t.jsx(c.Separator,{}),t.jsxs(c.Button,{size:"sm",variant:"ghost",onClick:()=>{h&&d({edit:!1,primaryPage:h.id})},className:"text-xs font-normal duration-200 hover:bg-slate-300 hover:text-slate-800",children:[t.jsx(w.Plus,{className:"mr-1 h-3 w-3"})," Add Langauge"]})]})]})]})})};function Wi(){const[e,s]=we.useAtom(Ts);return t.jsxs("div",{className:"relative z-10 flex items-center justify-end gap-1",children:[t.jsx(Hi,{}),t.jsx(Qi,{}),e&&t.jsx(vi,{isOpen:!0,id:e==null?void 0:e.id,edit:!!(e!=null&&e.id),primaryPage:e==null?void 0:e.primaryPage,preselectedLang:e==null?void 0:e.preselectedLang,onClose:()=>s(null)})]})}const Re=({permission:e,permissions:s,children:n,fallback:a=null})=>{const{hasPermission:r}=F.usePermissions();return e&&!r(e)||s&&!s.some(i=>r(i))?a:n};function Yi(e){const s=oe(),n=ee();return R.useQuery({queryKey:[W,"revisions",e],queryFn:async()=>await n(s,{action:I.GET_PAGE_REVISIONS,data:{pageId:e}}),enabled:!!e,gcTime:0,staleTime:0})}const Ji=()=>{const e=oe(),s=ee(),n=R.useQueryClient();return R.useMutation({mutationFn:async a=>await s(e,{action:I.DELETE_PAGE_REVISION,data:{revisionId:a}}),onSuccess:()=>{n.invalidateQueries({queryKey:[W,"revisions"]})}})},Xi=()=>{const e=oe(),s=ee(),n=R.useQueryClient();return R.useMutation({mutationFn:async({revisionId:a,discardCurrent:r})=>await s(e,{action:I.RESTORE_PAGE_REVISION,data:{revisionId:a,discardCurrent:r}}),onSuccess:()=>{n.invalidateQueries({queryKey:[W,"revisions"]})}})},at=({tag:e})=>e==="draft"?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.jsxs("span",{className:"relative flex h-2 w-2",children:[t.jsx("span",{className:"absolute inline-flex h-full w-full animate-ping rounded-full bg-amber-400 opacity-75"}),t.jsx("span",{className:"relative inline-flex h-2 w-2 rounded-full bg-amber-500"})]}),t.jsx("span",{className:"text-[11px] leading-tight",children:"Draft"})]}):e==="live"?t.jsxs("span",{className:"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:"relative flex h-2 w-2",children:[t.jsx("span",{className:"absolute inline-flex h-full w-full animate-ping rounded-full bg-green-400 opacity-75"}),t.jsx("span",{className:"relative inline-flex h-2 w-2 rounded-full bg-green-500"})]}),t.jsx("span",{className:"text-[11px] leading-tight",children:"Live"})]}):e==="published"?t.jsxs("div",{className:"flex items-center gap-1 rounded-full bg-green-500/10 px-1.5 py-0.5 text-xs text-green-600",children:[t.jsx(w.Rocket,{className:"h-3 w-3"}),t.jsx("span",{className:"text-[11px] leading-tight",children:"Published"})]}):e==="unsaved"?t.jsxs("div",{className:"flex items-center gap-1 rounded-full bg-red-500/10 px-1.5 py-0.5 text-xs text-red-600",children:[t.jsx(w.Save,{className:"h-3 w-3"}),t.jsx("span",{className:"text-[11px] leading-tight",children:"Unsaved changes"})]}):t.jsx("span",{className:"rounded bg-purple-500/10 px-1.5 py-0.5 font-mono text-xs font-bold text-purple-600",children:e});function Zi({compare:e,setCompare:s,isComparisonEnabled:n}){const{data:a}=Pe(),{saveState:r}=F.useSavePage(),[i]=As();if(!a)return null;const l=!!e.find(d=>{var h;return(h=d==null?void 0:d.uid)==null?void 0:h.startsWith("draft:")}),o=e.length>=2&&!l,u=r==="UNSAVED";return t.jsxs("div",{className:"relative flex items-start gap-3 rounded-md border bg-primary/5 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:"flex items-center gap-1 text-sm font-medium leading-none",children:[t.jsx(at,{tag:"draft"}),t.jsx("span",{className:"text-xs font-bold",children:"Currently editing"})]})}),t.jsx("div",{className:"flex items-center pl-2 text-[11px] text-muted-foreground",children:!f.isEmpty(i.lastSaved)&&t.jsxs("span",{children:["Last updated"," ",_t.formatDistanceToNow(new Date(i.lastSaved),{addSuffix:!0})]})}),t.jsx("div",{className:"flex items-center gap-2 pt-0.5",children:u?t.jsx(at,{tag:"unsaved"}):null})]}),n&&t.jsx(ba,{checked:l,disabled:o,onChange:()=>{s(l?e.filter(d=>d.uid!==`draft:${a==null?void 0:a.id}`):[...e,{uid:`draft:${a==null?void 0:a.id}`,label:"draft"}])}})]})}function el(){var Q,Z;const[e,s]=Se.useState([]),[n,a]=Se.useState(!1),[r,i]=Se.useState(null),[l,o]=Se.useState(!1),[u,d]=Se.useState(!1),{data:h}=Pe(),{data:m,isFetching:b,error:j,refetch:y}=Yi(h==null?void 0:h.id),{mutate:p,isPending:v}=Ji(),{mutate:S,isPending:C}=Xi(),L=R.useQueryClient(),k=ia(),D=F.useChaiFeatureFlag("enable-page-revisions-compare"),{selectedLang:G,fallbackLang:X}=F.useLanguages(),$=G||X;g.useEffect(()=>s([]),[h==null?void 0:h.id]);const P=_=>{r&&S({revisionId:r.uid,discardCurrent:_},{onSuccess:()=>{o(!1),i(null),L.invalidateQueries({queryKey:[W,I.GET_DRAFT_PAGE]})}})},M=_=>{i(_),o(!0)},H=_=>{i(_),d(!0)},K=()=>{r&&p(r.uid,{onSuccess:()=>{d(!1),i(null)}})};return g.useEffect(()=>{n&&y()},[n,y]),t.jsxs(t.Fragment,{children:[t.jsx(c.TooltipProvider,{children:t.jsxs(c.Tooltip,{children:[t.jsxs(c.Sheet,{open:n,onOpenChange:a,children:[t.jsx(c.SheetTrigger,{asChild:!0,children:t.jsx(c.TooltipTrigger,{asChild:!0,children:t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsxs(c.Button,{variant:"ghost",size:"icon",className:"h-8 w-8",children:[t.jsx(w.History,{className:"h-4 w-4"}),t.jsx("span",{className:"sr-only",children:"View revision history"})]}),t.jsx("div",{className:"h-4 w-px bg-gray-200 dark:bg-gray-700"})]})})}),t.jsxs(c.SheetContent,{className:"flex h-[100vh] flex-col",children:[t.jsxs(c.SheetHeader,{children:[t.jsx(c.SheetTitle,{children:"Revision History"}),(h==null?void 0:h.createdAt)&&t.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:["Page created on ",_t.format(new Date(h.createdAt),"MMM d, yyyy 'at' h:mm a")]})]}),b?t.jsx(tl,{}):j?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 flex h-full min-h-0 flex-1 flex-col space-y-2",children:[D&&t.jsx(nl,{lang:$,compare:e,setCompare:s}),t.jsx(Zi,{compare:e,setCompare:s,isComparisonEnabled:D}),(Q=m==null?void 0:m.filter(_=>_.uid==="current"))==null?void 0:Q.map((_,q)=>t.jsx(Pn,{lang:$,pageId:h==null?void 0:h.id,revision:_,isLatest:!0,onRestore:()=>M(_),onDelete:()=>H(_),revisionNumber:q,compare:e,setCompare:s,pageLiveFullSlug:k,isComparisonEnabled:D},_.uid)),t.jsx(c.ScrollArea,{className:"min-h-0 flex-1",children:t.jsx("div",{className:"space-y-2",children:(Z=m==null?void 0:m.filter(_=>_.uid!=="current"))==null?void 0:Z.map((_,q)=>t.jsx(Pn,{lang:$,pageId:h==null?void 0:h.id,revision:_,isLatest:_.uid==="current",onRestore:()=>M(_),onDelete:()=>H(_),revisionNumber:q+1,compare:e,setCompare:s,pageLiveFullSlug:k,isComparisonEnabled:D},_.uid))})})]})]})]}),t.jsx(c.TooltipContent,{side:"bottom",children:t.jsx("p",{children:"Revision history"})})]})}),t.jsx(rl,{open:l,onOpenChange:o,revision:r,onRestore:P,isRestoring:C}),t.jsx(il,{open:u,onOpenChange:d,revision:r,onDelete:K,isDeleting:v})]})}function tl(){return t.jsx("div",{className:"mt-2 space-y-2",children:Array.from({length:5}).map((e,s)=>t.jsxs("div",{className:"flex items-start gap-3 rounded-md border p-2",children:[t.jsxs("div",{className:"flex-1 space-y-1",children:[t.jsx(c.Skeleton,{className:"h-4 w-3/4"}),t.jsx(c.Skeleton,{className:"h-3 w-1/2"}),t.jsx(c.Skeleton,{className:"mt-1 h-5 w-20"})]}),t.jsx(c.Skeleton,{className:"h-8 w-8 rounded-full"})]},s))})}function Pn({revision:e,isLatest:s,onRestore:n,onDelete:a,revisionNumber:r,compare:i,setCompare:l,pageId:o,pageLiveFullSlug:u,isComparisonEnabled:d,lang:h}){const{data:m}=ct(e.currentEditor),b=(m==null?void 0:m.name)||"Unknown",j=!!i.find(p=>{var v;return s?(v=p==null?void 0:p.uid)==null?void 0:v.startsWith("live"):(p==null?void 0:p.uid)===e.uid}),y=i.length>=2&&!j;return t.jsxs("div",{className:"relative flex items-start gap-3 rounded-md border p-2 hover:bg-accent/50",children:[t.jsxs("div",{className:"flex-1 space-y-3",children:[t.jsx("div",{className:"flex items-center justify-between",children:t.jsxs("p",{className:"flex items-center gap-1 text-xs leading-none",children:[d&&t.jsx(at,{tag:s?"live":`#${r}`}),e.type==="published"?"Published":"Draft"," by ",t.jsx("span",{className:"text-xs font-bold",children:b}),!d&&s&&t.jsx(at,{tag:"live"})]})}),t.jsxs("div",{className:"flex items-center gap-x-3",children:[t.jsx("div",{className:"flex items-center gap-2",children:e.type==="published"?t.jsx(at,{tag:"published"}):t.jsx(at,{tag:"draft"})}),t.jsx("div",{className:"flex items-center text-[10px] text-muted-foreground",children:t.jsx("span",{className:"leading-tight",children:_t.format(e.createdAt,"MMM d, h:mm a")})})]})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[e.type!=="draft"&&d&&t.jsx("a",{target:"_blank",href:s?u:`/revision/revision:${e.uid}:${r}?lang=${h}`,children:t.jsxs(c.Button,{variant:"ghost",size:"icon",className:"h-4 w-4 hover:text-blue-500",children:[t.jsx(w.Eye,{className:"h-3 w-3"}),t.jsx("span",{className:"sr-only",children:"View this version"})]})}),t.jsx(Re,{permissions:[ve.RESTORE_REVISION,ve.DELETE_REVISION],children:t.jsx(al,{revision:e,onRestore:n,onDelete:a})})]}),d&&t.jsx(ba,{checked:j,disabled:y,onChange:()=>{l(j?i.filter(p=>s?p.uid!==`live:${o}`:p.uid!==e.uid):[...i,{uid:s?`live:${o}`:e.uid,label:s?"live":`#${r}`}])}})]})}function sl(e,s){let n="/revision/compare?";return e==null||e.forEach((a,r)=>{const i=a.uid,l=a.label;n+=`&${r===0?"version1":"version2"}=${i.startsWith("live:")||i.startsWith("draft:")?i:`revision:${i}:${l.replace("#","")}`}`}),n=n.replace(/^&/,"?"),`${n}&lang=${s}`}function nl({compare:e,setCompare:s,lang:n}){if(e.length===0)return null;const[a,r]=e,i=({tab:l})=>t.jsxs("span",{className:"flex items-center justify-between rounded border border-blue-100 p-1 font-medium",children:[t.jsx(at,{tag:l.label}),t.jsx("button",{className:"z-0 flex h-4 w-4 items-center justify-center rounded-full text-gray-400 hover:text-red-500",style:{lineHeight:1},onClick:()=>s(e.filter(o=>o.uid!==l.uid)),"aria-label":"Remove selection 1",children:t.jsx(w.X,{className:"h-3 w-3"})})]});return t.jsxs("div",{className:"mb-2 flex w-full max-w-md flex-col gap-1 rounded border bg-accent/60 p-2 shadow-sm",children:[t.jsxs("div",{className:"flex items-center gap-x-2 text-xs",children:[t.jsx("span",{className:"font-medium leading-tight text-gray-600",children:"Compare"}),a&&t.jsx(i,{tab:a}),t.jsx("span",{className:"font-medium leading-tight text-gray-600",children:"with"}),r?t.jsx(i,{tab:r}):t.jsx("span",{className:"rounded border px-1 text-xs text-muted-foreground",children:"Choose another"})]}),t.jsxs("div",{className:"flex items-center justify-end gap-3 pb-0.5 pt-2",children:[t.jsxs(c.Button,{size:"sm",className:"h-5 gap-1 rounded px-1 pr-2 text-xs leading-tight text-gray-500",variant:"outline",onClick:()=>s([]),children:[t.jsx(w.X,{className:"h-2.5 w-2.5"}),"Clear"]}),e.length===2?t.jsx("a",{target:"_blank",href:sl(e,n),children:t.jsxs(c.Button,{size:"sm",className:"h-5 gap-1 rounded px-2 text-xs leading-tight",children:["Compare ",t.jsx(w.ExternalLink,{className:"ml-1 h-2.5 w-2.5"})]})}):t.jsxs(c.Button,{size:"sm",className:"h-5 gap-1 rounded px-2 text-xs leading-tight",disabled:!0,children:["Compare ",t.jsx(w.ExternalLink,{className:"ml-1 h-2.5 w-2.5"})]})]})]})}function ba({checked:e,disabled:s,onChange:n,label:a="Compare"}){return t.jsx("div",{className:"absolute bottom-2 right-2",children:t.jsxs("label",{className:`flex cursor-pointer items-center gap-x-1 text-[11px] ${s?"opacity-50":""}`,children:[t.jsx("input",{type:"checkbox",className:"h-3 w-3 cursor-pointer rounded focus:ring-0 focus:ring-offset-0",checked:e,disabled:s,onChange:n}),t.jsx("span",{className:"select-none leading-tight",children:a})]})})}function al({revision:e,onRestore:s,onDelete:n}){return t.jsxs(c.DropdownMenu,{children:[t.jsx(c.DropdownMenuTrigger,{asChild:!0,children:t.jsxs(c.Button,{variant:"ghost",size:"icon",className:"h-5 w-5",children:[t.jsx(w.MoreHorizontal,{className:"h-4 w-4"}),t.jsx("span",{className:"sr-only",children:"More options"})]})}),t.jsxs(c.DropdownMenuContent,{align:"end",className:"text-xs",children:[t.jsx(Re,{permission:ve.RESTORE_REVISION,children:t.jsxs(c.DropdownMenuItem,{onClick:s,className:"cursor-pointer text-sm",children:[t.jsx(w.Undo2,{className:"mr-2 h-4 w-4"}),t.jsx("span",{children:"Restore this version"})]})}),t.jsx(Re,{permission:ve.DELETE_REVISION,children:e.uid!=="current"&&t.jsxs(t.Fragment,{children:[t.jsx(c.DropdownMenuSeparator,{}),t.jsxs(c.DropdownMenuItem,{onClick:n,className:"cursor-pointer text-destructive",children:[t.jsx(w.Trash,{className:"mr-2 h-4 w-4"}),t.jsx("span",{children:"Delete this version"})]})]})})]})]})}function rl({open:e,onOpenChange:s,revision:n,onRestore:a,isRestoring:r}){const{data:i}=ct((n==null?void 0:n.currentEditor)||""),l=(i==null?void 0:i.name)||"Unknown";return n?t.jsx(c.Dialog,{open:e,onOpenChange:o=>{r||s(o)},children:t.jsxs(c.DialogContent,{className:"sm:max-w-md",children:[t.jsxs(c.DialogHeader,{children:[t.jsx(c.DialogTitle,{children:"Restore Revision"}),t.jsxs(c.DialogDescription,{children:["You are about to restore to revision ",n.uid.substring(0,8)," from"," ",_t.format(n.createdAt,"MMM d, yyyy 'at' h:mm a")," by ",l]})]}),t.jsx("div",{className:"py-2",children:t.jsx("p",{className:"text-sm text-muted-foreground",children:"How would you like to handle your current edits?"})}),t.jsxs(c.DialogFooter,{className:"flex flex-col gap-2 sm:flex-row",children:[t.jsx(c.Button,{variant:"outline",className:"sm:flex-1",onClick:()=>a(!1),disabled:r,children:r?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mr-2 h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent"}),"Saving as draft..."]}):t.jsxs(t.Fragment,{children:[t.jsx(w.CloudOff,{className:"mr-2 h-4 w-4"}),"Save as draft"]})}),t.jsx(c.Button,{variant:"default",className:"sm:flex-1",onClick:()=>a(!0),disabled:r,children:r?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mr-2 h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent"}),"Discarding current..."]}):t.jsxs(t.Fragment,{children:[t.jsx(w.Undo2,{className:"mr-2 h-4 w-4"}),"Discard current"]})})]})]})}):null}function il({open:e,onOpenChange:s,revision:n,onDelete:a,isDeleting:r}){const{data:i}=ct((n==null?void 0:n.currentEditor)||""),l=(i==null?void 0:i.name)||"Unknown";return n?t.jsx(c.Dialog,{open:e,onOpenChange:o=>{r||s(o)},children:t.jsxs(c.DialogContent,{className:"sm:max-w-md",children:[t.jsxs(c.DialogHeader,{children:[t.jsx(c.DialogTitle,{children:"Delete Revision"}),t.jsxs(c.DialogDescription,{children:["You are about to delete revision ",n.uid.substring(0,8)," from"," ",_t.format(n.createdAt,"MMM d, yyyy 'at' h:mm a")," by ",l]})]}),t.jsx("div",{className:"py-2",children:t.jsx("p",{className:"text-sm text-muted-foreground",children:"This action cannot be undone. Are you sure you want to proceed?"})}),t.jsxs(c.DialogFooter,{className:"flex flex-col gap-2 sm:flex-row",children:[t.jsx(c.Button,{variant:"outline",className:"sm:flex-1",onClick:()=>s(!1),disabled:r,children:"Cancel"}),t.jsx(c.Button,{variant:"destructive",className:"sm:flex-1",onClick:a,disabled:r,children:r?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mr-2 h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent"}),"Deleting..."]}):t.jsxs(t.Fragment,{children:[t.jsx(w.Trash,{className:"mr-2 h-4 w-4"}),"Delete Revision"]})})]})]})}):null}const ll=()=>{const e=oe(),s=ee();return R.useQuery({queryKey:[W,I.GET_CHANGES],queryFn:async()=>s(e,{action:I.GET_CHANGES})})};function ol({showModal:e=!1,onClose:s=()=>console.log("Cancelled")}){const[n,a]=g.useState([]),r=Qe(),[i,l]=g.useState(r),{data:o,isFetching:u}=ll(),{data:d}=Ce(),h=g.useCallback(P=>{var M;return(M=f.find(d,{key:P}))==null?void 0:M.hasSlug},[d]),m=g.useMemo(()=>f.filter(d,P=>!h(P.key)).map(P=>P.key),[h,d]),j=f.uniq(f.map(o,"lang")).filter(Boolean),y=g.useMemo(()=>f.filter(o,P=>P.pageType==="theme"?!1:i===r?P.lang===i||P.lang==="":P.lang===i),[o,i,r]),p=g.useMemo(()=>f.filter(y,P=>!m.includes(P.pageType)),[y,m]),v=g.useMemo(()=>f.filter(y,P=>m.includes(P.pageType)),[y,m]),{mutate:S,isPending:C}=on();g.useEffect(()=>{const P=f.map(f.filter(y,{online:!0}),"id");a(P)},[y]);const L=n.length===(y==null?void 0:y.length),k=P=>{a(M=>f.includes(M,P)?f.filter(M,H=>H!==P):f.concat(M,P))},D=()=>{a(L?[]:f.map(y,"id"))},G=()=>{S({ids:f.uniq(n)},{onSuccess:()=>{s(),Ot("CENTER_CENTER"),l(r)}})},X=P=>{if(P==="theme")return"Theme";const M=f.find(d,{key:P});return M?M==null?void 0:M.name:P},$=g.useMemo(()=>{const P=[{label:"Updated",top:"pt-2"},...f.orderBy(f.filter(p,{online:!0}),"pageType"),...f.orderBy(f.filter(v,{online:!0}),"pageType")].filter(H=>H.pageType!=="theme"),M=[{label:"Offline",top:"pt-6"},...f.orderBy(f.filter(p,{online:!1}),"pageType"),...f.orderBy(f.filter(v,{online:!1}),"pageType")];return[...P,...M]},[p,v]);return t.jsx(c.Dialog,{open:e,onOpenChange:C?()=>{}:s,children:t.jsxs(c.DialogContent,{className:"flex max-h-[80%] max-w-4xl flex-col",children:[t.jsxs(c.DialogHeader,{children:[t.jsx(c.DialogTitle,{children:"Publish changes"}),t.jsx(c.DialogDescription,{className:"text-xs",children:"Select the pages you want to publish. Click publish when you're done."})]}),j.length>0&&t.jsx("div",{className:"my-[2px] mt-0",children:t.jsx(ja,{languages:[r,...j],selectedLanguage:i,setSelectedLanguage:l})}),t.jsx("div",{className:"no-scrollbar relative -mx-4 -mt-4 h-full max-h-full overflow-y-auto",children:u?t.jsxs("div",{className:"space-y-2 px-1",children:[t.jsx("div",{className:"mt-2 h-6 w-full animate-pulse rounded bg-gray-200"}),t.jsx("div",{className:"h-6 w-full animate-pulse rounded bg-gray-200"}),t.jsx("div",{className:"h-6 w-full animate-pulse rounded bg-gray-200"}),t.jsx("div",{className:"h-6 w-full animate-pulse rounded bg-gray-200"})]}):t.jsxs("table",{className:"w-full text-left text-xs text-gray-500 dark:text-gray-400 rtl:text-right",children:[t.jsx("thead",{className:"sticky top-0 z-10 border-b bg-gray-50 text-gray-700 dark:bg-gray-700 dark:text-gray-400",children:t.jsxs("tr",{children:[t.jsxs("th",{scope:"col",className:"w-[1 50px] flex items-center gap-x-2 px-6 py-3",children:[t.jsx("input",{checked:L,onClick:P=>{P.stopPropagation(),D()},type:"checkbox",className:"mt-1 cursor-pointer rounded focus:outline-none focus:ring-0"}),"Name"]}),t.jsx("th",{scope:"col",className:"w-[150px] px-2 py-3",children:"Type"}),t.jsx("th",{scope:"col",className:"w-[150px] px-4 py-3 text-right",children:"Status"})]})}),t.jsx("tbody",{children:f.map($,P=>P.label?t.jsx("tr",{children:t.jsxs("td",{colSpan:3,className:`relative px-6 py-2 text-xs font-medium text-gray-800 ${P.top}`,children:[t.jsx("div",{className:"absolute inset-0 left-6 flex items-center",children:t.jsx("div",{className:"order-gray-300 w-full"})}),t.jsx("div",{className:"relative flex justify-start",children:t.jsx("span",{className:"bg-gray-50 pr-2",children:P.label})})]})},"separator"):t.jsxs("tr",{className:"group border-b last:border-b-0 hover:bg-gray-50",children:[t.jsxs("td",{scope:"row",className:"flex items-center gap-x-1 whitespace-nowrap px-6 py-2 text-gray-900 dark:text-white",children:[t.jsx("input",{checked:f.includes(n,P==null?void 0:P.id),onClick:M=>{M.stopPropagation(),k(P==null?void 0:P.id)},type:"checkbox",className:"cursor-pointer rounded focus:outline-none focus:ring-0"})," ",h(P.pageType)?t.jsx(w.File,{className:"h-4 w-4"}):t.jsx(w.GlobeIcon,{className:"h-4 w-4"}),t.jsx(lt,{content:P.name,side:"top",showTooltip:P.name.length>25,children:t.jsx("span",{className:"max-w-[200px] truncate font-medium text-black",children:P.name})}),P.slug&&t.jsx(lt,{content:P.slug,side:"top",showTooltip:P.slug.length>25,children:t.jsx("span",{className:"max-w-[200px] truncate font-mono text-xs text-muted-foreground",children:P.slug})})]}),t.jsx("td",{className:"px-2",children:X(P==null?void 0:P.pageType)}),t.jsx("td",{className:"px-4 text-right",children:f.first(P.changes)||""})]},P==null?void 0:P.id))})]})}),t.jsxs(c.DialogFooter,{className:"mt-10 flex items-center justify-center",children:[n.length>0&&t.jsxs("span",{className:"text-center text-sm text-muted-foreground",children:[n.length," Page",n.length!==1?"s":""," Selected"]}),t.jsx(c.Button,{disabled:C,variant:"outline",onClick:s,children:"Cancel"}),t.jsx(c.Button,{disabled:C||u||f.isEmpty(n),onClick:G,children:C?"Publishing...":"Publish Selected"})]})]})})}const cl=()=>{const e=ee(),s=oe();return R.useQuery({queryKey:[I.GET_WEBSITE_DATA],staleTime:1e3*60*5,queryFn:async()=>e(s,{action:I.GET_WEBSITE_DATA,data:{draft:!0}})})};function ul({onClose:e}){const{data:s,isFetching:n}=cl(),{mutateAsync:a,isPending:r}=Pr(),i=qe("settingComponent",null),l=f.debounce(async o=>(await a({data:o}),!0),300);return i?t.jsx(c.Dialog,{open:!0,onOpenChange:e,children:t.jsxs(c.DialogContent,{className:"w-full",children:[t.jsx(c.DialogHeader,{children:t.jsx(c.DialogTitle,{children:"Website Settings"})}),n?t.jsxs("div",{className:"w-full space-y-3 py-4",children:[t.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"}),t.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"}),t.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"}),t.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"}),t.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"}),t.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"})]}):t.jsx("div",{children:g.createElement(i,{data:s||{},onSave:r?()=>{}:l,cancel:r?()=>{}:e})})]})}):null}const dl=()=>{const{selectedLang:e,fallbackLang:s}=F.useLanguages(),n=qe("getPreviewUrl",async m=>m),[a,r]=g.useState(""),{data:i}=Pe(),{data:l}=Oe(),{data:o}=Ce(),u=g.useMemo(()=>{var m;return(m=l==null?void 0:l.find(b=>(b==null?void 0:b.lang)===e))==null?void 0:m.slug},[e,l]),d=g.useCallback(m=>{var b;return(b=f.find(o,{key:m}))==null?void 0:b.hasSlug},[o]),h=e===s?"":e;return g.useEffect(()=>{(async()=>{if(typeof n=="function"){const m=!d(i==null?void 0:i.pageType),b=await n(m?`${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(c.Button,{variant:"ghost",size:"sm",className:"gap-2",children:[t.jsx(w.Eye,{className:"h-4 w-4"})," ",le.PREVIEW]})})})},hl=()=>{const[e,s]=F.useRightPanel();return t.jsxs(t.Fragment,{children:[t.jsx(lt,{content:le.THEME,children:t.jsx(c.Button,{variant:e==="theme"?"outline":"ghost",size:"icon",className:"gap-2",onClick:()=>s(e==="theme"?"block":"theme"),children:t.jsx(w.Palette,{className:"h-4 w-4"})})}),t.jsx("div",{className:"h-4 w-px bg-gray-200 dark:bg-gray-700"})]})},ml=()=>{const[e,s]=g.useState(!1),{isLocked:n}=ut(),{savePageAsync:a,saveState:r}=F.useSavePage();g.useEffect(()=>{const h=m=>{r==="UNSAVED"&&(m.preventDefault(),m.returnValue=!1)};return r==="UNSAVED"&&window.addEventListener("beforeunload",h),()=>{window.removeEventListener("beforeunload",h)}},[r]);const i=g.useCallback(async()=>{s(!0),await a()},[a]);g.useEffect(()=>{r==="SAVED"&&s(!1)},[r]);const l=g.useMemo(()=>{if(r==="SAVED"||r==="UNSAVED")return r;if(r==="SAVING")return e?r:"SAVED"},[e,r]),{buttonIcon:o,buttonClass:u,tooltipContent:d}=g.useMemo(()=>{switch(l){case"UNSAVED":return{tooltipContent:le.SAVEDRAFT,buttonIcon:t.jsx(w.Save,{className:"h-4 w-4"}),buttonClass:"flex items-center gap-x-1 leading-tight"};case"SAVING":return{tooltipContent:le.SAVING,buttonIcon:t.jsx(w.Loader,{className:"h-4 w-4 animate-spin"}),buttonClass:"flex items-center gap-x-1 leading-tight"};case"SAVED":return{tooltipContent:le.SAVED,buttonIcon:t.jsx(w.CheckCircle,{className:"h-4 w-4"}),buttonClass:"text-green-500 flex items-center gap-x-1 leading-tight"}}},[l]);return n?null:t.jsxs(c.Button,{size:"sm",variant:"ghost",onClick:i,className:u,children:[o," ",d]})},fl=()=>{const{selectedLang:e}=F.useLanguages(),{data:s}=tt(),{data:n}=Oe(),[a,r]=g.useState(!1),[i,l]=g.useState(!1),[o,u]=g.useState(null),{data:d}=Pe(),{mutate:h,isPending:m}=on(),{buttonText:b,buttonClassName:j,isPublished:y}=g.useMemo(()=>{const S=d&&(d==null?void 0:d.online);return{buttonClassName:S?"hover:bg-green-600 bg-green-500":"",isPublished:S,buttonText:S?le.PUBLISHED:le.PUBLISH}},[d]),p=async()=>{const S=[s==null?void 0:s.id,s==null?void 0:s.primaryPage];h({ids:f.compact(S)},{onSuccess:()=>Ot("TOP_RIGHT")})},v=g.useMemo(()=>f.map(n??[],"id"),[n]);return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex",children:[t.jsxs(c.Button,{size:"sm",onClick:p,disabled:m||!(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 ${j}`,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:y?t.jsx(w.Send,{className:"h-4 w-4"}):t.jsx(w.Rocket,{className:"h-4 w-4"})}),t.jsx("span",{className:`absolute inset-0 left-3 flex items-center transition-transform duration-300 ease-in-out ${i?"":"translate-y-10"}`,children:y?t.jsx(w.Rocket,{className:"h-4 w-4"}):t.jsx(w.Send,{className:"h-4 w-4"})}),t.jsx("span",{children:b}),e?`(${f.upperCase(e)})`:""]}),t.jsxs(c.DropdownMenu,{children:[t.jsx(c.DropdownMenuTrigger,{asChild:!0,children:t.jsx(c.Button,{size:"sm",disabled:m||!(d!=null&&d.id),className:`rounded-l-none border-l border-white/50 px-2 text-white ${j}`,children:t.jsx(w.ChevronDown,{className:"h-4 w-4"})})}),t.jsxs(c.DropdownMenuContent,{align:"end",className:"w-52",children:[t.jsxs(c.DropdownMenuItem,{disabled:m,className:"cursor-pointer text-xs",onClick:()=>h({ids:v},{onSuccess:()=>Ot("TOP_RIGHT")}),children:[le.PUBLISH," with translation pages"]}),!y&&t.jsxs(c.DropdownMenuItem,{disabled:m,className:"cursor-pointer text-xs",onClick:()=>h({ids:[d==null?void 0:d.id]},{onSuccess:()=>Ot("TOP_RIGHT")}),children:[le.PUBLISH," page"]}),t.jsxs(c.DropdownMenuItem,{onClick:()=>r(!0),className:"cursor-pointer text-xs",children:[le.OPEN," publish menu"]}),y&&t.jsxs(c.DropdownMenuItem,{onClick:()=>u(s),className:"cursor-pointer text-xs",children:[le.UNPUBLISH," page ",e?`(${f.upperCase(e)})`:""]})]})]})]}),t.jsx(ol,{showModal:a,onClose:()=>r(!1)}),o&&t.jsx(is,{page:o,onClose:()=>u(null)})]})},gl=()=>{const e=qe("settingComponent",null),[s,n]=g.useState(!1);return e?t.jsxs(t.Fragment,{children:[t.jsx(lt,{content:le.WEBSITEDATA,children:t.jsx(c.Button,{variant:"ghost",size:"icon",className:"gap-2",onClick:()=>n(!0),children:t.jsx(w.Settings,{className:"h-4 w-4"})})}),s&&t.jsx(ul,{onClose:()=>n(!1)}),t.jsx("div",{className:"h-4 w-px bg-gray-200 dark:bg-gray-700"})]}):null};function xl(){const{isLocked:e}=ut(),[s]=_e(),n=s.get("lang"),a=sa(n);return e||!a?t.jsx("div",{}):t.jsxs("div",{className:"flex items-center justify-end gap-1",children:[t.jsx(el,{}),t.jsx(Re,{permission:ve.EDIT_THEME,children:t.jsx(hl,{})}),t.jsx(Re,{permission:ve.EDIT_SETTINGS,children:t.jsx(gl,{})}),t.jsx(dl,{}),t.jsx(Re,{permission:ve.SAVE_PAGE,children:t.jsx(ml,{})}),t.jsx(Re,{permission:ve.PUBLISH_PAGE,children:t.jsx(fl,{})})]})}const pl=({isDefaultLang:e,searchQuery:s,setSearchQuery:n})=>t.jsx(c.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,onKeyDown:a=>a.stopPropagation()}),yl=({dynamicPage:e,setDynamicPage:s,searchQuery:n,setSearchQuery:a,dynamicPages:r})=>{const{selectedLang:i,fallbackLang:l}=F.useLanguages(),o=(i==null?void 0:i.length)===0;return t.jsxs(c.DropdownMenu,{children:[t.jsx(c.DropdownMenuTrigger,{asChild:!0,children:t.jsxs(c.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?f.get(e,"name"):"Select Page",t.jsx(w.ChevronDown,{className:"ml-2 h-4 w-4"})]})}),t.jsxs(c.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(pl,{isDefaultLang:o,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(c.DropdownMenuItem,{onClick:()=>s(u),disabled:o?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.jsx("div",{className:"w-full text-xs whitespace-nowrap px-2 py-[2px]",children:t.jsxs("div",{className:"flex items-center gap-x-2",children:[t.jsx("span",{className:"font-medium",children:u.name}),t.jsx("span",{className:"font-mono font-medium text-gray-500 text-xs rounded-full px-2 py-[1px] border border-gray-300 truncate",children:u.slug})]})})},u.id))]})]})},jl=()=>{const{dynamicPage:e,dynamicPages:s,allLangPages:n,selectedLang:a,searchQuery:r,updateDynamicPage:i,updateSearchQuery:l,onChangeLanguage:o}=aa(),u=g.useRef(void 0);return g.useEffect(()=>{u.current!==a&&e&&(o(),u.current=a)},[a,s]),t.jsx("div",{className:"relative",children:t.jsx(yl,{dynamicPage:e,setDynamicPage:i,searchQuery:r,setSearchQuery:l,dynamicPages:n})})},vl=()=>{const[e,s]=g.useState(null),[n,a]=g.useState(null),[r,i]=g.useState(null),[l,o]=g.useState(null),[u,d]=g.useState(null),[h,m]=g.useState(null),{data:b,isFetching:j}=tt(),{selectedLang:y,fallbackLang:p}=F.useLanguages(),{data:v}=Oe(),S=v==null?void 0:v.find(k=>k.lang===y),{isLocked:C}=ut(),L=!(b!=null&&b.slug);return b?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex items-center justify-center space-x-2 rounded py-1 pl-2 duration-100",children:[t.jsx("span",{className:"flex max-w-[200px] items-center truncate text-xs font-medium leading-tight",children:j?t.jsx(w.Loader,{className:"h-4 w-4 animate-spin text-slate-400"}):t.jsxs(t.Fragment,{children:[L?t.jsx(w.Globe,{className:"mr-1 h-4 w-4"}):t.jsx(w.File,{className:"mr-1 h-4 w-4"}),f.get(S||b,"name")??""]})}),C?t.jsx(c.Button,{variant:"ghost",size:"icon",className:"h-7 w-7 cursor-not-allowed rounded opacity-50 hover:bg-transparent",children:t.jsx(w.MoreHorizontal,{className:"h-4 w-4"})}):t.jsx(gn,{page:b,setDuplicatePage:k=>d(k),setAddEditPage:k=>m(k),setUnpublishPage:k=>a(k),setDeletePage:k=>s(k),setMarkAsTemplate:k=>i(k),setUnmarkAsTemplate:k=>o(k),isLanguagePage:y.length>0&&y!==p,children:t.jsx(c.Button,{variant:"ghost",size:"icon",className:"h-7 w-7 rounded hover:bg-gray-200",children:t.jsx(w.MoreHorizontal,{className:"h-4 w-4"})})})]}),h&&t.jsx(hn,{closePanel:()=>m(null),editPage:()=>{},addEditPage:h,setAddEditPage:m}),e&&t.jsx(ks,{page:e,onClose:()=>s(null)}),n&&t.jsx(is,{page:n,onClose:()=>a(null)}),r&&t.jsx(fn,{page:r,onClose:()=>i(null)}),l&&t.jsx(xn,{page:l,onClose:()=>o(null)}),u&&t.jsx(mn,{page:u,onClose:()=>d(null)})]}):null},bl=({hasDynamicPage:e,className:s=""})=>t.jsx("div",{className:`fixed bottom-0 left-0 right-0 top-[50px] z-[20] z-[9999] flex w-screen items-center justify-center bg-black/10 backdrop-blur ${s}`,children:t.jsxs("div",{className:"flex min-w-[300px] max-w-[400px] flex-col items-center justify-center rounded-md bg-white p-4 shadow-xl",children:[t.jsx("h1",{className:"text-lg font-medium",children:e?"Select a page":"No pages found"}),t.jsx("p",{className:"pt-4 text-center text-sm text-gray-600",children:e?"Please select a page from the list in the top header. This will enable you to edit the page.":"Please add a new page"})]})}),Sl=()=>{const{data:e}=tt(),s=nn(),{data:n,isFetching:a}=Pe(),r=f.get(n,"dynamic",!1),i=F.useChaiFeatureFlag("dynamic-page-selector"),{dynamicPage:l,allLangPages:o}=aa(),u=o.length>0,d=e==null?void 0:e.slug,h=!d,m=ia(),j=(h?`Partial: ${e==null?void 0:e.name} `:`${d}${s}`).replace(window.location.host,"");return t.jsxs("div",{className:"relative z-10 flex items-center gap-x-1",children:[t.jsx("div",{className:F.mergeClasses("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&&"pointer-events-none cursor-not-allowed opacity-50"),children:t.jsx(vl,{})}),t.jsxs("div",{className:F.mergeClasses("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"+(h?" pr-2":""),a&&"pointer-events-none cursor-not-allowed opacity-50"),children:[t.jsx(yn,{}),t.jsxs("div",{className:"flex w-full items-center overflow-hidden",children:[t.jsx("div",{className:`w-full max-w-[200px] overflow-hidden overflow-ellipsis whitespace-nowrap pl-1 text-xs ${h?"italic text-gray-400":"font-mono text-gray-500"}`,children:j==="/"?t.jsxs("span",{className:"text-gray-900",children:["/",t.jsx("span",{className:"text-[11px] font-light italic text-gray-400",children:"(Homepage)"})]}):j}),!h&&t.jsx("a",{href:m,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(w.ExternalLink,{className:"h-4 w-4",strokeWidth:1})})})]})]}),r&&!a&&i&&t.jsxs("div",{className:"relative",children:[!l&&t.jsx(bl,{hasDynamicPage:u}),t.jsx(jl,{})]})]})},wl=()=>t.jsxs("div",{className:"flex h-full w-full items-center justify-between px-2",children:[t.jsx(Wi,{}),t.jsx(Sl,{}),t.jsx(xl,{})]}),El=()=>{const e=oe(),{aiContext:s}=sn(),n=ee();return g.useCallback(async(a,r,i,l)=>n(e,{action:I.ASK_AI,data:{type:a,prompt:r,blocks:i,context:s,lang:l}}),[e,s,n])},Nl=(e,s)=>s.map(n=>{if(f.has(e,n._type)){const a=Qn.getDefaultBlockProps(n._type);return{...a,...f.pick(n,[...f.keys(a),"_type","_id","_name","_parent","_bindings"]),...f.pickBy(n,(r,i)=>f.endsWith(i,"_attrs")),...n}}return n}),Cl=e=>{const s=Qn.useRegisteredChaiBlocks();return g.useMemo(()=>{if(!e||f.isEmpty(e))return{blocks:[]};const n=f.filter(e,a=>!f.includes(a==null?void 0:a._type,"@chai/"));return{blocks:Nl(s,n)}},[e,s])},_n={async getUILibraryBlock(e,s,n){const a=await s(n,{action:"GET_LIBRARY_ITEM",data:{id:e.id}}),r=f.get(a,"html",""),i=f.get(a,"blocks",[]);return f.isArray(i)?i:F.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),[]}}},Al=()=>{const e=oe(),s=ee();return R.useQuery({queryKey:[W,"uiLibraries"],initialData:[],queryFn:async()=>{const a=(await s(e,{action:"GET_LIBRARIES"})).map(r=>({...r}));return a.forEach(r=>{F.registerChaiLibrary(r.id,{name:r.name,description:r.description,getBlocksList:i=>_n.getUILibraryBlocks(i,s,e),getBlock:({block:i})=>_n.getUILibraryBlock(i,s,e)})}),a}})},Sa=()=>{const e=Cs(),s=ee(),{user:n}=Ue(),a=n==null?void 0:n.id;return R.useQuery({queryKey:[W,"permissions",a],queryFn:()=>s(e,{action:I.GET_ROLE_AND_PERMISSIONS,data:{userId:a}}),enabled:!!a})},Tl=()=>{const e=oe(),s=ee(),{setCurrentEditor:n}=ut(),[,a]=As();return{onSave:async({page:i,blocks:l})=>{try{const o=await s(e,{action:"UPDATE_PAGE",data:{id:i,blocks:l}});return o.code==="PAGE_LOCKED"?(n(o.editor),!0):(a(u=>({...u,lastSaved:new Date().toISOString()})),o)}catch(o){return console.error(o),new Error("Failed to save blocks")}}}},kl=()=>{const{data:e}=ot(),s=oe(),n=ee();return{getPartialBlocks:g.useCallback(async()=>{const a={};for(const r of e??[])f.isEmpty(r==null?void 0:r.slug)&&(a[r.id]={type:r.pageType,name:f.startCase(r.name??r.slug),description:""});return a},[e]),getPartialBlockBlocks:g.useCallback(async a=>{if(!a)return[];try{const r=await n(s,{action:"GET_DRAFT_PAGE",data:{id:a,draft:!0,editor:!1}});return f.filter(r.blocks,i=>f.has(i,"_id"))}catch(r){return console.error(r),[]}},[n,s])}},In=ms.z.object({email:ms.z.string().email({message:"Please enter a valid email address"}),password:ms.z.string().min(6,{message:"Password must be at least 6 characters"})}),Pl=()=>{const{setUser:e,logout:s}=Ue(),n=Cs(),[a,r]=g.useState(""),[i,l]=g.useState(""),[o,u]=g.useState({}),[d,h]=g.useState(!1),[m,b]=g.useState(""),j=R.useMutation({mutationFn:async v=>{b("");const S=await tn(n,{action:"LOGIN",data:v});if(!S.ok){const L=await S.json();throw new Error(L.error||"Login failed")}const C=await S.json();if(f.has(C,"id")&&f.has(C,"email")&&f.has(C,"accessToken")&&f.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")}}),y=async v=>{v.preventDefault(),u({});const S={email:a,password:i};try{const C=In.parse(S);j.mutate(C)}catch(C){if(C instanceof ms.z.ZodError){const L=C.errors.reduce((k,D)=>{const G=D.path[0];return k[G]=D.message,k},{});u(L)}}},p=In.safeParse({email:a,password:i}).success;return t.jsx("div",{className:"flex justify-center items-center min-h-screen bg-slate-50",children:t.jsxs(c.Card,{className:"w-full max-w-md",children:[t.jsxs(c.CardHeader,{children:[t.jsx(c.CardTitle,{className:"text-2xl",children:"Sign in"}),t.jsx(c.CardDescription,{children:"Enter your credentials to sign in to visual builder"})]}),t.jsx(c.CardContent,{children:t.jsxs("form",{onSubmit:y,className:"space-y-4",children:[t.jsxs("div",{className:"space-y-1",children:[t.jsx(c.Label,{htmlFor:"email",children:"Email"}),t.jsx(c.Input,{id:"email",placeholder:"you@example.com",type:"email",value:a,onChange:v=>r(v.target.value),className:o.email?"border-destructive":""}),o.email&&t.jsx("p",{className:"text-sm text-destructive",children:o.email})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsx(c.Label,{htmlFor:"password",children:"Password"}),t.jsxs("div",{className:"relative",children:[t.jsx(c.Input,{id:"password",placeholder:"Enter your password",type:d?"text":"password",value:i,onChange:v=>l(v.target.value),className:o.password?"border-destructive":""}),t.jsx("button",{type:"button",className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground",onClick:()=>h(!d),children:d?t.jsx(w.EyeOff,{className:"h-4 w-4"}):t.jsx(w.Eye,{className:"h-4 w-4"})})]}),o.password&&t.jsx("p",{className:"text-sm text-destructive",children:o.password})]}),t.jsx("div",{children:t.jsx("p",{className:"text-sm text-destructive",children:m})}),t.jsx(c.Button,{type:"submit",className:"w-full",disabled:!p||j.isPending,children:j.isPending?t.jsxs(t.Fragment,{children:[t.jsx(w.Loader2,{className:"mr-2 h-4 w-4 animate-spin"}),"Logging in..."]}):"Login"})]})}),t.jsxs(c.CardFooter,{className:"flex flex-col justify-center",children:[t.jsxs("p",{className:"text-sm text-muted-foreground",children:["Forgot your password?"," ",t.jsx("a",{target:"_blank",href:"https://chaibuilder.com/forgot-password",className:"text-primary hover:underline",children:"Reset password"})]}),t.jsx("br",{}),t.jsx("br",{}),t.jsxs("div",{className:"flex items-center border-t pt-2 px-10 gap-2",children:["Powered by"," ",t.jsxs("a",{target:"_blank",href:"https://chaibuilder.com",className:"text-primary hover:underline flex items-center gap-1",children:[t.jsx("img",{src:"https://ucarecdn.com/a82e256c-1cf2-4755-b65c-5d85e7652daa/-/preview/400x400",alt:"Chai Builder",className:"w-4 h-4 rounded uppercase font-bold"}),"Chai Builder"]})]})]})]})})};let $s=Pl;const _l=()=>g.useMemo(()=>$s,[$s]),Il=e=>{$s=e},Ll=()=>{const e=_l();return t.jsx(g.Suspense,{fallback:t.jsx("div",{children:"Loading..."}),children:t.jsx(e,{})})},Dl=({page:e,onClose:s})=>{const[n,a]=g.useState(e.slug||""),{mutate:r,isPending:i}=ci(),{data:l}=Ce(),o=f.find(l,{key:e==null?void 0:e.pageType}),u=h=>{if(h.preventDefault(),!(e!=null&&e.primaryPage)&&Object.keys(Te).some(j=>n===`/${j}`||f.startsWith(n,`/${j}/`))){J.toast.error("Error",{description:"Slugs cannot start with a language code for primary page"});return}r({...e,slug:n},{onSuccess:s})},d=(e==null?void 0:e.lang)||"";return t.jsx(c.Dialog,{open:!!e,onOpenChange:s,children:t.jsxs(c.DialogContent,{children:[t.jsxs(c.DialogHeader,{children:[t.jsx(c.DialogTitle,{children:"Change Slug"}),t.jsx(c.DialogDescription,{className:"text-xs",children:t.jsxs(c.Alert,{variant:"destructive",className:"mt-2",children:[t.jsx(w.AlertCircle,{className:"h-4 w-4"}),"Changing the slug may have impact on your SEO. Please proceed with caution."]})})]}),t.jsxs("form",{onSubmit:u,children:[t.jsxs("div",{className:"space-y-4 py-4 text-sm ",children:[t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{children:[t.jsx("span",{children:"Type:"}),t.jsxs("span",{className:"font-medium text-gray-600",children:[" ",(o==null?void 0:o.name)||(e==null?void 0:e.pageType)]})]}),t.jsxs("div",{children:[t.jsx("span",{children:"Name:"}),t.jsxs("span",{className:"font-medium text-gray-600",children:[" ",e.name]})]})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsxs(c.Label,{htmlFor:"slug",className:"text-right",children:["Slug"," ",t.jsxs("small",{className:"font-light text-gray-500",children:["Slug should start with /",d]})]}),t.jsx(c.Input,{id:"slug",value:n,onChange:h=>{const m=h.target.value;f.startsWith(m,`/${d}`)&&a(m)},className:"col-span-3",required:!0,pattern:"^/.*",title:"Slug must start with /",placeholder:"Enter page slug"})]})]}),t.jsx(c.DialogFooter,{children:t.jsx(c.Button,{type:"submit",disabled:i||!f.startsWith(n,`/${d}`)||f.isEqual(e==null?void 0:e.slug,n),children:i?"Changing...":"Change Slug"})})]})]})})},Bl=()=>{const[,e]=we.useAtom(Ts),{selectedLang:s,fallbackLang:n,setSelectedLang:a}=F.useLanguages(),{data:r,isFetching:i}=Oe(),{data:l}=Pe(),{data:o}=Ce(),u=g.useMemo(()=>{const S=o==null?void 0:o.find(C=>C.key===(l==null?void 0:l.pageType));return S==null?void 0:S.dynamicSlug},[o,l==null?void 0:l.pageType]),[d,h]=g.useState(null),[m,b]=g.useState(null),[j,y]=g.useState(null),{data:p}=He(),v=f.filter(f.get(p,"languages")||["en"],S=>!f.find(r,{lang:S})&&S!==f.get(p,"fallbackLang"));return t.jsxs("div",{className:"space-y-4",children:[t.jsx("ul",{className:"space-y-2",children:i?t.jsxs("div",{className:"w-full space-y-3 py-4",children:[t.jsx("div",{className:"h-8 w-full animate-pulse rounded bg-gray-300"}),t.jsx("div",{className:"h-8 w-full animate-pulse rounded bg-gray-300"}),t.jsx("div",{className:"h-8 w-full animate-pulse rounded bg-gray-300"})]}):f.map(r,S=>{const C=S.lang,L=S.slug,k=!S.primaryPage,D=C===s;return t.jsxs(t.Fragment,{children:[t.jsxs("li",{className:`flex w-full cursor-pointer items-center justify-between rounded p-2 text-slate-500 ${D?"bg-gray-200":"hover:bg-gray-100"}`,onClick:()=>a(C),children:[t.jsxs("div",{className:"flex-1 gap-x-3",children:[t.jsxs("div",{className:"flex items-center gap-x-2 text-[13px] text-slate-800",children:[t.jsx("div",{className:`h-2.5 w-2.5 rounded-full ${S.online?"bg-green-300":"bg-gray-300"}`}),f.get(Te,k?n:C,C)]}),t.jsxs("div",{children:[L&&t.jsxs("div",{className:"text-[11px] font-light text-slate-600",children:["Slug: ",t.jsx("b",{className:"font-mono font-medium",children:u?`${L}/${u}`:L})]}),t.jsxs("div",{className:"text-[11px] font-light text-slate-600",children:["Name:",t.jsxs("b",{className:"font-medium",children:[" ",S.name," "]})]})]})]}),k?t.jsxs("div",{className:"flex items-center gap-x-1 text-[11px] text-orange-500",children:[t.jsx(w.StarIcon,{fill:"orange",className:"h-3 w-3"}),t.jsx("b",{children:" Primary"})]}):t.jsx("div",{className:"flex items-center gap-x-3",children:t.jsx(Re,{permissions:[ve.EDIT_PAGE,ve.DELETE_PAGE,ve.UNPUBLISH_PAGE],children:t.jsxs(c.DropdownMenu,{children:[t.jsx(c.DropdownMenuTrigger,{asChild:!0,onClick:G=>G.stopPropagation(),children:t.jsx(c.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",children:t.jsx(w.MoreHorizontal,{className:"h-4 w-4"})})}),t.jsxs(c.DropdownMenuContent,{align:"end",className:"z-[9999] text-sm",children:[t.jsx(Re,{permissions:[ve.EDIT_PAGE],children:t.jsxs(c.DropdownMenuItem,{className:"flex cursor-pointer items-center gap-2",onClick:G=>{G.stopPropagation(),e({edit:!0,id:S.id,primaryPage:S.primaryPage})},children:[t.jsx(w.PencilIcon,{className:"size-3"}),le.EDIT]})}),t.jsx(Re,{permissions:[ve.UNPUBLISH_PAGE],children:(S==null?void 0:S.online)&&t.jsxs(c.DropdownMenuItem,{className:"flex cursor-pointer items-center gap-2",onClick:G=>{G.stopPropagation(),b(S)},children:[t.jsx(w.Power,{className:"size-3"}),le.UNPUBLISH]})}),t.jsx(Re,{permissions:[ve.DELETE_PAGE],children:t.jsxs(c.DropdownMenuItem,{className:"flex cursor-pointer items-center gap-2",onClick:G=>{G.stopPropagation(),h(S)},children:[t.jsx(w.TrashIcon,{className:"size-3"}),le.DELETE]})})]})]})})})]},S.id),t.jsx("div",{className:"h-1 w-full border-b"})]})})}),t.jsx(Re,{permissions:[ve.ADD_PAGE],children:t.jsx("div",{className:"flex w-full justify-center",children:t.jsx(c.Button,{variant:"default",size:"sm",disabled:f.isEmpty(v),onClick:()=>{e({primaryPage:l==null?void 0:l.id,edit:!1})},children:le.ADD_NEW_LANGUAGE})})}),d&&t.jsx(ks,{page:d,onClose:()=>h(null)}),m&&t.jsx(is,{page:m,onClose:()=>b(null)}),j&&t.jsx(Dl,{page:j,onClose:()=>y(null)})]})},Gl=({isActive:e,show:s})=>{const{data:n}=He();return!f.has(n,"languages")||!f.get(n,"languages",[]).length?null:t.jsx(c.Button,{size:"sm",onClick:s,variant:e?"default":"ghost",children:t.jsx(w.LanguagesIcon,{className:"w-4 h-4"})})},wa="lang",Ml={id:wa,label:"Languages",position:"top",panel:Bl,button:Gl,view:"modal",width:400};function Ye({data:e,onSelect:s,dataType:n="value",disabled:a=!1}){const[r,i]=Se.useState(!1),[l,o]=Se.useState([]),[u,d]=Se.useState(e);Se.useEffect(()=>{r||o([]),d(e)},[e,r]);const h=y=>Array.isArray(y)?"array":typeof y=="object"&&y!==null?"object":"value",m=Se.useCallback(y=>{const p=v=>n==="value"?v==="value"||v==="object":n==="array"?v==="array":v===n;y.type==="object"?(o(v=>[...v,y.key]),d(y.value)):p(y.type)&&(s([...l,y.key].join(".")),i(!1))},[l,s,n]),b=Se.useCallback(()=>{if(l.length>0){const y=l.slice(0,-1);o(y),d(y.reduce((p,v)=>p[v],e))}},[l,e]),j=Se.useMemo(()=>Object.entries(u).map(([y,p])=>({key:y,value:p,type:h(p)})).filter(y=>n==="value"?y.type==="value"||y.type==="object":n==="array"?y.type==="array"||y.type==="object":n==="object"?y.type==="object":!0),[u,n]);return t.jsxs(c.Popover,{open:r,onOpenChange:i,children:[t.jsxs(c.Tooltip,{children:[t.jsx(c.TooltipTrigger,{asChild:!0,children:t.jsx(c.PopoverTrigger,{asChild:!0,children:t.jsx(c.Button,{size:"sm",variant:"outline",className:"h-6 w-6 px-1 py-0 text-[9px] text-muted-foreground",role:"combobox","aria-expanded":r,disabled:a,children:t.jsx(w.DatabaseIcon,{className:"h-3 w-3"})})})}),t.jsx(c.TooltipContent,{children:"Add field"})]}),t.jsx(c.PopoverContent,{className:"w-[200px] z-[9999] p-0",children:t.jsxs(c.Command,{children:[t.jsx(c.CommandInput,{className:"border-none",placeholder:"Search..."}),t.jsxs(c.CommandList,{onWheel:y=>{try{y.preventDefault();const p=y.currentTarget;p.scrollTop+=y.deltaY}catch{y.preventDefault()}},children:[t.jsx(c.CommandEmpty,{children:"No option found."}),t.jsxs(c.CommandGroup,{children:[l.length>0&&t.jsxs(c.CommandItem,{onSelect:b,className:"flex items-center text-sm",children:[t.jsx(w.ChevronLeft,{className:"w-4 h-4 mr-2"}),"Back"]}),j.map(y=>t.jsxs(c.CommandItem,{onSelect:()=>m(y),className:"flex items-center justify-between",children:[t.jsx("span",{children:y.key}),t.jsxs("div",{className:"flex items-center gap-2",children:[n==="object"&&y.type==="object"&&t.jsx(c.Button,{size:"sm",variant:"ghost",className:"h-6 px-2 hover:bg-primary hover:text-primary-foreground",onClick:p=>{p.stopPropagation(),s([...l,y.key].join(".")),i(!1)},children:"Select"}),(y.type==="object"||y.type==="array")&&t.jsx("div",{className:"p-1 rounded hover:bg-muted cursor-pointer",children:t.jsx(w.ChevronRight,{className:"w-4 h-4 opacity-50"})})]})]},y.key))]})]})]})})]})}const Rl=()=>{const{selectedLang:e}=F.useLanguages(),{data:s,isFetching:n}=Oe();return{data:g.useMemo(()=>f.find(s,{lang:e||""})||{},[s,e]),isFetching:n}},Ul=()=>{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, [data-block-type='PartialBlock']").forEach(o=>o.remove()),a.querySelectorAll("*").forEach(o=>{Array.from(o.attributes).forEach(u=>o.removeAttribute(u.name))});const r=a.querySelectorAll("h1, h2, h3, h4, h5, h6, p");return Array.from(r).map(o=>`<${o.tagName.toLowerCase()}>${o.innerHTML}</${o.tagName.toLowerCase()}>`).join(" ").replace(/<p>Partial block. Double click to edit.<\/p>/,"")},Mt=({keyword:e,onComplete:s,field:n})=>{const a=ee(),r=oe(),{selectedLang:i,fallbackLang:l}=F.useLanguages(),o=F.useBuilderProp("aiContext",""),{mutate:u,isPending:d}=R.useMutation({mutationFn:async()=>{const h=Ul();return await a(r,{action:I.GENERATE_SEO_FIELD,data:{pageContext:o,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(c.Button,{disabled:d,type:"button",className:"h-5 w-5",variant:"ghost",size:"sm",onClick:()=>u(),children:d?t.jsx(w.Loader2,{className:"h-3 w-3 animate-spin text-yellow-500"}):t.jsx(w.Sparkle,{className:"text-yellow-500"})})},Fl=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Ln=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,o=`"__placeholder_${n.length}__"`;n.push({original:i,replaced:o,position:l}),a=a.replace(i,o)}try{return{isValid:!0,parsed:JSON.parse(a),error:null,placeholders:n}}catch(i){const l=i,o=l.message.match(/position (\d+)/),u=o?parseInt(o[1]):void 0;let d,h;if(u!==void 0){const m=a.substring(0,u).split(`
3
+ `);d=m.length,h=m[m.length-1].length+1}return{isValid:!1,parsed:null,placeholders:n,error:{message:l.message,line:d,column:h,position:u}}}},Ol=(e,s)=>{let a=JSON.stringify(e,null,2);return s.forEach(({original:r},i)=>{const l=`"__placeholder_${i}__"`,o=new RegExp(Fl(l),"g");a=a.replace(o,r)}),a},ql=(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=f.get(s,i,null);n=n.replace(r[0],l)}return n},Ea=({value:e,onChange:s,disabled:n=!1,readOnly:a=!1,placeholder:r="Enter JSON",rows:i=6,id:l="json-input",pageData:o={},handleFieldInsert:u})=>{const[d,h]=g.useState("edit"),[m,b]=g.useState(null),[j,y]=g.useState(""),p=g.useRef(null),v=k=>{if(a)return;const D=k.target.value;s(D)},S=k=>{if(k.key==="Tab"){k.preventDefault();const D=k.currentTarget,G=D.selectionStart,X=D.selectionEnd;if(G!==X){const P=e.substring(G,X).split(`
4
+ `);if(k.shiftKey){const H=P.map(Q=>Q.startsWith(" ")?Q.substring(2):Q).join(`
5
+ `),K=e.substring(0,G)+H+e.substring(X);s(K),setTimeout(()=>{D.selectionStart=G,D.selectionEnd=G+H.length},0)}else{const H=P.map(Q=>` ${Q}`).join(`
6
+ `),K=e.substring(0,G)+H+e.substring(X);s(K),setTimeout(()=>{D.selectionStart=G,D.selectionEnd=G+H.length},0)}}else{const $=e.substring(0,G)+" "+e.substring(X);s($),setTimeout(()=>{D.selectionStart=D.selectionEnd=G+2},0)}}};g.useEffect(()=>{const k=Ln(e);if(k.isValid)if(b(null),k.parsed){const D=ql(k.parsed,o);y(D)}else y("");else b(k.error),y("")},[e,o]);const C=()=>{const k=Ln(e);if(k.isValid&&k.parsed){const D=Ol(k.parsed,k.placeholders);s(D)}},L=()=>{m!=null&&m.position&&p.current&&(p.current.focus(),p.current.setSelectionRange(m.position,m.position+1))};return t.jsx("div",{className:"space-y-2",children:t.jsxs(c.Tabs,{value:d,onValueChange:h,className:"w-full",children:[t.jsxs("div",{className:"mb-2 flex items-center justify-between",children:[t.jsxs(c.TabsList,{className:"grid w-[200px] grid-cols-2",children:[t.jsxs(c.TabsTrigger,{value:"edit",className:"flex items-center gap-1",children:[t.jsx(w.Code,{className:"h-4 w-4"}),t.jsx("span",{children:"Edit"})]}),t.jsxs(c.TabsTrigger,{value:"preview",className:"flex items-center gap-1",disabled:!e.trim()||m!==null,children:[t.jsx(w.Eye,{className:"h-4 w-4"}),t.jsx("span",{children:"Preview"})]})]}),d==="edit"&&!a&&t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(Ye,{dataType:"value",data:o??{},onSelect:k=>u&&u(k,l)}),t.jsx(c.Button,{type:"button",variant:"outline",size:"sm",onClick:C,disabled:!e.trim()||n||m!==null,children:"Format"})]})]}),t.jsxs(c.TabsContent,{value:"edit",className:"mt-0",children:[t.jsx(c.Textarea,{ref:p,id:l,name:l,className:`rounded-md border border-input text-xs ${m?"border-red-500":""}`,onChange:v,onKeyDown:S,value:e,placeholder:r,rows:i,disabled:n,readOnly:a}),m&&t.jsxs(c.Alert,{variant:"destructive",className:"mt-2",children:[t.jsx(w.AlertTriangle,{className:"h-4 w-4"}),t.jsxs(c.AlertDescription,{className:"flex flex-col",children:[t.jsx("span",{className:"font-medium",children:"Invalid JSON"}),t.jsx("span",{className:"text-sm",children:m.message}),m.line&&m.column&&t.jsxs("span",{className:"text-sm",children:["Error at line ",m.line,", column ",m.column]}),t.jsx(c.Button,{type:"button",variant:"link",size:"sm",className:"mt-1 h-auto self-start p-0 text-sm",onClick:L,children:"Show position"})]})]})]}),t.jsxs(c.TabsContent,{value:"preview",className:"mt-0",children:[t.jsx(c.Textarea,{rows:i,value:j,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."})]})]})})},Dn=e=>{if(!e)return!0;try{return JSON.parse(e),!0}catch{return!1}},$l=(e,s)=>{const n=e.selectionStart||0,a=e.selectionEnd||0,r=e.value,i=r.substring(0,n),l=r.substring(a),o=`{{${s}}}`,u=i+""+o+l,d=n+0+o.length;return{value:u,newCursorPos:d}},Na=()=>{const{t:e}=F.useTranslation(),[,s]=F.useSidebarActivePanel(),{data:n}=Pe(),{data:a}=rn(),{data:r,isFetching:i}=Rl(),l=r==null?void 0:r.seo,o=g.useRef(null),u=n==null?void 0:n.pageType,d=ua(u),{selectedLang:h,fallbackLang:m}=F.useLanguages(),b=h||m,[j,y]=g.useState(!1),[p,v]=g.useState(!1),[S,C]=g.useState({keyword:"",title:"",description:"",cononicalUrl:"",noIndex:!1,noFollow:"",ogTitle:"",ogDescription:"",ogImage:"",ogImageId:"",searchTitle:"",searchDescription:"",jsonLD:"{}",...l}),L=g.useRef({initial:S,updated:S}),{mutate:k,isPending:D}=ln(),G=D||j||p,{hasPermission:X}=F.usePermissions(),$=X(ve.EDIT_SEO);g.useEffect(()=>{!i&&l&&C({title:"",description:"",cononicalUrl:"",noIndex:!1,noFollow:"",ogTitle:"",ogDescription:"",ogImage:"",searchTitle:"",searchDescription:"",jsonLD:"",...l})},[i,l]);const P=async()=>{if(!(!d||!b))try{y(!0);const _=xs(d,b),q={...S,keyword:f.get(_,"seo.keyword",""),title:f.get(_,"seo.title",""),description:f.get(_,"seo.description",""),cononicalUrl:f.get(_,"seo.canonicalUrl",""),noIndex:f.get(_,"seo.noIndex",!1),noFollow:f.get(_,"seo.noFollow",!1),ogTitle:f.get(_,"seo.ogTitle",""),ogDescription:f.get(_,"seo.ogDescription","")};C(q),L.current.updated=q,J.toast.success(e("SEO fields reset to defaults"))}catch(_){J.toast.error(e("Failed to reset SEO fields")),console.error("Reset SEO error:",_)}finally{y(!1)}},M=async()=>{if(!(!d||!b))try{v(!0);const _=xs(d,b),q={...S,jsonLD:f.get(_,"seo.jsonLD","")};C(q),L.current.updated=q,J.toast.success(e("JSON-LD reset to default"))}catch(_){J.toast.error(e("Failed to reset JSON-LD")),console.error("Reset JSON-LD error:",_)}finally{v(!1)}},H=async()=>{k({id:r==null?void 0:r.id,seo:S},{onSuccess:()=>{L.current.initial=S,L.current.updated=S,s("outline"),J.toast.success("SEO & JSON-LD updated successfully")}})},K=(_,q)=>{const fe=document.getElementById(q);if(fe){const{value:be,newCursorPos:ue}=$l(fe,_);o.current={id:q,position:ue},fe.tagName.toLowerCase()==="input"?(fe.value=be,C(N=>({...N,[fe.name]:be})),fe.focus(),fe.setSelectionRange(ue,ue),[0,10,50,100,200].forEach(N=>{setTimeout(()=>{const U=document.getElementById(q);U&&(U.focus(),U.setSelectionRange(ue,ue))},N)})):(C(x=>({...x,[fe.name]:be})),requestAnimationFrame(()=>{const x=document.getElementById(q);x&&(x.focus(),x.setSelectionRange(ue,ue),setTimeout(()=>{const N=document.getElementById(q);N&&(N.focus(),N.setSelectionRange(ue,ue))},50))}))}},Q=_=>{const q={...S,[_.target.name]:_.target.name==="noIndex"||_.target.name==="noFollow"?_.target.checked:_.target.value};C(q),L.current.updated=q},Z=_=>q=>{f.isEmpty(q.fieldValue)||Q({target:{name:_,value:typeof q.fieldValue=="string"?q.fieldValue.replace(/^"(.*)"$/,"$1"):q.fieldValue}}),q.error&&J.toast.error(t.jsxs("div",{children:[t.jsx("h2",{children:"Failed to generate:"}),t.jsx("p",{children:q.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(c.Alert,{variant:"default",className:"w-[80%] max-w-md text-xs",children:t.jsx(c.AlertDescription,{children:e("You don't have permission to edit SEO settings. Contact your administrator for access.")})})}),t.jsxs("div",{className:"no-scrollbar flex-grow overflow-y-auto px-2 pb-20",children:[t.jsxs("div",{className:"mb-4 flex w-full items-center justify-between rounded-md bg-gray-100 p-2 text-left text-sm font-bold",children:[t.jsxs("span",{children:[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(yn,{variant:"outline",showAdd:!1})]}),t.jsx("form",{className:"space-y-8",children:t.jsxs(c.Tabs,{defaultValue:"seo",className:"w-full",children:[t.jsxs(c.TabsList,{className:"mb-4 grid w-full grid-cols-2",children:[t.jsx(c.TabsTrigger,{value:"seo",children:e("SEO Fields")}),t.jsx(c.TabsTrigger,{value:"jsonld",children:e("JSON-LD")})]}),t.jsx(c.TabsContent,{value:"seo",children:t.jsxs("div",{className:"space-y-4",children:[$&&t.jsx("div",{className:"mb-4 flex justify-end",children:t.jsx(c.Button,{type:"button",variant:"outline",size:"sm",onClick:P,disabled:G||!$||!d,children:e(j?"Resetting...":"Reset to Default")})}),t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(c.Label,{className:"text-xs",htmlFor:"keyword",children:e("Keyword")}),$&&t.jsx(Ye,{dataType:"value",data:a??{},onSelect:_=>K(_,"keyword")})]}),t.jsx(c.Input,{type:"text",id:"keyword",name:"keyword",value:S.keyword,onChange:Q,disabled:G||!$,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(c.Label,{className:"text-xs",htmlFor:"title",children:e("SEO Title")}),t.jsxs("div",{className:"flex items-center justify-end gap-2",children:[t.jsx(Mt,{keyword:S.keyword,onComplete:Z("title"),field:"title"}),$&&t.jsx(Ye,{dataType:"value",data:a??{},onSelect:_=>K(_,"title")})]})]}),t.jsx(c.Input,{type:"text",id:"title",name:"title",value:S.title,onChange:Q,disabled:G||!$,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(c.Label,{className:"text-xs",htmlFor:"description",children:e("SEO Description")}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(Mt,{keyword:S.keyword,onComplete:Z("description"),field:"description"}),$&&t.jsx(Ye,{data:a??{},onSelect:_=>K(_,"description")})]})]}),t.jsx(c.Textarea,{id:"description",name:"description",rows:5,value:S.description,onChange:Q,disabled:G||!$,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(c.Label,{className:"text-xs",htmlFor:"title",children:e("Canonical URL")}),$&&t.jsx(Ye,{dataType:"value",data:a??{},onSelect:_=>K(_,"canonicalUrl")})]}),t.jsx(c.Input,{type:"text",id:"canonicalUrl",name:"canonicalUrl",value:S.canonicalUrl,onChange:Q,disabled:G||!$,placeholder:e("Enter Canonical URL"),readOnly:!$})]}),t.jsxs("div",{className:"",children:[t.jsxs("div",{className:"flex items-center gap-x-2",children:[t.jsx(c.Input,{type:"checkbox",id:"noIndex",name:"noIndex",checked:S.noIndex,onChange:Q,disabled:G||!$,className:"h-4 w-4"}),t.jsx(c.Label,{className:"pb-1 text-xs",htmlFor:"noIndex",children:e("No Index")})]}),t.jsx("p",{className:"mt-0 text-[10px] font-light leading-4 text-gray-400",children:e("Check this if you don't want search engines to index this page.")})]}),t.jsxs("div",{className:"",children:[t.jsxs("div",{className:"flex items-center gap-x-2",children:[t.jsx(c.Input,{type:"checkbox",id:"noFollow",name:"noFollow",checked:S.noFollow,onChange:Q,disabled:G||!$,className:"h-4 w-4"}),t.jsx(c.Label,{className:"pb-1 text-xs",htmlFor:"noIndex",children:e("No Follow")})]}),t.jsx("p",{className:"text-[10px] font-light leading-4 text-gray-400",children:e("Check this if you don't want search engines to follow links on this page.")})]}),t.jsxs("div",{children:[t.jsx("h3",{className:"mb-4 font-semibold text-slate-700",children:e("Open Graph")}),t.jsxs("div",{className:"space-y-4",children:[t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(c.Label,{className:"text-xs",htmlFor:"ogTitle",children:e("OG Title")}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(Mt,{keyword:S.keyword,onComplete:Z("ogTitle"),field:"ogTitle"}),$&&t.jsx(Ye,{dataType:"value",data:a??{},onSelect:_=>K(_,"ogTitle")})]})]}),t.jsx(c.Input,{type:"text",id:"ogTitle",name:"ogTitle",value:S.ogTitle,onChange:Q,disabled:G||!$,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(c.Label,{className:"text-xs",htmlFor:"ogDescription",children:e("OG Description")}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(Mt,{keyword:S.keyword,onComplete:Z("ogDescription"),field:"ogDescription"}),$&&t.jsx(Ye,{dataType:"value",data:a??{},onSelect:_=>K(_,"ogDescription")})]})]}),t.jsx(c.Textarea,{id:"ogDescription",name:"ogDescription",rows:5,value:S.ogDescription,onChange:Q,disabled:G||!$,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(c.Label,{className:"text-xs",htmlFor:"ogImage",children:e("OG Image")})}),t.jsx(Ns,{assetId:S.ogImageId,assetUrl:S.ogImage,onChange:_=>{C({...S,ogImage:_.url,ogImageId:_.id})},disabled:G||!$,placeholder:e("Select OG image"),className:"mb-2"})]})]})]})]})}),t.jsx(c.TabsContent,{value:"jsonld",children:t.jsxs("div",{className:"space-y-4",children:[$&&t.jsx("div",{className:"mb-4 flex justify-end",children:t.jsx(c.Button,{variant:"outline",size:"sm",type:"button",onClick:M,disabled:G||!$||!d,children:e(p?"Resetting...":"Reset to Default")})}),t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(c.Label,{className:"text-xs",htmlFor:"jsonLD",children:e("JSON-LD")}),t.jsx("div",{className:"flex items-center gap-2",children:t.jsx(Mt,{keyword:S.keyword,onComplete:Z("jsonLD"),field:"jsonLD"})})]}),t.jsx("div",{className:"hidden",children:JSON.stringify(a)}),t.jsx(Ea,{id:"jsonLD",value:S.jsonLD,onChange:_=>{Q({target:{name:"jsonLD",value:_}})},placeholder:e("Enter JSON-LD"),disabled:G||!$,readOnly:!$,pageData:a||{},rows:12,handleFieldInsert:K})]})]})})]})})]}),$&&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:[Dn(S.jsonLD)?t.jsx("div",{}):t.jsx("p",{className:"text-xs text-red-500",children:e("Invalid JSON. Please check.")}),t.jsxs("div",{className:"flex items-center gap-4",children:[t.jsx(c.Button,{onClick:H,disabled:!Dn(S==null?void 0:S.jsonLD)||f.isEqual(L.current.initial,S)||G||!$,children:e(D?"Saving...":"Save")}),t.jsx(c.Button,{variant:"link",className:"text-gray-500 hover:text-gray-700",onClick:()=>s("outline"),children:e("Cancel")})]})]})]})};Na.displayName="SeoPanel";const Ca="seo",zl=({isActive:e,show:s})=>{const{data:n}=Pe(),a=ua(n==null?void 0:n.pageType);return!f.has(a,"hasSlug")||!a.hasSlug?null:t.jsx(c.Button,{size:"sm",className:"my-1",onClick:s,variant:e?"default":"ghost",children:t.jsxs("svg",{className:"h-4 w-4",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 21 21",fill:"currentColor",children:[t.jsx("path",{d:"M9.931 6.818c-1.238 0-2.136.925-2.136 2.2 0 1.279.898 2.207 2.136 2.207.664 0 1.257-.246 1.67-.694a.15.15 0 0 0-.009-.213l-.311-.286a.15.15 0 0 0-.213.009c-.273.297-.677.46-1.137.46-.699 0-1.233-.444-1.375-1.12h3.295a.15.15 0 0 0 .151-.151v-.211c0-1.295-.852-2.2-2.072-2.2m0 .724c.697 0 1.188.422 1.315 1.113h-2.69c.142-.673.676-1.113 1.374-1.113m4.332-.724c-1.246 0-2.15.925-2.15 2.2 0 1.279.904 2.207 2.15 2.207.596 0 1.143-.223 1.538-.628s.612-.965.612-1.579c0-1.275-.904-2.2-2.15-2.2m0 3.683c-.826 0-1.426-.624-1.426-1.483 0-.855.6-1.475 1.426-1.475s1.426.621 1.426 1.476c0 .423-.144.804-.406 1.073-.258.264-.62.41-1.019.41M6.318 8.71c-.665-.206-.902-.335-.902-.645 0-.47.564-.521.806-.521.29 0 .552.07.801.215a.15.15 0 0 0 .206-.055l.212-.366a.15.15 0 0 0-.055-.206 2.27 2.27 0 0 0-1.165-.312c-.915 0-1.53.501-1.53 1.245 0 .899.816 1.152 1.411 1.336.655.203.812.307.804.53-.016.398-.567.429-.735.429-.386 0-.722-.129-.972-.374q-.043-.042-.107-.043a.15.15 0 0 0-.106.045l-.295.302a.15.15 0 0 0 .002.213c.383.374.908.58 1.478.58.859 0 1.432-.441 1.459-1.125.031-.833-.746-1.074-1.313-1.249"}),t.jsx("path",{d:"M20.396 2.049H.604A.604.604 0 0 0 0 2.653v12.7c0 .333.27.604.604.604h6.941c-.266 1.296-.881 1.966-.886 1.971a.604.604 0 0 0 .434 1.024h6.815a.604.604 0 0 0 .434-1.024c-.007-.007-.621-.675-.886-1.971h6.941c.333 0 .604-.27.604-.604V2.652a.604.604 0 0 0-.604-.604m-.604 12.701h-.985v-.17a.604.604 0 0 0-1.208 0v.17h-.63v-.17a.604.604 0 0 0-1.208 0v.17H1.207V3.256h18.585z"})]})})},Vl={id:Ca,label:"SEO & JSON-LD",panel:Na,button:zl,position:"top",width:600,view:"modal"},zs={},Vs=(e,s)=>{f.has(zs,e)&&console.warn(`Site setting ${e} already registered. Overriding...`),f.set(zs,e,{id:e,...s})},Kl=()=>f.values(zs),Hl=()=>{var i;const e=Kl(),[s,n]=g.useState(((i=e[0])==null?void 0:i.id)||""),a=e.find(l=>l.id===s),r=a==null?void 0:a.panel;return t.jsxs("div",{className:"flex h-full gap-4",children:[t.jsx("div",{className:"w-1/5 border-r pr-2 no-scrollbar overflow-y-auto",children:t.jsx("div",{className:"space-y-1",children:e.map(l=>{const o=l.id===s,u=l.button;return t.jsx("div",{className:"mb-1",children:t.jsx(u,{isActive:o,onClick:()=>n(l.id)})},l.id)})})}),t.jsx("div",{className:"w-4/5 no-scrollbar overflow-y-auto",children:t.jsx(g.Suspense,{fallback:t.jsx("div",{className:"flex items-center justify-center h-full",children:"Loading..."}),children:r?t.jsx(r,{}):t.jsx("div",{className:"flex items-center justify-center h-full text-muted-foreground",children:t.jsx("p",{children:"Select a setting from the sidebar or register settings using registerChaiSiteSetting"})})})})]})},Ql="site-settings",Wl=({isActive:e,show:s})=>F.useChaiFeatureFlag("enable-site-settings")?t.jsx(c.Button,{size:"sm",className:"my-1",onClick:s,variant:e?"default":"ghost",children:t.jsx(w.Settings,{className:"h-4 w-4"})}):null,Yl={id:Ql,label:"Site Settings",panel:Hl,button:Wl,position:"bottom",width:800,view:"modal"},Jl="user-info",Xl=()=>{const{user:e,logout:s}=Ue(),n=R.useQueryClient(),a=qe("onLogout",f.noop);return e?t.jsxs(c.HoverCard,{children:[t.jsx(c.HoverCardTrigger,{asChild:!0,children:t.jsx(c.Button,{variant:"ghost",className:"text-sm font-medium",children:t.jsx(w.User,{className:"w-4 h-4"})})}),t.jsxs(c.HoverCardContent,{className:"w-auto p-4 space-y-2",children:[t.jsx("div",{className:"text-sm font-medium",children:e.name??e.email}),t.jsx("div",{className:"text-xs text-muted-foreground",children:e.email}),t.jsxs(c.AlertDialog,{children:[t.jsx(c.AlertDialogTrigger,{asChild:!0,children:t.jsx(c.Button,{variant:"outline",size:"sm",className:"w-full",children:"Logout"})}),t.jsxs(c.AlertDialogContent,{children:[t.jsxs(c.AlertDialogHeader,{children:[t.jsx(c.AlertDialogTitle,{children:"Are you sure you want to logout?"}),t.jsx(c.AlertDialogDescription,{children:"You will be redirected to the login page."})]}),t.jsxs(c.AlertDialogFooter,{children:[t.jsx(c.AlertDialogCancel,{children:"Cancel"}),t.jsx(c.AlertDialogAction,{onClick:()=>{s(),n.invalidateQueries({queryKey:[W]}),f.isFunction(a)&&a()},children:"Logout"})]})]})]})]})]}):null},Zl={id:Jl,label:"User Info",button:Xl,position:"bottom"},eo=()=>{F.registerChaiSidebarPanel(Ca,Vl),F.registerChaiSidebarPanel(wa,Ml),F.registerChaiSidebarPanel("site-settings",Yl),F.registerChaiSidebarPanel("user-info",Zl)};var re={context:void 0,registry:void 0,effects:void 0,done:!1,getContextId(){return Bn(this.context.count)},getNextContextId(){return Bn(this.context.count++)}};function Bn(e){const s=String(e),n=s.length-1;return re.context.id+(n?String.fromCharCode(96+n):"")+s}function Rt(e){re.context=e}var to=(e,s)=>e===s,ps=Symbol("solid-proxy"),Aa=typeof Proxy=="function",jn=Symbol("solid-track"),ys={equals:to},Ta=Ba,We=1,js=2,ka={owned:null,cleanups:null,context:null,owner:null},Rs={},ge=null,Us=null,so=null,ye=null,Le=null,Ke=null,Ps=0;function Je(e,s){const n=ye,a=ge,r=e.length===0,i=s===void 0?a:s,l=r?ka:{owned:null,cleanups:null,context:i?i.context:null,owner:i},o=r?e:()=>e(()=>ke(()=>zt(l)));ge=l,ye=null;try{return ze(o,!0)}finally{ye=n,ge=a}}function Ee(e,s){s=s?Object.assign({},ys,s):ys;const n={value:e,observers:null,observerSlots:null,comparator:s.equals||void 0},a=r=>(typeof r=="function"&&(r=r(n.value)),Da(n,r));return[La.bind(n),a]}function Pa(e,s,n){const a=_s(e,s,!0,We);Lt(a)}function Xe(e,s,n){const a=_s(e,s,!1,We);Lt(a)}function vn(e,s,n){Ta=po;const a=_s(e,s,!1,We);(!n||!n.render)&&(a.user=!0),Ke?Ke.push(a):Lt(a)}function Ge(e,s,n){n=n?Object.assign({},ys,n):ys;const a=_s(e,s,!0,0);return a.observers=null,a.observerSlots=null,a.comparator=n.equals||void 0,Lt(a),La.bind(a)}function no(e){return e&&typeof e=="object"&&"then"in e}function ao(e,s,n){let a,r,i;arguments.length===1?(a=!0,r=e,i={}):(a=e,r=s,i={});let l=null,o=Rs,u=null,d=!1,h="initialValue"in i,m=typeof a=="function"&&Ge(a);const b=new Set,[j,y]=(i.storage||Ee)(i.initialValue),[p,v]=Ee(void 0),[S,C]=Ee(void 0,{equals:!1}),[L,k]=Ee(h?"ready":"unresolved");re.context&&(u=re.getNextContextId(),i.ssrLoadFrom==="initial"?o=i.initialValue:re.load&&re.has(u)&&(o=re.load(u)));function D(P,M,H,K){return l===P&&(l=null,K!==void 0&&(h=!0),(P===o||M===o)&&i.onHydrated&&queueMicrotask(()=>i.onHydrated(K,{value:M})),o=Rs,G(M,H)),M}function G(P,M){ze(()=>{M===void 0&&y(()=>P),k(M!==void 0?"errored":h?"ready":"unresolved"),v(M);for(const H of b.keys())H.decrement();b.clear()},!1)}function X(){const P=fo,M=j(),H=p();if(H!==void 0&&!l)throw H;return ye&&ye.user,M}function $(P=!0){if(P!==!1&&d)return;d=!1;const M=m?m():a;if(M==null||M===!1){D(l,ke(j));return}const H=o!==Rs?o:ke(()=>r(M,{value:j(),refetching:P}));return no(H)?(l=H,"value"in H?(H.status==="success"?D(l,H.value,void 0,M):D(l,void 0,Ks(H.value),M),H):(d=!0,queueMicrotask(()=>d=!1),ze(()=>{k(h?"refreshing":"pending"),C()},!1),H.then(K=>D(H,K,void 0,M),K=>D(H,void 0,Ks(K),M)))):(D(l,H,void 0,M),H)}return Object.defineProperties(X,{state:{get:()=>L()},error:{get:()=>p()},loading:{get(){const P=L();return P==="pending"||P==="refreshing"}},latest:{get(){if(!h)return X();const P=p();if(P&&!l)throw P;return j()}}}),m?Pa(()=>$(!1)):$(!1),[X,{refetch:$,mutate:y}]}function ro(e){return ze(e,!1)}function ke(e){if(ye===null)return e();const s=ye;ye=null;try{return e()}finally{ye=s}}function io(e,s,n){const a=Array.isArray(e);let r,i=n&&n.defer;return l=>{let o;if(a){o=Array(e.length);for(let d=0;d<e.length;d++)o[d]=e[d]()}else o=e();if(i)return i=!1,l;const u=ke(()=>s(o,r,l));return r=o,u}}function _a(e){vn(()=>ke(e))}function kt(e){return ge===null||(ge.cleanups===null?ge.cleanups=[e]:ge.cleanups.push(e)),e}function Gn(){return ge}function lo(e,s){const n=ge,a=ye;ge=e,ye=null;try{return ze(s,!0)}catch(r){bn(r)}finally{ge=n,ye=a}}function oo(e){const s=ye,n=ge;return Promise.resolve().then(()=>{ye=s,ge=n;let a;return ze(e,!1),ye=ge=null,a?a.done:void 0})}var[co,bu]=Ee(!1);function uo(){return[co,oo]}function ho(e,s){const n=Symbol("context");return{id:n,Provider:yo(n),defaultValue:e}}function mo(e){let s;return ge&&ge.context&&(s=ge.context[e.id])!==void 0?s:e.defaultValue}function Ia(e){const s=Ge(e),n=Ge(()=>Hs(s()));return n.toArray=()=>{const a=n();return Array.isArray(a)?a:a!=null?[a]:[]},n}var fo;function La(){if(this.sources&&this.state)if(this.state===We)Lt(this);else{const e=Le;Le=null,ze(()=>bs(this),!1),Le=e}if(ye){const e=this.observers?this.observers.length:0;ye.sources?(ye.sources.push(this),ye.sourceSlots.push(e)):(ye.sources=[this],ye.sourceSlots=[e]),this.observers?(this.observers.push(ye),this.observerSlots.push(ye.sources.length-1)):(this.observers=[ye],this.observerSlots=[ye.sources.length-1])}return this.value}function Da(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=Us&&Us.running;l&&Us.disposed.has(i),(l?!i.tState:!i.state)&&(i.pure?Le.push(i):Ke.push(i),i.observers&&Ga(i)),l||(i.state=We)}if(Le.length>1e6)throw Le=[],new Error},!1)),s}function Lt(e){if(!e.fn)return;zt(e);const s=Ps;go(e,e.value,s)}function go(e,s,n){let a;const r=ge,i=ye;ye=ge=e;try{a=e.fn(s)}catch(l){return e.pure&&(e.state=We,e.owned&&e.owned.forEach(zt),e.owned=null),e.updatedAt=n+1,bn(l)}finally{ye=i,ge=r}(!e.updatedAt||e.updatedAt<=n)&&(e.updatedAt!=null&&"observers"in e?Da(e,a):e.value=a,e.updatedAt=n)}function _s(e,s,n,a=We,r){const i={fn:e,state:a,updatedAt:null,owned:null,sources:null,sourceSlots:null,cleanups:null,value:s,owner:ge,context:ge?ge.context:null,pure:n};return ge===null||ge!==ka&&(ge.owned?ge.owned.push(i):ge.owned=[i]),i}function vs(e){if(e.state===0)return;if(e.state===js)return bs(e);if(e.suspense&&ke(e.suspense.inFallback))return e.suspense.effects.push(e);const s=[e];for(;(e=e.owner)&&(!e.updatedAt||e.updatedAt<Ps);)e.state&&s.push(e);for(let n=s.length-1;n>=0;n--)if(e=s[n],e.state===We)Lt(e);else if(e.state===js){const a=Le;Le=null,ze(()=>bs(e,s[0]),!1),Le=a}}function ze(e,s){if(Le)return e();let n=!1;s||(Le=[]),Ke?n=!0:Ke=[],Ps++;try{const a=e();return xo(n),a}catch(a){n||(Ke=null),Le=null,bn(a)}}function xo(e){if(Le&&(Ba(Le),Le=null),e)return;const s=Ke;Ke=null,s.length&&ze(()=>Ta(s),!1)}function Ba(e){for(let s=0;s<e.length;s++)vs(e[s])}function po(e){let s,n=0;for(s=0;s<e.length;s++){const a=e[s];a.user?e[n++]=a:vs(a)}if(re.context){if(re.count){re.effects||(re.effects=[]),re.effects.push(...e.slice(0,n));return}Rt()}for(re.effects&&(re.done||!re.count)&&(e=[...re.effects,...e],n+=re.effects.length,delete re.effects),s=0;s<n;s++)vs(e[s])}function bs(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===We?a!==s&&(!a.updatedAt||a.updatedAt<Ps)&&vs(a):r===js&&bs(a,s)}}}function Ga(e){for(let s=0;s<e.observers.length;s+=1){const n=e.observers[s];n.state||(n.state=js,n.pure?Le.push(n):Ke.push(n),n.observers&&Ga(n))}}function zt(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--)zt(e.tOwned[s]);delete e.tOwned}if(e.owned){for(s=e.owned.length-1;s>=0;s--)zt(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 Ks(e){return e instanceof Error?e:new Error(typeof e=="string"?e:"Unknown error",{cause:e})}function bn(e,s=ge){throw Ks(e)}function Hs(e){if(typeof e=="function"&&!e.length)return Hs(e());if(Array.isArray(e)){const s=[];for(let n=0;n<e.length;n++){const a=Hs(e[n]);Array.isArray(a)?s.push.apply(s,a):s.push(a)}return s}return e}function yo(e,s){return function(a){let r;return Xe(()=>r=ke(()=>(ge.context={...ge.context,[e]:a.value},Ia(()=>a.children))),void 0),r}}var Qs=Symbol("fallback");function Ss(e){for(let s=0;s<e.length;s++)e[s]()}function jo(e,s,n={}){let a=[],r=[],i=[],l=0,o=s.length>1?[]:null;return kt(()=>Ss(i)),()=>{let u=e()||[],d=u.length,h,m;return u[jn],ke(()=>{let j,y,p,v,S,C,L,k,D;if(d===0)l!==0&&(Ss(i),i=[],a=[],r=[],l=0,o&&(o=[])),n.fallback&&(a=[Qs],r[0]=Je(G=>(i[0]=G,n.fallback())),l=1);else if(l===0){for(r=new Array(d),m=0;m<d;m++)a[m]=u[m],r[m]=Je(b);l=d}else{for(p=new Array(d),v=new Array(d),o&&(S=new Array(d)),C=0,L=Math.min(l,d);C<L&&a[C]===u[C];C++);for(L=l-1,k=d-1;L>=C&&k>=C&&a[L]===u[k];L--,k--)p[k]=r[L],v[k]=i[L],o&&(S[k]=o[L]);for(j=new Map,y=new Array(k+1),m=k;m>=C;m--)D=u[m],h=j.get(D),y[m]=h===void 0?-1:h,j.set(D,m);for(h=C;h<=L;h++)D=a[h],m=j.get(D),m!==void 0&&m!==-1?(p[m]=r[h],v[m]=i[h],o&&(S[m]=o[h]),m=y[m],j.set(D,m)):i[h]();for(m=C;m<d;m++)m in p?(r[m]=p[m],i[m]=v[m],o&&(o[m]=S[m],o[m](m))):r[m]=Je(b);r=r.slice(0,l=d),a=u.slice(0)}return r});function b(j){if(i[m]=j,o){const[y,p]=Ee(m);return o[m]=p,s(u[m],y)}return s(u[m])}}}function vo(e,s,n={}){let a=[],r=[],i=[],l=[],o=0,u;return kt(()=>Ss(i)),()=>{const d=e()||[],h=d.length;return d[jn],ke(()=>{if(h===0)return o!==0&&(Ss(i),i=[],a=[],r=[],o=0,l=[]),n.fallback&&(a=[Qs],r[0]=Je(b=>(i[0]=b,n.fallback())),o=1),r;for(a[0]===Qs&&(i[0](),i=[],a=[],r=[],o=0),u=0;u<h;u++)u<a.length&&a[u]!==d[u]?l[u](()=>d[u]):u>=a.length&&(r[u]=Je(m));for(;u<a.length;u++)i[u]();return o=l.length=i.length=h,a=d.slice(0),r=r.slice(0,o)});function m(b){i[u]=b;const[j,y]=Ee(d[u]);return l[u]=y,s(j,u)}}}function Sn(e,s){return ke(()=>e(s||{}))}function us(){return!0}var Ws={get(e,s,n){return s===ps?n:e.get(s)},has(e,s){return s===ps?!0:e.has(s)},set:us,deleteProperty:us,getOwnPropertyDescriptor(e,s){return{configurable:!0,enumerable:!0,get(){return e.get(s)},set:us,deleteProperty:us}},ownKeys(e){return e.keys()}};function Fs(e){return(e=typeof e=="function"?e():e)?e:{}}function bo(){for(let e=0,s=this.length;e<s;++e){const n=this[e]();if(n!==void 0)return n}}function wn(...e){let s=!1;for(let l=0;l<e.length;l++){const o=e[l];s=s||!!o&&ps in o,e[l]=typeof o=="function"?(s=!0,Ge(o)):o}if(Aa&&s)return new Proxy({get(l){for(let o=e.length-1;o>=0;o--){const u=Fs(e[o])[l];if(u!==void 0)return u}},has(l){for(let o=e.length-1;o>=0;o--)if(l in Fs(e[o]))return!0;return!1},keys(){const l=[];for(let o=0;o<e.length;o++)l.push(...Object.keys(Fs(e[o])));return[...new Set(l)]}},Ws);const n={},a=Object.create(null);for(let l=e.length-1;l>=0;l--){const o=e[l];if(!o)continue;const u=Object.getOwnPropertyNames(o);for(let d=u.length-1;d>=0;d--){const h=u[d];if(h==="__proto__"||h==="constructor")continue;const m=Object.getOwnPropertyDescriptor(o,h);if(!a[h])a[h]=m.get?{enumerable:!0,configurable:!0,get:bo.bind(n[h]=[m.get.bind(o)])}:m.value!==void 0?m:void 0;else{const b=n[h];b&&(m.get?b.push(m.get.bind(o)):m.value!==void 0&&b.push(()=>m.value))}}}const r={},i=Object.keys(a);for(let l=i.length-1;l>=0;l--){const o=i[l],u=a[o];u&&u.get?Object.defineProperty(r,o,u):r[o]=u?u.value:void 0}return r}function Ma(e,...s){if(Aa&&ps in e){const r=new Set(s.length>1?s.flat():s[0]),i=s.map(l=>new Proxy({get(o){return l.includes(o)?e[o]:void 0},has(o){return l.includes(o)&&o in e},keys(){return l.filter(o=>o in e)}},Ws));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))}},Ws)),i}const n={},a=s.map(()=>({}));for(const r of Object.getOwnPropertyNames(e)){const i=Object.getOwnPropertyDescriptor(e,r),l=!i.get&&!i.set&&i.enumerable&&i.writable&&i.configurable;let o=!1,u=0;for(const d of s)d.includes(r)&&(o=!0,l?a[u][r]=i.value:Object.defineProperty(a[u],r,i)),++u;o||(l?n[r]=i.value:Object.defineProperty(n,r,i))}return[...a,n]}function Ra(e){let s,n;const a=r=>{const i=re.context;if(i){const[o,u]=Ee();re.count||(re.count=0),re.count++,(n||(n=e())).then(d=>{!re.done&&Rt(i),re.count--,u(()=>d.default),Rt()}),s=o}else if(!s){const[o]=ao(()=>(n||(n=e())).then(u=>u.default));s=o}let l;return Ge(()=>(l=s())?ke(()=>{if(!i||re.done)return l(r);const o=re.context;Rt(i);const u=l(r);return Rt(o),u}):"")};return a.preload=()=>n||((n=e()).then(r=>s=()=>r.default),n),a}var So=0;function wo(){return re.context?re.getNextContextId():`cl-${So++}`}var Ua=e=>`Stale read from <${e}>.`;function Eo(e){const s="fallback"in e&&{fallback:()=>e.fallback};return Ge(jo(()=>e.each,e.children,s||void 0))}function No(e){const s="fallback"in e&&{fallback:()=>e.fallback};return Ge(vo(()=>e.each,e.children,s||void 0))}function Co(e){const s=e.keyed,n=Ge(()=>e.when,void 0,{equals:(a,r)=>s?a===r:!a==!r});return Ge(()=>{const a=n();if(a){const r=e.children;return typeof r=="function"&&r.length>0?ke(()=>r(s?a:()=>{if(!ke(n))throw Ua("Show");return e.when})):r}return e.fallback},void 0,void 0)}function Ao(e){let s=!1;const n=(i,l)=>(s?i[1]===l[1]:!i[1]==!l[1])&&i[2]===l[2],a=Ia(()=>e.children),r=Ge(()=>{let i=a();Array.isArray(i)||(i=[i]);for(let l=0;l<i.length;l++){const o=i[l].when;if(o)return s=!!i[l].keyed,[l,o,i[l]]}return[-1]},void 0,{equals:n});return Ge(()=>{const[i,l,o]=r();if(i<0)return e.fallback;const u=o.children;return typeof u=="function"&&u.length>0?ke(()=>u(s?l:()=>{if(ke(r)[0]!==i)throw Ua("Match");return o.when})):u},void 0,void 0)}function To(e){return e}var ko=["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"],Po=new Set(["className","value","readOnly","formNoValidate","isMap","noModule","playsInline",...ko]),_o=new Set(["innerHTML","textContent","innerText","children"]),Io=Object.assign(Object.create(null),{className:"class",htmlFor:"for"}),Lo=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 Do(e,s){const n=Lo[e];return typeof n=="object"?n[s]?n.$:void 0:n}var Bo=new Set(["beforeinput","click","dblclick","contextmenu","focusin","focusout","input","keydown","keyup","mousedown","mousemove","mouseout","mouseover","mouseup","pointerdown","pointermove","pointerout","pointerover","pointerup","touchend","touchmove","touchstart"]),Go=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"]),Mo={xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace"};function Ro(e,s,n){let a=n.length,r=s.length,i=a,l=0,o=0,u=s[r-1].nextSibling,d=null;for(;l<r||o<i;){if(s[l]===n[o]){l++,o++;continue}for(;s[r-1]===n[i-1];)r--,i--;if(r===l){const h=i<a?o?n[o-1].nextSibling:n[i-o]:u;for(;o<i;)e.insertBefore(n[o++],h)}else if(i===o)for(;l<r;)(!d||!d.has(s[l]))&&s[l].remove(),l++;else if(s[l]===n[i-1]&&n[o]===s[r-1]){const h=s[--r].nextSibling;e.insertBefore(n[o++],s[l++].nextSibling),e.insertBefore(n[--i],h),s[r]=n[i]}else{if(!d){d=new Map;let m=o;for(;m<i;)d.set(n[m],m++)}const h=d.get(s[l]);if(h!=null)if(o<h&&h<i){let m=l,b=1,j;for(;++m<r&&m<i&&!((j=d.get(s[m]))==null||j!==h+b);)b++;if(b>h-o){const y=s[l];for(;o<h;)e.insertBefore(n[o++],y)}else e.replaceChild(n[o++],s[l++])}else l++;else s[l++].remove()}}}var qt="_$DX_DELEGATE";function Fa(e,s,n,a={}){let r;return Je(i=>{r=i,s===document?e():Es(s,e(),s.firstChild?null:void 0,n)},a.owner),()=>{r(),s.textContent=""}}function Uo(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 Oa(e,s=window.document){const n=s[qt]||(s[qt]=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,Ka))}}function Fo(e=window.document){if(e[qt]){for(let s of e[qt].keys())e.removeEventListener(s,Ka);delete e[qt]}}function ws(e,s,n){dt(e)||(n==null?e.removeAttribute(s):e.setAttribute(s,n))}function Oo(e,s,n,a){dt(e)||(a==null?e.removeAttributeNS(s,n):e.setAttributeNS(s,n,a))}function qo(e,s,n){dt(e)||(n?e.setAttribute(s,""):e.removeAttribute(s))}function qa(e,s){dt(e)||(s==null?e.removeAttribute("class"):e.className=s)}function $a(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 $o(e,s,n={}){const a=Object.keys(s||{}),r=Object.keys(n);let i,l;for(i=0,l=r.length;i<l;i++){const o=r[i];!o||o==="undefined"||s[o]||(Mn(e,o,!1),delete n[o])}for(i=0,l=a.length;i<l;i++){const o=a[i],u=!!s[o];!o||o==="undefined"||n[o]===u||!u||(Mn(e,o,!0),n[o]=u)}return n}function zo(e,s,n){if(!s)return n?ws(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 za(e,s={},n,a){const r={};return a||Xe(()=>r.children=Vt(e,s.children,r.children)),Xe(()=>typeof s.ref=="function"&&Va(s.ref,e)),Xe(()=>Vo(e,s,n,!0,r,!0)),r}function Va(e,s,n){return ke(()=>e(s,n))}function Es(e,s,n,a){if(n!==void 0&&!a&&(a=[]),typeof s!="function")return Vt(e,s,a,n);Xe(r=>Vt(e,s(),r,n),a)}function Vo(e,s,n,a,r={},i=!1){s||(s={});for(const l in r)if(!(l in s)){if(l==="children")continue;r[l]=Rn(e,l,null,r[l],n,i,s)}for(const l in s){if(l==="children")continue;const o=s[l];r[l]=Rn(e,l,o,r[l],n,i,s)}}function Ko(e){let s,n;return!dt()||!(s=re.registry.get(n=Qo()))?e():(re.completed&&re.completed.add(s),re.registry.delete(n),s)}function dt(e){return!!re.context&&!re.done&&(!e||e.isConnected)}function Ho(e){return e.toLowerCase().replace(/-([a-z])/g,(s,n)=>n.toUpperCase())}function Mn(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 Rn(e,s,n,a,r,i,l){let o,u,d,h,m;if(s==="style")return zo(e,n,a);if(s==="classList")return $o(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(),j=Bo.has(b);if(!j&&a){const y=Array.isArray(a)?a[0]:a;e.removeEventListener(b,y)}(j||n)&&($a(e,b,n,j),j&&Oa([b]))}else if(s.slice(0,5)==="attr:")ws(e,s.slice(5),n);else if(s.slice(0,5)==="bool:")qo(e,s.slice(5),n);else if((m=s.slice(0,5)==="prop:")||(d=_o.has(s))||!r&&((h=Do(s,e.tagName))||(u=Po.has(s)))||(o=e.nodeName.includes("-")||"is"in l)){if(m)s=s.slice(5),u=!0;else if(dt(e))return n;s==="class"||s==="className"?qa(e,n):o&&!u&&!d?e[Ho(s)]=n:e[h||s]=n}else{const b=r&&s.indexOf(":")>-1&&Mo[s.split(":")[0]];b?Oo(e,b,s,n):ws(e,Io[s]||s,n)}return n}function Ka(e){if(re.registry&&re.events&&re.events.find(([u,d])=>d===e))return;let s=e.target;const n=`$$${e.type}`,a=e.target,r=e.currentTarget,i=u=>Object.defineProperty(e,"target",{configurable:!0,value:u}),l=()=>{const u=s[n];if(u&&!s.disabled){const d=s[`${n}Data`];if(d!==void 0?u.call(s,d,e):u.call(s,e),e.cancelBubble)return}return s.host&&typeof s.host!="string"&&!s.host._$host&&s.contains(e.target)&&i(s.host),!0},o=()=>{for(;l()&&(s=s._$host||s.parentNode||s.host););};if(Object.defineProperty(e,"currentTarget",{configurable:!0,get(){return s||document}}),re.registry&&!re.done&&(re.done=_$HY.done=!0),e.composedPath){const u=e.composedPath();i(u[0]);for(let d=0;d<u.length-2&&(s=u[d],!!l());d++){if(s._$host){s=s._$host,o();break}if(s.parentNode===r)break}}else o();i(a)}function Vt(e,s,n,a,r){const i=dt(e);if(i){!n&&(n=[...e.childNodes]);let u=[];for(let d=0;d<n.length;d++){const h=n[d];h.nodeType===8&&h.data.slice(0,2)==="!$"?h.remove():u.push(h)}n=u}for(;typeof n=="function";)n=n();if(s===n)return n;const l=typeof s,o=a!==void 0;if(e=o&&n[0]&&n[0].parentNode||e,l==="string"||l==="number"){if(i||l==="number"&&(s=s.toString(),s===n))return n;if(o){let u=n[0];u&&u.nodeType===3?u.data!==s&&(u.data=s):u=document.createTextNode(s),n=ht(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=ht(e,n,a)}else{if(l==="function")return Xe(()=>{let u=s();for(;typeof u=="function";)u=u();n=Vt(e,u,n,a)}),()=>n;if(Array.isArray(s)){const u=[],d=n&&Array.isArray(n);if(Ys(u,s,n,r))return Xe(()=>n=Vt(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 m=[h];for(;(h=h.nextSibling)!==a;)m.push(h);return n=m}if(u.length===0){if(n=ht(e,n,a),o)return n}else d?n.length===0?Un(e,u,a):Ro(e,n,u):(n&&ht(e),Un(e,u));n=u}else if(s.nodeType){if(i&&s.parentNode)return n=o?[s]:s;if(Array.isArray(n)){if(o)return n=ht(e,n,a,s);ht(e,n,null,s)}else n==null||n===""||!e.firstChild?e.appendChild(s):e.replaceChild(s,e.firstChild);n=s}}return n}function Ys(e,s,n,a){let r=!1;for(let i=0,l=s.length;i<l;i++){let o=s[i],u=n&&n[e.length],d;if(!(o==null||o===!0||o===!1))if((d=typeof o)=="object"&&o.nodeType)e.push(o);else if(Array.isArray(o))r=Ys(e,o,u)||r;else if(d==="function")if(a){for(;typeof o=="function";)o=o();r=Ys(e,Array.isArray(o)?o:[o],Array.isArray(u)?u:[u])||r}else e.push(o),r=!0;else{const h=String(o);u&&u.nodeType===3&&u.data===h?e.push(u):e.push(document.createTextNode(h))}}return r}function Un(e,s,n=null){for(let a=0,r=s.length;a<r;a++)e.insertBefore(s[a],n)}function ht(e,s,n,a){if(n===void 0)return e.textContent="";const r=a||document.createTextNode("");if(s.length){let i=!1;for(let l=s.length-1;l>=0;l--){const o=s[l];if(r!==o){const u=o.parentNode===e;!i&&!l?u?e.replaceChild(r,o):e.insertBefore(r,n):u&&o.remove()}else i=!0}}else e.insertBefore(r,n);return[r]}function Qo(){return re.getNextContextId()}var Wo="http://www.w3.org/2000/svg";function Ha(e,s=!1){return s?document.createElementNS(Wo,e):document.createElement(e)}function Yo(e){const{useShadow:s}=e,n=document.createTextNode(""),a=()=>e.mount||document.body,r=Gn();let i,l=!!re.context;return vn(()=>{l&&(Gn().user=l=!1),i||(i=lo(r,()=>Ge(()=>e.children)));const o=a();if(o instanceof HTMLHeadElement){const[u,d]=Ee(!1),h=()=>d(!0);Je(m=>Es(o,()=>u()?m():i(),null)),kt(h)}else{const u=Ha(e.isSVG?"g":"div",e.isSVG),d=s&&u.attachShadow?u.attachShadow({mode:"open"}):u;Object.defineProperty(u,"_$host",{get(){return n.parentNode},configurable:!0}),Es(d,i),o.appendChild(u),e.ref&&e.ref(u),kt(()=>o.removeChild(u))}},void 0,{render:!l}),n}function Jo(e){const[s,n]=Ma(e,["component"]),a=Ge(()=>s.component);return Ge(()=>{const r=a();switch(typeof r){case"function":return ke(()=>r(n));case"string":const i=Go.has(r),l=re.context?Ko():Ha(r,i);return za(l,n,i),l}})}var Xo=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()}},Qa=class{constructor(e){this.generateIdentifier=e,this.kv=new Xo}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)}},Zo=class extends Qa{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 ec(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 tc(e,s){const n=ec(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 Pt(e,s){Object.entries(e).forEach(([n,a])=>s(a,n))}function fs(e,s){return e.indexOf(s)!==-1}function Fn(e,s){for(let n=0;n<e.length;n++){const a=e[n];if(s(a))return a}}var sc=class{constructor(){this.transfomers={}}register(e){this.transfomers[e.name]=e}findApplicable(e){return tc(this.transfomers,s=>s.isApplicable(e))}findByName(e){return this.transfomers[e]}},nc=e=>Object.prototype.toString.call(e).slice(8,-1),Wa=e=>typeof e>"u",ac=e=>e===null,Kt=e=>typeof e!="object"||e===null||e===Object.prototype?!1:Object.getPrototypeOf(e)===null?!0:Object.getPrototypeOf(e)===Object.prototype,Js=e=>Kt(e)&&Object.keys(e).length===0,et=e=>Array.isArray(e),rc=e=>typeof e=="string",ic=e=>typeof e=="number"&&!isNaN(e),lc=e=>typeof e=="boolean",oc=e=>e instanceof RegExp,Ht=e=>e instanceof Map,Qt=e=>e instanceof Set,Ya=e=>nc(e)==="Symbol",cc=e=>e instanceof Date&&!isNaN(e.valueOf()),uc=e=>e instanceof Error,On=e=>typeof e=="number"&&isNaN(e),dc=e=>lc(e)||ac(e)||Wa(e)||ic(e)||rc(e)||Ya(e),hc=e=>typeof e=="bigint",mc=e=>e===1/0||e===-1/0,fc=e=>ArrayBuffer.isView(e)&&!(e instanceof DataView),gc=e=>e instanceof URL,Ja=e=>e.replace(/\./g,"\\."),Os=e=>e.map(String).map(Ja).join("."),$t=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 $e(e,s,n,a){return{isApplicable:e,annotation:s,transform:n,untransform:a}}var Xa=[$e(Wa,"undefined",()=>null,()=>{}),$e(hc,"bigint",e=>e.toString(),e=>typeof BigInt<"u"?BigInt(e):e),$e(cc,"Date",e=>e.toISOString(),e=>new Date(e)),$e(uc,"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}),$e(oc,"regexp",e=>""+e,e=>{const s=e.slice(1,e.lastIndexOf("/")),n=e.slice(e.lastIndexOf("/")+1);return new RegExp(s,n)}),$e(Qt,"set",e=>[...e.values()],e=>new Set(e)),$e(Ht,"map",e=>[...e.entries()],e=>new Map(e)),$e(e=>On(e)||mc(e),"number",e=>On(e)?"NaN":e>0?"Infinity":"-Infinity",Number),$e(e=>e===0&&1/e===-1/0,"number",()=>"-0",Number),$e(gc,"URL",e=>e.toString(),e=>new URL(e))];function Is(e,s,n,a){return{isApplicable:e,annotation:s,transform:n,untransform:a}}var Za=Is((e,s)=>Ya(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}),xc=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,Uint8ClampedArray].reduce((e,s)=>(e[s.name]=s,e),{}),er=Is(fc,e=>["typed-array",e.constructor.name],e=>[...e],(e,s)=>{const n=xc[s[1]];if(!n)throw new Error("Trying to deserialize unknown typed array");return new n(e)});function tr(e,s){return e!=null&&e.constructor?!!s.classRegistry.getIdentifier(e.constructor):!1}var sr=Is(tr,(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)}),nr=Is((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)}),pc=[sr,Za,nr,er],qn=(e,s)=>{const n=Fn(pc,r=>r.isApplicable(e,s));if(n)return{value:n.transform(e,s),type:n.annotation(e,s)};const a=Fn(Xa,r=>r.isApplicable(e,s));if(a)return{value:a.transform(e,s),type:a.annotation}},ar={};Xa.forEach(e=>{ar[e.annotation]=e});var yc=(e,s,n)=>{if(et(s))switch(s[0]){case"symbol":return Za.untransform(e,s,n);case"class":return sr.untransform(e,s,n);case"custom":return nr.untransform(e,s,n);case"typed-array":return er.untransform(e,s,n);default:throw new Error("Unknown transformation: "+s)}else{const a=ar[s];if(!a)throw new Error("Unknown transformation: "+s);return a.untransform(e,n)}},mt=(e,s)=>{const n=e.keys();for(;s>0;)n.next(),s--;return n.next().value};function rr(e){if(fs(e,"__proto__"))throw new Error("__proto__ is not allowed as a property");if(fs(e,"prototype"))throw new Error("prototype is not allowed as a property");if(fs(e,"constructor"))throw new Error("constructor is not allowed as a property")}var jc=(e,s)=>{rr(s);for(let n=0;n<s.length;n++){const a=s[n];if(Qt(e))e=mt(e,+a);else if(Ht(e)){const r=+a,i=+s[++n]==0?"key":"value",l=mt(e,r);switch(i){case"key":e=l;break;case"value":e=e.get(l);break}}else e=e[a]}return e},Xs=(e,s,n)=>{if(rr(s),s.length===0)return n(e);let a=e;for(let i=0;i<s.length-1;i++){const l=s[i];if(et(a)){const o=+l;a=a[o]}else if(Kt(a))a=a[l];else if(Qt(a)){const o=+l;a=mt(a,o)}else if(Ht(a)){if(i===s.length-2)break;const u=+l,d=+s[++i]==0?"key":"value",h=mt(a,u);switch(d){case"key":a=h;break;case"value":a=a.get(h);break}}}const r=s[s.length-1];if(et(a)?a[+r]=n(a[+r]):Kt(a)&&(a[r]=n(a[r])),Qt(a)){const i=mt(a,+r),l=n(i);i!==l&&(a.delete(i),a.add(l))}if(Ht(a)){const i=+s[s.length-2],l=mt(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 Zs(e,s,n=[]){if(!e)return;if(!et(e)){Pt(e,(i,l)=>Zs(i,s,[...n,...$t(l)]));return}const[a,r]=e;r&&Pt(r,(i,l)=>{Zs(i,s,[...n,...$t(l)])}),s(a,n)}function vc(e,s,n){return Zs(s,(a,r)=>{e=Xs(e,r,i=>yc(i,a,n))}),e}function bc(e,s){function n(a,r){const i=jc(e,$t(r));a.map($t).forEach(l=>{e=Xs(e,l,()=>i)})}if(et(s)){const[a,r]=s;a.forEach(i=>{e=Xs(e,$t(i),()=>e)}),r&&Pt(r,n)}else Pt(s,n);return e}var Sc=(e,s)=>Kt(e)||et(e)||Ht(e)||Qt(e)||tr(e,s);function wc(e,s,n){const a=n.get(e);a?a.push(s):n.set(e,[s])}function Ec(e,s){const n={};let a;return e.forEach(r=>{if(r.length<=1)return;s||(r=r.map(o=>o.map(String)).sort((o,u)=>o.length-u.length));const[i,...l]=r;i.length===0?a=l.map(Os):n[Os(i)]=l.map(Os)}),a?Js(n)?[a]:[a,n]:Js(n)?void 0:n}var ir=(e,s,n,a,r=[],i=[],l=new Map)=>{const o=dc(e);if(!o){wc(e,r,s);const j=l.get(e);if(j)return a?{transformedValue:null}:j}if(!Sc(e,n)){const j=qn(e,n),y=j?{transformedValue:j.value,annotations:[j.type]}:{transformedValue:e};return o||l.set(e,y),y}if(fs(i,e))return{transformedValue:null};const u=qn(e,n),d=(u==null?void 0:u.value)??e,h=et(d)?[]:{},m={};Pt(d,(j,y)=>{if(y==="__proto__"||y==="constructor"||y==="prototype")throw new Error(`Detected property ${y}. This is a prototype pollution risk, please remove it from your object.`);const p=ir(j,s,n,a,[...r,y],[...i,e],l);h[y]=p.transformedValue,et(p.annotations)?m[y]=p.annotations:Kt(p.annotations)&&Pt(p.annotations,(v,S)=>{m[Ja(y)+"."+S]=v})});const b=Js(m)?{transformedValue:h,annotations:u?[u.type]:void 0}:{transformedValue:h,annotations:u?[u.type,m]:m};return o||l.set(e,b),b};function lr(e){return Object.prototype.toString.call(e).slice(8,-1)}function $n(e){return lr(e)==="Array"}function Nc(e){if(lr(e)!=="Object")return!1;const s=Object.getPrototypeOf(e);return!!s&&s.constructor===Object&&s===Object.prototype}function Cc(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 en(e,s={}){if($n(e))return e.map(r=>en(r,s));if(!Nc(e))return e;const n=Object.getOwnPropertyNames(e),a=Object.getOwnPropertySymbols(e);return[...n,...a].reduce((r,i)=>{if($n(s.props)&&!s.props.includes(i))return r;const l=e[i],o=en(l,s);return Cc(r,i,o,e,s.nonenumerable),r},{})}var je=class{constructor({dedupe:e=!1}={}){this.classRegistry=new Zo,this.symbolRegistry=new Qa(s=>s.description??""),this.customTransformerRegistry=new sc,this.allowedErrorProps=[],this.dedupe=e}serialize(e){const s=new Map,n=ir(e,s,this,this.dedupe),a={json:n.transformedValue};n.annotations&&(a.meta={...a.meta,values:n.annotations});const r=Ec(s,this.dedupe);return r&&(a.meta={...a.meta,referentialEqualities:r}),a}deserialize(e){const{json:s,meta:n}=e;let a=en(s);return n!=null&&n.values&&(a=vc(a,n.values,this)),n!=null&&n.referentialEqualities&&(a=bc(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)}};je.defaultInstance=new je;je.serialize=je.defaultInstance.serialize.bind(je.defaultInstance);je.deserialize=je.defaultInstance.deserialize.bind(je.defaultInstance);je.stringify=je.defaultInstance.stringify.bind(je.defaultInstance);je.parse=je.defaultInstance.parse.bind(je.defaultInstance);je.registerClass=je.defaultInstance.registerClass.bind(je.defaultInstance);je.registerSymbol=je.defaultInstance.registerSymbol.bind(je.defaultInstance);je.registerCustom=je.defaultInstance.registerCustom.bind(je.defaultInstance);je.allowErrorProps=je.defaultInstance.allowErrorProps.bind(je.defaultInstance);var or=je.serialize,Ac=je.stringify;function Tc(e){return e.state.fetchStatus==="fetching"?"fetching":e.getObserversCount()?e.state.fetchStatus==="paused"?"paused":e.isStale()?"stale":"fresh":"inactive"}function kc(e,s){return`${e}${s.charAt(0).toUpperCase()+s.slice(1)}`}function Pc({queryState:e,observerCount:s,isStale:n}){return e.fetchStatus==="fetching"?"blue":s?e.fetchStatus==="paused"?"purple":n?"yellow":"green":"gray"}function _c({status:e,isPaused:s}){return s?"purple":e==="error"?"red":e==="pending"?"yellow":e==="success"?"green":"gray"}function Ic(e){return e==="fresh"?"green":e==="stale"?"yellow":e==="paused"?"purple":e==="inactive"?"gray":"blue"}var Lc=(e,s=!1)=>{const{json:n}=or(e);return JSON.stringify(n,null,s?2:void 0)},ds=e=>e.state.fetchStatus!=="idle"?0:e.getObserversCount()?e.isStale()?2:1:3,Dc=(e,s)=>e.queryHash.localeCompare(s.queryHash),cr=(e,s)=>e.state.dataUpdatedAt<s.state.dataUpdatedAt?1:-1,Bc=(e,s)=>ds(e)===ds(s)?cr(e,s):ds(e)>ds(s)?1:-1,Gc={status:Bc,"query hash":Dc,"last updated":cr},hs=e=>e.state.isPaused?0:e.state.status==="error"?2:e.state.status==="pending"?1:3,ur=(e,s)=>e.state.submittedAt<s.state.submittedAt?1:-1,Mc=(e,s)=>hs(e)===hs(s)?ur(e,s):hs(e)>hs(s)?1:-1,Rc={status:Mc,"last updated":ur},Uc=e=>e*parseFloat(getComputedStyle(document.documentElement).fontSize),Fc=()=>{const[e,s]=Ee("dark");return _a(()=>{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),kt(()=>n.removeEventListener("change",a))}),e},Ut=(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,Ut(a.get(r),i,n)),a}if(e instanceof Set){const a=Ut(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]=Ut(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]=Ut(a[r],i,n),a}return e},Ft=(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,Ft(n.get(a),r)),n}if(e instanceof Set){const n=Ft(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]=Ft(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]=Ft(n[a],r),n}return e},dr=(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)},ft,Wt,Yt,Jt,rt,Xt,gt,xt,pt,yt,jt,vt,Zt,Kn,Oc=(Kn=class{constructor(e){pe(this,ft);pe(this,Wt);pe(this,Yt);pe(this,Jt);pe(this,rt,!1);pe(this,Xt);pe(this,gt);pe(this,xt);pe(this,pt);pe(this,yt);pe(this,jt);pe(this,vt);pe(this,Zt);const{client:s,queryFlavor:n,version:a,onlineManager:r,buttonPosition:i,position:l,initialIsOpen:o,errorTypes:u,styleNonce:d,shadowDOMTarget:h}=e;xe(this,ft,Ee(s)),xe(this,Yt,n),xe(this,Jt,a),xe(this,Wt,r),xe(this,Xt,d),xe(this,gt,h),xe(this,xt,Ee(i)),xe(this,pt,Ee(l)),xe(this,yt,Ee(o)),xe(this,jt,Ee(u))}setButtonPosition(e){ae(this,xt)[1](e)}setPosition(e){ae(this,pt)[1](e)}setInitialIsOpen(e){ae(this,yt)[1](e)}setErrorTypes(e){ae(this,jt)[1](e)}setClient(e){ae(this,ft)[1](e)}mount(e){if(ae(this,rt))throw new Error("Devtools is already mounted");const s=Fa(()=>{const n=this,[a]=ae(this,xt),[r]=ae(this,pt),[i]=ae(this,yt),[l]=ae(this,jt),[o]=ae(this,ft);let u;return ae(this,vt)?u=ae(this,vt):(u=Ra(()=>Promise.resolve().then(()=>require("./HO4MOOFI-GxkFnTET.cjs"))),xe(this,vt,u)),dr(ae(this,Xt),ae(this,gt)),Sn(u,wn({get queryFlavor(){return ae(n,Yt)},get version(){return ae(n,Jt)},get onlineManager(){return ae(n,Wt)},get shadowDOMTarget(){return ae(n,gt)}},{get client(){return o()},get buttonPosition(){return a()},get position(){return r()},get initialIsOpen(){return i()},get errorTypes(){return l()}}))},e);xe(this,rt,!0),xe(this,Zt,s)}unmount(){var e;if(!ae(this,rt))throw new Error("Devtools is not mounted");(e=ae(this,Zt))==null||e.call(this),xe(this,rt,!1)}},ft=new WeakMap,Wt=new WeakMap,Yt=new WeakMap,Jt=new WeakMap,rt=new WeakMap,Xt=new WeakMap,gt=new WeakMap,xt=new WeakMap,pt=new WeakMap,yt=new WeakMap,jt=new WeakMap,vt=new WeakMap,Zt=new WeakMap,Kn),bt,es,ts,ss,it,ns,St,wt,Et,Nt,Ct,At,Tt,as,Hn,qc=(Hn=class{constructor(e){pe(this,bt);pe(this,es);pe(this,ts);pe(this,ss);pe(this,it,!1);pe(this,ns);pe(this,St);pe(this,wt);pe(this,Et);pe(this,Nt);pe(this,Ct);pe(this,At);pe(this,Tt);pe(this,as);const{client:s,queryFlavor:n,version:a,onlineManager:r,buttonPosition:i,position:l,initialIsOpen:o,errorTypes:u,styleNonce:d,shadowDOMTarget:h,onClose:m}=e;xe(this,bt,Ee(s)),xe(this,ts,n),xe(this,ss,a),xe(this,es,r),xe(this,ns,d),xe(this,St,h),xe(this,wt,Ee(i)),xe(this,Et,Ee(l)),xe(this,Nt,Ee(o)),xe(this,Ct,Ee(u)),xe(this,At,Ee(m))}setButtonPosition(e){ae(this,wt)[1](e)}setPosition(e){ae(this,Et)[1](e)}setInitialIsOpen(e){ae(this,Nt)[1](e)}setErrorTypes(e){ae(this,Ct)[1](e)}setClient(e){ae(this,bt)[1](e)}setOnClose(e){ae(this,At)[1](()=>e)}mount(e){if(ae(this,it))throw new Error("Devtools is already mounted");const s=Fa(()=>{const n=this,[a]=ae(this,wt),[r]=ae(this,Et),[i]=ae(this,Nt),[l]=ae(this,Ct),[o]=ae(this,bt),[u]=ae(this,At);let d;return ae(this,Tt)?d=ae(this,Tt):(d=Ra(()=>Promise.resolve().then(()=>require("./HUY7CZI3-D0BzeL1O.cjs"))),xe(this,Tt,d)),dr(ae(this,ns),ae(this,St)),Sn(d,wn({get queryFlavor(){return ae(n,ts)},get version(){return ae(n,ss)},get onlineManager(){return ae(n,es)},get shadowDOMTarget(){return ae(n,St)}},{get client(){return o()},get buttonPosition(){return a()},get position(){return r()},get initialIsOpen(){return i()},get errorTypes(){return l()},get onClose(){return u()}}))},e);xe(this,it,!0),xe(this,as,s)}unmount(){var e;if(!ae(this,it))throw new Error("Devtools is not mounted");(e=ae(this,as))==null||e.call(this),xe(this,it,!1)}},bt=new WeakMap,es=new WeakMap,ts=new WeakMap,ss=new WeakMap,it=new WeakMap,ns=new WeakMap,St=new WeakMap,wt=new WeakMap,Et=new WeakMap,Nt=new WeakMap,Ct=new WeakMap,At=new WeakMap,Tt=new WeakMap,as=new WeakMap,Hn);function $c(e){const s=R.useQueryClient(e.client),n=Se.useRef(null),{buttonPosition:a,position:r,initialIsOpen:i,errorTypes:l,styleNonce:o,shadowDOMTarget:u}=e,[d]=Se.useState(new Oc({client:s,queryFlavor:"React Query",version:"5",onlineManager:R.onlineManager,buttonPosition:a,position:r,initialIsOpen:i,errorTypes:l,styleNonce:o,shadowDOMTarget:u}));return Se.useEffect(()=>{d.setClient(s)},[s,d]),Se.useEffect(()=>{a&&d.setButtonPosition(a)},[a,d]),Se.useEffect(()=>{r&&d.setPosition(r)},[r,d]),Se.useEffect(()=>{d.setInitialIsOpen(i||!1)},[i,d]),Se.useEffect(()=>{d.setErrorTypes(l||[])},[l,d]),Se.useEffect(()=>(n.current&&d.mount(n.current),()=>{d.unmount()}),[d]),t.jsx("div",{className:"tsqd-parent-container",ref:n})}function zc(e){const s=R.useQueryClient(e.client),n=Se.useRef(null),{errorTypes:a,styleNonce:r,shadowDOMTarget:i}=e,[l]=Se.useState(new qc({client:s,queryFlavor:"React Query",version:"5",onlineManager:R.onlineManager,buttonPosition:"bottom-left",position:"bottom",initialIsOpen:!0,errorTypes:a,styleNonce:r,shadowDOMTarget:i,onClose:e.onClose}));return Se.useEffect(()=>{l.setClient(s)},[s,l]),Se.useEffect(()=>{l.setOnClose(e.onClose??(()=>{}))},[e.onClose,l]),Se.useEffect(()=>{l.setErrorTypes(a||[])},[a,l]),Se.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 Vc=process.env.NODE_ENV!=="development"?function(){return null}:$c;process.env.NODE_ENV;const hr=()=>t.jsx("div",{className:"absolute inset-0 z-50 flex h-screen w-screen items-center justify-center bg-white/20",children:t.jsx("div",{className:"flex size-10 items-center justify-center rounded-full bg-white",children:t.jsx(w.Loader2,{className:"size-5 animate-spin"})})}),Kc=()=>{F.registerChaiFeatureFlag("dynamic-page-selector",{description:"Dynamic page selector"}),F.registerChaiFeatureFlag("realtime-page-lock",{description:"Realtime page lock"}),F.registerChaiFeatureFlag("enable-add-page-dropdown",{description:"Enable add page dropdown"}),F.registerChaiFeatureFlag("enable-page-revisions-compare",{description:"Page revisions compare"}),F.registerChaiFeatureFlag("enable-page-manager-v2",{description:"Page manager v2"}),F.registerChaiFeatureFlag("enable-site-settings",{description:"Site settings"})},Hc=()=>{const e=oe(),s=ee();return R.useQuery({queryKey:[W,I.GET_COLLECTIONS],initialData:[],queryFn:async()=>s(e,{action:I.GET_COLLECTIONS})})},Qc=()=>{const{data:e}=Pe(),{data:s}=tt(),{data:n}=He(),a=oe(),r=ee(),i=g.useMemo(()=>(n==null?void 0:n.fallbackLang)||"en",[n==null?void 0:n.fallbackLang]);return R.useMutation({mutationFn:async({block:l})=>r(a,{action:I.GET_BLOCK_ASYNC_PROPS,data:{block:l,lang:(s==null?void 0:s.lang)||i,pageProps:{slug:s==null?void 0:s.slug,searchParams:{},pageType:s==null?void 0:s.pageType,fallbackLang:i,lastSaved:s.lastSaved,pageId:e.id,primaryPageId:s.primaryPage||e.id,pageBaseSlug:s==null?void 0:s.slug,dynamic:e==null?void 0:e.dynamic,languagePageId:s.id}}})})},mr=()=>{const e=dn();return g.useCallback(({pageId:s})=>{e(s)},[e])},Wc=60*5;function Yc(){const{user:e,setUser:s,logout:n,isLoggedIn:a,isSessionExpired:r}=Ue(),i=Cs(),l=g.useRef(null),o=qe("getAccessToken",!1),u=g.useCallback(async()=>{if(o===!1&&!(!f.has(e,"expiresAt")||!f.has(e,"accessToken")||!f.has(e,"refreshToken")))try{const d=await tn(i,{action:"REFRESH_TOKEN",data:{refreshToken:e.refreshToken,accessToken:e.accessToken}});if(!d.ok){n();return}const h=await d.json();f.has(h,"id")&&f.has(h,"email")&&f.has(h,"accessToken")&&f.has(h,"refreshToken")?s(h):n()}catch{n()}},[e,n,s,i,o]);return g.useEffect(()=>{a&&r&&u()},[r,a,u]),g.useEffect(()=>{if(!a||!f.has(e,"expiresAt")||!f.has(e,"refreshToken")||!f.has(e,"accessToken")){l.current&&(clearInterval(l.current),l.current=null);return}return l.current||(l.current=setInterval(()=>{if(!f.has(e,"expiresAt")||!f.has(e,"refreshToken")||!f.has(e,"accessToken"))return;const d=Math.floor(Date.now()/1e3),h=e.expiresAt-d;h<Wc&&h>0&&u()},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,o]),null}const Jc=({isActive:e,onClick:s})=>t.jsx(c.Button,{variant:e?"default":"ghost",className:"w-full justify-start text-left",onClick:s,children:"General"}),Xc=()=>{const[e,s]=g.useState({siteName:"",siteTagline:"",siteDescription:"",siteURL:"",language:"",timezone:""}),[n,a]=g.useState(!1),r=o=>{const{name:u,value:d}=o.target;s(h=>({...h,[u]:d}))},i=()=>{a(!0),setTimeout(()=>{a(!1),console.log("Form submitted:",e)},1e3)},l=e.siteName.trim()!=="";return t.jsxs("div",{className:"space-y-4",children:[t.jsx("h2",{className:"text-lg font-medium",children:"General Settings"}),t.jsxs("div",{className:"border rounded p-4 space-y-3",children:[t.jsxs("div",{children:[t.jsx("label",{className:"text-sm font-medium block mb-1",children:"Site Name"}),t.jsx("input",{type:"text",name:"siteName",value:e.siteName,onChange:r,className:"w-full border rounded px-3 py-2 text-sm",placeholder:"Enter site name"})]}),t.jsxs("div",{children:[t.jsx("label",{className:"text-sm font-medium block mb-1",children:"Site Tagline"}),t.jsx("input",{type:"text",name:"siteTagline",value:e.siteTagline,onChange:r,className:"w-full border rounded px-3 py-2 text-sm",placeholder:"Enter site tagline"})]}),t.jsxs("div",{children:[t.jsx("label",{className:"text-sm font-medium block mb-1",children:"Site URL"}),t.jsx("input",{type:"url",name:"siteURL",value:e.siteURL,onChange:r,className:"w-full border rounded px-3 py-2 text-sm",placeholder:"https://example.com"})]}),t.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[t.jsxs("div",{children:[t.jsx("label",{className:"text-sm font-medium block mb-1",children:"Language"}),t.jsxs("select",{name:"language",value:e.language,onChange:r,className:"w-full border rounded px-3 py-2 text-sm",children:[t.jsx("option",{value:"",children:"Select language"}),t.jsx("option",{value:"en",children:"English"}),t.jsx("option",{value:"es",children:"Spanish"}),t.jsx("option",{value:"fr",children:"French"}),t.jsx("option",{value:"de",children:"German"}),t.jsx("option",{value:"hi",children:"Hindi"})]})]}),t.jsxs("div",{children:[t.jsx("label",{className:"text-sm font-medium block mb-1",children:"Timezone"}),t.jsxs("select",{name:"timezone",value:e.timezone,onChange:r,className:"w-full border rounded px-3 py-2 text-sm",children:[t.jsx("option",{value:"",children:"Select timezone"}),t.jsx("option",{value:"UTC",children:"UTC"}),t.jsx("option",{value:"America/New_York",children:"Eastern Time (US & Canada)"}),t.jsx("option",{value:"America/Chicago",children:"Central Time (US & Canada)"}),t.jsx("option",{value:"America/Denver",children:"Mountain Time (US & Canada)"}),t.jsx("option",{value:"America/Los_Angeles",children:"Pacific Time (US & Canada)"}),t.jsx("option",{value:"Asia/Kolkata",children:"India Standard Time"}),t.jsx("option",{value:"Europe/London",children:"GMT (London)"})]})]})]}),t.jsxs("div",{children:[t.jsx("label",{className:"text-sm font-medium block mb-1",children:"Site Description"}),t.jsx("textarea",{name:"siteDescription",value:e.siteDescription,onChange:r,className:"w-full border rounded px-3 py-2 text-sm",placeholder:"Enter site description",rows:3})]}),t.jsx("div",{className:"pt-3",children:t.jsx(c.Button,{onClick:i,disabled:!l||n,className:"w-full",children:n?"Saving...":"Save Settings"})})]})]})},Zc=()=>{const e=rs(),s=R.useQueryClient(),n=ee();return R.useMutation({mutationFn:async({file:a,folderId:r,name:i,optimize:l=!0})=>n(e,{action:I.UPLOAD_ASSET,data:{file:a,folderId:r,name:i,optimize:l}}),onSuccess:a=>{if(a!=null&&a.error)throw new Error(a==null?void 0:a.error);s.invalidateQueries({queryKey:[W,I.GET_ASSETS]}),J.toast.success("Asset uploaded successfully")},onError:()=>{J.toast.error("Failed to upload asset")}})},eu=()=>{const e=rs(),s=R.useQueryClient(),n=ee();return R.useMutation({mutationFn:async a=>n(e,{action:I.DELETE_ASSET,data:{id:a}}),onSuccess:a=>{if(a!=null&&a.error)throw new Error(a==null?void 0:a.error);s.invalidateQueries({queryKey:[W,I.GET_ASSETS]}),J.toast.success("Asset deleted successfully")},onError:()=>{J.toast.error("Failed to delete asset")}})},tu=()=>{const e=rs(),s=R.useQueryClient(),n=ee();return R.useMutation({mutationFn:async a=>n(e,{action:I.UPDATE_ASSET,data:a}),onSuccess:a=>{if(a!=null&&a.error)throw new Error(a==null?void 0:a.error);s.invalidateQueries({queryKey:[W,I.GET_ASSETS]}),J.toast.success("Asset updated successfully")},onError:()=>{J.toast.error("Failed to update asset")}})},su=(e={})=>{const s=rs(),n=ee(),{search:a,page:r=1,limit:i=30}=e;return R.useQuery({queryKey:[W,I.GET_ASSETS,a,r,i],queryFn:async()=>{const l=await n(s,{action:I.GET_ASSETS,data:{search:a,page:r,limit:i}});return l.page=r,l.limit=i,l},staleTime:1e3*60*5,retry:1})},nu=e=>{const s=rs(),n=ee();return R.useQuery({queryKey:[W,I.GET_ASSET,e],queryFn:async()=>e?await n(s,{action:I.GET_ASSET,data:{id:e}}):null,staleTime:1e3*60*5,retry:1})};function au(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 zn(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 Vn(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 ru=({assetId:e,onBack:s,onEdit:n,onSave:a,isSaving:r})=>{var m,b,j;const{data:i,isLoading:l,isError:o}=nu(e||""),[u,d]=g.useState(""),h=async(y,p)=>{try{await navigator.clipboard.writeText(y),J.toast.success(`${p} copied to clipboard`)}catch(v){J.toast.error(`Failed to copy ${p}`,{description:v==null?void 0:v.message})}};return g.useEffect(()=>{i!=null&&i.description&&d(i.description)},[i]),l?t.jsx("div",{className:"flex-1 flex items-center justify-center",children:t.jsx(w.Loader,{className:"h-8 w-8 animate-spin"})}):o||!(i!=null&&i.id)?t.jsx("div",{className:"flex-1 flex items-center justify-center",children:t.jsxs("div",{className:"text-center max-w-md mx-auto p-6",children:[t.jsx("div",{className:"flex justify-center mb-4",children:t.jsx(w.AlertCircle,{className:"h-12 w-12 text-gray-400"})}),t.jsx("h3",{className:"text-lg font-medium text-gray-900 mb-2",children:"No Asset Found"}),t.jsx("p",{className:"text-sm text-gray-500 mb-6",children:o?"There was an error loading the asset. Please try again later.":"The asset you're looking for doesn't exist or has been removed."}),t.jsxs("div",{className:"flex justify-center gap-4",children:[t.jsx(c.Button,{variant:"outline",onClick:s,children:"Back to Assets"}),o&&t.jsx(c.Button,{variant:"default",onClick:()=>window.location.reload(),children:"Try Again"})]})]})}):t.jsxs("div",{className:"flex-1 flex flex-col gap-y-4 overflow-hidden",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsxs(c.Button,{variant:"outline",size:"sm",onClick:s,disabled:r,children:[t.jsx(w.ChevronLeft,{className:"h-4 w-4"}),"Back to Assets"]}),t.jsxs("div",{className:"flex gap-2",children:[t.jsx(c.Button,{variant:"outline",onClick:s,disabled:r,children:"Cancel"}),t.jsxs(c.Button,{variant:"outline",onClick:()=>h(i.url,"Asset URL"),disabled:r,children:[t.jsx(w.Copy,{className:"h-4 w-4 mr-2"}),"Copy URL"]}),t.jsxs(c.Button,{variant:"default",onClick:()=>n(i),disabled:r,children:[t.jsx(w.Pencil,{className:"h-4 w-4"}),"Edit Image"]})]})]}),t.jsxs("div",{className:"grid grid-cols-2 items-start gap-6 flex-1 overflow-hidden",children:[t.jsx("div",{className:"relative h-[calc(80vh-200px)] w-full flex items-start justify-center",children:t.jsx("img",{src:`${i.url}?v=${((m=i.metadata)==null?void 0:m.updatedAt)||i.createdAt}`,alt:i.name,className:"w-full h-full object-contain rounded-lg max-h-max max-w-max"})}),t.jsxs("div",{className:"space-y-6",children:[t.jsxs("div",{className:"grid gap-3 border rounded-md pt-2 bg-gray-100",children:[t.jsx(c.Label,{className:"w-full text-center",children:"Details"}),t.jsx("div",{className:"grid grid-cols-1 gap-2 text-sm border rounded-md p-2 bg-white",children:[{label:"File Name",value:i.name},{label:"Type",value:i.type,capitalize:!0},{label:"Format",value:((b=i.metadata)==null?void 0:b.format)||i.type,capitalize:!0},{label:"Size",value:au(i.size)},{label:"Dimensions",value:`${i.width||0} × ${i.height||0}`},{label:"Created",value:zn(i.createdAt)},{label:"Updated",value:zn(((j=i.metadata)==null?void 0:j.updatedAt)||i.createdAt)},{label:"URL",value:i.url,copyable:!0}].map(y=>t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(c.Label,{className:"w-max text-left px-2 w-1/4 font-normal text-gray-700",children:y.label}),":",t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("div",{className:"w-max text-left font-medium text-gray-900"+(y.capitalize?" capitalize":""),children:y.value}),y.copyable&&t.jsx(c.Button,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>h(y.value,y.label),children:t.jsx(w.Link,{className:"h-3 w-3"})})]})]},y.label))})]}),i.usedOn&&i.usedOn.length>0&&t.jsxs("div",{className:"grid gap-3",children:[t.jsx(c.Label,{children:"Used On"}),t.jsx("div",{className:"grid grid-cols-1 gap-2 text-sm border rounded-md p-2",children:i.usedOn.map((y,p)=>t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("div",{className:"w-max text-left font-medium text-gray-900",children:y.name}),t.jsxs("div",{className:"text-gray-500",children:["(",y.slug,")"]})]},p))})]}),t.jsxs("div",{className:"grid gap-3 border rounded-md pt-2 bg-gray-100 relative",children:[t.jsx(c.Label,{className:"w-full text-center",children:"Description"}),t.jsx(c.Textarea,{id:"description",value:u,placeholder:"Enter a description for the asset",onChange:y=>d(y.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||!Vn(u,i),className:`py-0 bg-blue-500 text-white px-3 py-0.5 rounded-md text-sm ${r||!Vn(u,i)?"opacity-50 cursor-not-allowed":""}`,children:r?t.jsxs(t.Fragment,{children:[t.jsx(w.Loader,{className:"h-4 w-4 mr-2 animate-spin"}),"Saving..."]}):"Save"})})]})]})]})]})},iu=g.lazy(()=>Promise.resolve().then(()=>require("./image-editor-BWLJT1mr.cjs")));function lu(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 ou=({isUpdatingAsset:e,allowedTypes:s,maxFileSize:n,uploadAsset:a,isUploadingAsset:r,onUploaded:i})=>{const[l,o]=g.useState(()=>{const j=localStorage.getItem("chai_optimize_images");return j!==null?j==="true":!0});g.useEffect(()=>{localStorage.setItem("chai_optimize_images",l.toString())},[l]);const u=e||r,d=g.useCallback(async j=>new Promise((y,p)=>{const v=j[0],S=new FileReader;S.readAsDataURL(v),S.onload=async()=>{a({file:S.result,folderId:void 0,name:v.name,optimize:l},{onSuccess:C=>{i&&i(C),y(C)},onError:C=>{p(C)}})},S.onerror=C=>p(C)}),[a,l,i]),{getRootProps:h,getInputProps:m,isDragActive:b}=jr.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:F.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",{...m()}),u?t.jsx("div",{className:"flex flex-col items-center px-6",children:t.jsxs("div",{className:"leading-tight flex items-center justify-center gap-2",children:[t.jsx("div",{className:"flex items-center justify-center rounded-full bg-indigo-100 p-2",children:t.jsx(w.Loader,{className:"h-4 w-4 text-indigo-500 animate-spin"})}),t.jsxs("div",{className:"text-left",children:[t.jsx("div",{className:"font-medium",children:e?"Updating file...":"Uploading file..."}),t.jsxs("div",{className:"text-xs text-muted-foreground font-light",children:["Please wait while we ",e?"update":"upload"," ","your file..."]})]})]})}):t.jsxs("div",{className:"flex items-center justify-between w-full px-6",children:[t.jsx("div",{className:"flex flex-col items-center",children:t.jsxs("div",{className:"leading-tight flex items-center justify-between gap-2",children:[t.jsx("div",{className:"flex items-center justify-center rounded-full bg-indigo-100 p-2 border border-indigo-500",children:t.jsx(w.Upload,{className:"h-4 w-4 text-indigo-500"})}),t.jsxs("div",{className:"text-left",children:[t.jsxs("div",{className:"font-medium",children:["Drop your file here or"," ",t.jsx("span",{className:"text-indigo-500 cursor-pointer hover:underline",children:"browse"})]}),t.jsxs("div",{className:"text-xs text-muted-foreground font-light",children:[t.jsxs("span",{className:"",children:["Accepted file types:"," ",t.jsx("span",{className:"capitalize text-indigo-400",children:s.join(", ")})," & "]}),t.jsxs("span",{children:["Max file size:"," ",t.jsxs("span",{className:"capitalize text-indigo-400",children:[n," MB"]})]})]})]})]})}),t.jsxs("div",{className:"text-xs text-muted-foreground flex items-center gap-2",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsxs("span",{className:"text-xs",children:["Optimization:"," ",t.jsx("span",{className:l?"text-indigo-600":"text-gray-400",children:l?"On":"Off"})]}),t.jsx(c.Switch,{checked:l,onCheckedChange:j=>{o(j)},onClick:j=>{j.stopPropagation()},className:"data-[state=checked]:bg-indigo-500"})]}),t.jsx(c.TooltipProvider,{children:t.jsxs(c.Tooltip,{children:[t.jsx(c.TooltipTrigger,{asChild:!0,children:t.jsx("span",{className:`text-amber-500 flex items-center cursor-help ${l?"invisible":""}`,children:t.jsx(w.AlertTriangle,{className:"h-4 w-4 mr-1"})})}),t.jsx(c.TooltipContent,{side:"top",children:t.jsxs("p",{className:"text-white text-xs",children:["Warning: Unoptimized images may affect ",t.jsx("br",{})," performance and page load times"]})})]})})]})]})]})})};function fr({close:e,onSelect:s,mode:n="image",assetId:a}){const l=g.useMemo(()=>[n],[n]),[o,u]=g.useState(null),[d,h]=g.useState(null),[m,b]=g.useState(null),[j,y]=g.useState({show:!1,file:""}),[p,v]=g.useState(!1),[S,C]=g.useState(a?"details":"grid"),[L,k]=g.useState(""),[D,G]=g.useState(""),[X,$]=g.useState(1),[P]=g.useState(30),[M,H]=g.useState([]);g.useEffect(()=>{a&&(u(a),C("details"))},[a]),g.useEffect(()=>{const B=setTimeout(()=>{k(D),$(1)},300);return()=>clearTimeout(B)},[D]);const{data:K,isLoading:Q}=su({search:L.toLowerCase().trim(),page:X,limit:P}),Z=(K==null?void 0:K.assets)||[],_=(K==null?void 0:K.total)||0,q=Math.ceil(_/P),fe=X<q,be=X>1,ue=(Z==null?void 0:Z.length)>0,{mutate:E}=eu(),{mutate:x,isPending:N}=Zc(),{mutate:U,isPending:T}=tu(),O=g.useCallback(B=>{B>=1&&B<=q&&$(B)},[q]),se=g.useCallback(()=>{fe&&O(X+1)},[X,fe,O]),V=g.useCallback(()=>{be&&O(X-1)},[X,be,O]),ie=B=>{G(B.target.value)},de=g.useCallback(B=>{H(ce=>f.find(ce,{id:B.id})?[]:[B])},[!1]),Y=g.useCallback(()=>{H([])},[]),te=B=>{(B==null?void 0:B.length)!==0&&(s(f.pick(f.first(B||M),["id","url","width","height","description"])),e())},me=async B=>{h(B)},z=async()=>{d&&(b(d==null?void 0:d.id),await E(d.id,{onSuccess:()=>{b(null),h(null)},onError:()=>{b(null)}}),h(null))},ne=B=>{u(B.id),C("details")},Ae=async(B,ce)=>{try{const Ne=localStorage.getItem("chai_optimize_images")!=="false";ce?(await x({file:B,folderId:void 0,name:j.name||"",optimize:Ne}),y({show:!1,file:""})):(await U({id:j.id||"",file:B}),y({show:!1,file:""}))}catch(Ne){console.error("Error saving edited image:",Ne)}},De=g.useCallback(B=>{H([B])},[]);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"}),S==="grid"?t.jsxs(t.Fragment,{children:[t.jsx(ou,{maxFileSize:10,allowedTypes:l,uploadAsset:x,isUpdatingAsset:T,isUploadingAsset:N,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(w.Search,{strokeWidth:3,className:`absolute left-2 top-2.5 h-4 w-4 text-muted-foreground ${D.length>0?"text-indigo-800":""}`}),t.jsx(c.Input,{placeholder:"Search assets...",onChange:ie,value:D,className:"pl-8"})]}),M.length>0?t.jsx("div",{className:"flex justify-between items-center",children:t.jsxs("div",{className:"flex items-center gap-2",children:[M.length>0&&t.jsx(t.Fragment,{children:t.jsx(c.Button,{variant:"outline",size:"sm",onClick:()=>Y(),title:"Clear selection",children:"Clear"})}),t.jsx(c.Button,{size:"sm",onClick:()=>te(M),disabled:M.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&&!ue?t.jsxs("div",{className:"flex flex-col items-center justify-center h-full border rounded-lg",children:[t.jsx("div",{className:"text-muted-foreground",children:t.jsx(w.Archive,{className:"h-9 w-9 text-indigo-500"})}),t.jsx("div",{className:"text-muted-foreground text-lg",children:"No assets found"}),t.jsx("div",{className:"text-muted-foreground text-sm",children:L.length>0?"No assets found for your search: "+L:"Start uploading assets to get started"}),t.jsx("br",{})]}):t.jsx("div",{className:"flex flex-wrap gap-3 p-1",children:Z==null?void 0:Z.map(B=>t.jsxs("div",{className:F.mergeClasses("relative cursor-pointer overflow-hidden transition-all rounded-lg border-2 group max-w-[180px] max-h-[180px] flex flex-col justify-between",M.some(ce=>ce.id===B.id)?"border-blue-500":"hover:border-black/90",m&&(d==null?void 0:d.id)===B.id?"opacity-50 pointer-events-none":"",m===B.id?"opacity-50 pointer-events-none":""),onClick:()=>de(B),onDoubleClick:()=>te([B]),children:[t.jsxs("div",{className:"aspect-square relative overflow-hidden",children:[m===B.id?t.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/50",children:t.jsx(w.Loader,{className:"h-8 w-8 animate-spin text-white"})}):null,B.type==="image"?t.jsx("img",{src:`${B.thumbnailUrl||"/placeholder.svg"}?v=${(B==null?void 0:B.updatedAt)||B.createdAt}`,alt:B.name,className:`object-contain w-full h-full min-h-[80px] ${M.some(ce=>ce.id===B.id)?"":"group-hover:blur group-hover:contrast-50"}`}):t.jsxs("div",{className:"flex items-center justify-center h-full",children:[t.jsx(w.Film,{className:"h-12 w-12 text-muted-foreground"}),B.thumbnailUrl&&t.jsx("img",{src:`${B.thumbnailUrl||"/placeholder.svg"}?v=${(B==null?void 0:B.updatedAt)||B.createdAt}`,alt:B.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:B.name,children:B.name}),t.jsx("div",{className:"text-[9px] whitespace-nowrap font-light text-muted-foreground flex items-center justify-between",children:t.jsx("span",{children:lu((B==null?void 0:B.size)||0)})})]}),!M.some(ce=>ce.id===B.id)&&t.jsx("div",{className:"absolute inset-0 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center",children:t.jsxs("div",{className:"grid grid-cols-4 gap-2 p-2",children:[t.jsx(c.TooltipProvider,{children:t.jsxs(c.Tooltip,{children:[t.jsx(c.TooltipTrigger,{asChild:!0,children:t.jsx(c.Button,{variant:"secondary",size:"icon",className:"h-8 w-8 rounded-full",onClick:ce=>{ce.stopPropagation(),ne(B)},children:t.jsx(w.ImageIcon,{className:"h-4 w-4"})})}),t.jsx(c.TooltipContent,{children:t.jsx("p",{children:"View Details"})})]})}),t.jsx(c.TooltipProvider,{children:t.jsxs(c.Tooltip,{children:[t.jsx(c.TooltipTrigger,{asChild:!0,children:t.jsx(c.Button,{variant:"secondary",size:"icon",className:"h-8 w-8 rounded-full",onClick:ce=>{ce.stopPropagation(),navigator.clipboard.writeText(B.url),J.toast.success("Asset URL copied to clipboard")},children:t.jsx(w.Copy,{className:"h-4 w-4"})})}),t.jsx(c.TooltipContent,{children:t.jsx("p",{children:"Copy URL"})})]})}),t.jsx(c.TooltipProvider,{children:t.jsxs(c.Tooltip,{children:[t.jsx(c.TooltipTrigger,{asChild:!0,children:t.jsx(c.Button,{variant:"secondary",size:"icon",className:"h-8 w-8 rounded-full",onClick:ce=>{ce.stopPropagation(),y({id:B.id,show:!0,file:B.url,name:B.name})},children:t.jsx(w.Edit,{className:"h-4 w-4"})})}),t.jsx(c.TooltipContent,{children:t.jsx("p",{children:"Edit Image"})})]})}),t.jsx(c.TooltipProvider,{children:t.jsxs(c.Tooltip,{children:[t.jsx(c.TooltipTrigger,{asChild:!0,children:t.jsx(c.Button,{variant:"destructive",size:"icon",className:"h-8 w-8 rounded-full",onClick:ce=>{ce.stopPropagation(),me(B)},children:t.jsx(w.Trash2,{className:"h-4 w-4"})})}),t.jsx(c.TooltipContent,{children:t.jsx("p",{children:"Delete Asset"})})]})})]})}),M.some(ce=>ce.id===B.id)&&t.jsx("div",{className:"absolute top-1 right-1 border border-white h-max rounded-full bg-blue-500 p-1",children:t.jsx(w.Check,{className:"w-3 h-3 text-white",strokeWidth:5})})]},B.id))})}),q>1&&t.jsx("div",{className:"absolute bottom-0 left-0 right-0 bg-white border-t p-4",children:t.jsxs("div",{className:"flex items-center justify-center space-x-2",children:[t.jsx(c.Button,{variant:"outline",size:"sm",onClick:V,disabled:!be,children:"Previous"}),Array.from({length:Math.min(5,q)},(B,ce)=>{const Ne=ce+1;return t.jsx(c.Button,{variant:X===Ne?"default":"outline",size:"sm",onClick:()=>O(Ne),children:Ne},Ne)}),q>5&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"text-muted-foreground",children:"..."}),t.jsx(c.Button,{variant:X===q?"default":"outline",size:"sm",onClick:()=>O(q),children:q})]}),t.jsx(c.Button,{variant:"outline",size:"sm",onClick:se,disabled:!fe,children:"Next"})]})})]})]}):t.jsx(ru,{assetId:o||a||"",onBack:()=>{C("grid"),u(null)},onEdit:B=>{y({id:B.id,show:!0,file:B.url,name:B.name})},onSave:async B=>{if(o){v(!0);try{const ce=Z.find(Ne=>Ne.id===o);ce&&await U(f.merge(ce,{description:B}))}finally{v(!1)}}},isSaving:p})]}),j.show&&t.jsx(g.Suspense,{fallback:t.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:t.jsx(w.Loader,{className:"h-8 w-8 animate-spin"})}),children:t.jsx(iu,{imageUrl:j.file,onSave:Ae,onClose:()=>y({show:!1,file:""}),defaultSavedImageName:j.name,isEditing:!!j.id})}),d&&t.jsx(c.Dialog,{open:!!d,onOpenChange:()=>h(null),children:t.jsxs(c.DialogContent,{children:[t.jsxs(c.DialogHeader,{children:[t.jsx(c.DialogTitle,{children:"Delete Asset"}),t.jsxs(c.DialogDescription,{children:['Are you sure you want to delete "',d.name,'"? This action cannot be undone.']})]}),t.jsxs(c.DialogFooter,{className:"gap-2 sm:gap-0",children:[t.jsx(c.Button,{variant:"outline",onClick:()=>h(null),children:"Cancel"}),t.jsx(c.Button,{variant:"destructive",onClick:z,children:"Delete"})]})]})})]})}const cu=Object.freeze(Object.defineProperty({__proto__:null,default:fr},Symbol.toStringTag,{value:"Module"})),Ns=({assetId:e,assetUrl:s,onChange:n,className:a="",placeholder:r="Select an image",disabled:i=!1})=>{const[l,o]=g.useState(!1),u=()=>{i||o(!0)},d=()=>{o(!1)},h=b=>{const j=Array.isArray(b)?b[0]:b;j!=null&&j.url&&n(f.pick(j,["url","id"])),o(!1)},m=()=>{n({url:"",id:""})};return t.jsxs("div",{className:`w-full ${a}`,children:[s?t.jsxs("div",{className:"relative border rounded-md overflow-hidden",children:[t.jsx("img",{onClick:u,src:s,alt:"Selected image",className:"w-full h-auto bg-gray-300 object-contain max-h-[100px]"}),t.jsxs("div",{className:"absolute top-2 right-2 flex gap-2",children:[t.jsx(c.Button,{type:"button",variant:"destructive",size:"icon",className:"h-8 w-8 rounded-full bg-white/80 text-red-500 hover:bg-white/90",onClick:m,disabled:i,children:t.jsx(w.Trash2,{className:"h-4 w-4"})}),t.jsx(c.Button,{type:"button",variant:"secondary",size:"icon",className:"h-8 w-8 rounded-full bg-white/80 hover:bg-white/90",onClick:u,disabled:i,children:t.jsx(w.ImageIcon,{className:"h-4 w-4"})})]})]}):t.jsx("div",{className:`flex items-center justify-center border border-dashed rounded-md p-6 cursor-pointer ${i?"opacity-50 cursor-not-allowed":"hover:border-gray-400"}`,onClick:u,children:t.jsxs("div",{className:"flex flex-col items-center gap-2",children:[t.jsx(w.ImageIcon,{className:"h-10 w-10 text-gray-400"}),t.jsx("p",{className:"text-sm text-gray-500",children:r})]})}),t.jsx(c.Dialog,{open:l,onOpenChange:o,children:t.jsxs(c.DialogContent,{className:"w-full max-w-7xl h-fit p-0 overflow-hidden",children:[t.jsxs(c.DialogHeader,{className:"px-4 py-2 border-b hidden",children:[t.jsx(c.DialogTitle,{children:"Select Image"}),t.jsx(c.Button,{type:"button",variant:"ghost",size:"icon",className:"absolute right-4 top-2",onClick:d,children:t.jsx(w.X,{className:"h-4 w-4"})})]}),t.jsx("div",{className:"flex-1 p-4 h-full",children:t.jsx(fr,{close:d,onSelect:h,mode:"image",assetId:e})})]})})]})},uu=({isActive:e,onClick:s})=>t.jsx(c.Button,{variant:e?"default":"ghost",className:"w-full justify-start text-left",onClick:s,children:"Branding"}),du=()=>{const[e,s]=g.useState({logoUrl:"",logoId:"",faviconUrl:"",faviconId:""}),[n,a]=g.useState(!1),r=()=>{a(!0),setTimeout(()=>{a(!1),console.log("Branding settings saved:",e)},1e3)};return t.jsxs("div",{className:"space-y-4",children:[t.jsx("h2",{className:"text-lg font-medium",children:"Branding Settings"}),t.jsxs("div",{className:"border rounded p-4 space-y-3",children:[t.jsxs("div",{children:[t.jsx("label",{className:"text-sm font-medium block mb-1",children:"Logo"}),t.jsx(Ns,{assetId:e.logoId,assetUrl:e.logoUrl,onChange:i=>{s({...e,logoUrl:i.url,logoId:i.id})},placeholder:"Select logo image",className:"mb-2"}),t.jsx("span",{className:"text-xs text-muted-foreground",children:"Recommended size: 200x50px"})]}),t.jsxs("div",{children:[t.jsx("label",{className:"text-sm font-medium block mb-1",children:"Favicon"}),t.jsx(Ns,{assetId:e.faviconId,assetUrl:e.faviconUrl,onChange:i=>{s({...e,faviconUrl:i.url,faviconId:i.id})},placeholder:"Select favicon",className:"mb-2"}),t.jsx("span",{className:"text-xs text-muted-foreground",children:"Recommended size: 32x32px"})]}),t.jsx("div",{className:"pt-3",children:t.jsx(c.Button,{onClick:r,disabled:n,className:"w-full",children:n?"Saving...":"Save Branding Settings"})})]})]})},hu=()=>{Vs("general",{label:"General",button:Jc,panel:Xc}),Vs("branding",{label:"Branding",button:uu,panel:du})},mu=g.lazy(()=>Promise.resolve().then(()=>cu));Kc();vr.loadWebBlocks();F.registerChaiTopBar(wl);eo();hu();F.registerChaiMediaManager(mu);F.registerChaiSaveToLibrary(ti);const fu=e=>{const s=g.useRef([]),[n]=_e(),a=n.get("page"),{data:r}=Pe(),{data:i={role:"",permissions:null}}=Sa();Al(),Fr();const{data:l,isFetching:o}=ca(),{blocks:u}=Cl(l),{data:d}=Ce(),{mutateAsync:h}=Zn(),m=El(),{onSave:b}=Tl(),{getPartialBlocks:j,getPartialBlockBlocks:y}=kl(),{aiContext:p,setAiContext:v}=sn(),{mutateAsync:S}=ni(),[C,L]=g.useState(!1),{data:k}=He(),D=Qe(),{data:G}=rn(),{data:X}=Hc(),{mutateAsync:$}=Qc(),P=mr();Ir(),g.useEffect(()=>{const Q=()=>{document.hidden?L(!0):L(!1)};return window.addEventListener("visibilitychange",Q),()=>window.removeEventListener("visibilitychange",Q)},[]),s.current=u;const M=g.useMemo(()=>{const Q={};return i&&(Q.permissions=f.get(i,"permissions",null),Q.role=f.get(i,"role","user")),Q},[i]),H=g.useCallback(async(Q,Z)=>await S({pageType:Q,query:Z}),[S]),K=g.useMemo(()=>f.get(k,"theme",{})||{},[k]);return t.jsxs(t.Fragment,{children:[o&&t.jsx(hr,{}),t.jsx(F.ChaiBuilderEditor,{gotoPage:P,collections:X??[],getBlockAsyncProps:$,pageExternalData:G,themePresets:e.themePresets??[],pageId:r==null?void 0:r.id,loading:o,fallbackLang:D,languages:(k==null?void 0:k.languages)||[],brandingOptions:(k==null?void 0:k.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:y,getPartialBlocks:j,blocks:o?[]:u,theme:f.cloneDeep(K),pageTypes:d,searchPageTypeItems:H,saveAiContextCallback:async Q=>{if(!a)return!0;const Z=s.current,_={_type:"@chai/ai-context",_value:f.isString(Q)?Q:""},q=[...Z,_];return await b({page:a,blocks:q}),v(Q),!0},aiContext:p,askAiCallBack:m,onSave:async({blocks:Q,theme:Z})=>{if(!a)return!0;s.current=Q;const _={_type:"@chai/ai-context",_value:f.isString(p)?p:""},q=[...Q,_];return await b({page:a,blocks:q}),s.current=q,f.isEqual(Z,K)||await h({settings:{theme:Z}}),!0},themePanelComponent:mi,...M}),t.jsxs("div",{children:[t.jsx(zr,{}),t.jsx(Vr,{})]})]})},gu=new R.QueryClient({defaultOptions:{queries:{refetchOnWindowFocus:!1,refetchOnReconnect:!1}}}),xu=e=>{const{isLoggedIn:s,isSessionExpired:n}=Ue(),[,a]=ea(),[r,i]=g.useState(!1);return Yc(),g.useEffect(()=>(a(f.pick(e,["apiUrl","usersApiUrl","assetsApiUrl","getPreviewUrl","getLiveUrl","logo","onLogout","getAccessToken","realtimeInstance"])),setTimeout(()=>{i(!0)},200),()=>{i(!1),a({})}),[e,a]),r?t.jsxs(R.QueryClientProvider,{client:gu,children:[s?n?t.jsx(hr,{}):t.jsx(fu,{...e}):t.jsx(Ll,{}),t.jsx(Vc,{})]}):t.jsx("div",{})},pu=()=>{const e=oe(),s=ee(),{data:n}=tt(),a=R.useQueryClient();return R.useMutation({mutationFn:async r=>{if(!(n!=null&&n.id))throw new Error("No active page found");return await s(`${e}`,{action:I.UPDATE_PAGE_METADATA,data:{id:n.id,metadata:r}})},onSuccess:()=>{a.invalidateQueries({queryKey:[W,I.GET_BUILDER_PAGE_DATA]}),a.invalidateQueries({queryKey:[W,I.GET_LANGUAGE_PAGES]})},onError:()=>{console.error("Failed to update metadata")}})},yu=()=>{const{logout:e}=Ue(),{getAccessToken:s}=Jn();return g.useCallback(async({url:n,method:a="GET",body:r={},headers:i={}})=>{const l=await s();if(!l)throw new Error("No auth token");if(!n)throw new Error("URL is required");try{const o=await fetch(n,{method:a,headers:{"Content-Type":"application/json",Authorization:`Bearer ${l}`,...i},body:JSON.stringify(r)});if(o.status===401)return console.log("Session expired",o),await e(),window.location.reload(),null;if(o.status===400)throw new Error((await o.json()).error);return await o.json()}catch(o){throw console.log("Something went wrong",o),o}},[e,s])};class ju{constructor(s){Gt(this,"client");Gt(this,"channel",null);Gt(this,"currentUserId",null);Gt(this,"updateLockingState",s=>{const n=this.getCurrentOnlineUser();!n||n===this.currentUserId?s("USER_JOINED",{lockedBy:n}):s("PAGE_LOCKED",{lockedBy:n})});this.client=s}async joinPage(s,n,a){var i,l,o,u,d,h;const r=`PAGE:${s}`;this.channel&&await this.leavePage(),this.currentUserId=n,this.channel=this.client.channel(r,{config:{presence:{key:n}}}),(h=(d=(u=(o=(l=(i=this.channel)==null?void 0:i.on("presence",{event:"sync"},()=>{this.updateLockingState(a)}))==null?void 0:l.on("presence",{event:"leave"},()=>{this.updateLockingState(a)}))==null?void 0:o.on("presence",{event:"join"},m=>{(m==null?void 0:m.key)!==this.currentUserId&&this.updateLockingState(a)}))==null?void 0:u.on("broadcast",{event:"TAKE_OVER_REQUESTED"},({payload:m})=>{a("TAKE_OVER_REQUESTED",m)}))==null?void 0:d.on("broadcast",{event:"TAKE_OVER_REQUEST_ACCEPTED"},({payload:m})=>{a("TAKE_OVER_REQUEST_ACCEPTED",m)}))==null||h.on("broadcast",{event:"TAKE_OVER_REQUEST_REJECTED"},({payload:m})=>{a("TAKE_OVER_REQUEST_REJECTED",m)}).subscribe(m=>{var b;m==="SUBSCRIBED"&&((b=this.channel)==null||b.track({userId:n,onlineAt:+new Date}))})}async leavePage(){if(this.channel){await this.channel.unsubscribe();const s=await this.client.removeChannel(this.channel);return this.channel=null,s}}async sendEvent(s,n){return new Promise(a=>{var r;this.channel&&((r=this.channel)==null||r.send({type:"broadcast",event:s,payload:n}).then(()=>{s==="TAKE_OVER_REQUEST_ACCEPTED"?this.channel.untrack({userId:this.currentUserId}).then(()=>{this.channel.track({userId:this.currentUserId,onlineAt:+new Date}),a()}):a()}))})}getCurrentOnlineUser(){var a,r;const s=(a=this.channel)==null?void 0:a.presenceState(),n=Object.values(s||{}).map(i=>i[0]).filter(Boolean);return((r=f.minBy(n,"onlineAt"))==null?void 0:r.userId)||""}}if(typeof window>"u")throw new Error("@chaibuilder/pages is not available on the server");exports.$TRACK=jn;exports.ChaiBuilderPages=xu;exports.ChaiBuilderPagesRealtime=ju;exports.Dynamic=Jo;exports.For=Eo;exports.ImagePicker=Ns;exports.Index=No;exports.LanguageSwitcher=yn;exports.Match=To;exports.NestedPathSelector=Ye;exports.PermissionChecker=Re;exports.Portal=Yo;exports.Show=Co;exports.SmartJsonInput=Ea;exports.Switch=Ao;exports.addEventListener=$a;exports.batch=ro;exports.className=qa;exports.clearDelegatedEvents=Fo;exports.convertRemToPixels=Uc;exports.createComponent=Sn;exports.createComputed=Pa;exports.createContext=ho;exports.createEffect=vn;exports.createMemo=Ge;exports.createRenderEffect=Xe;exports.createRoot=Je;exports.createSignal=Ee;exports.createUniqueId=wo;exports.delegateEvents=Oa;exports.deleteNestedDataByPath=Ft;exports.displayValue=Lc;exports.getMutationStatusColor=_c;exports.getPreferredColorScheme=Fc;exports.getQueryStatusColor=Pc;exports.getQueryStatusColorByLabel=Ic;exports.getQueryStatusLabel=Tc;exports.getSidedProp=kc;exports.insert=Es;exports.mergeProps=wn;exports.mutationSortFns=Rc;exports.on=io;exports.onCleanup=kt;exports.onMount=_a;exports.registerChaiSiteSetting=Vs;exports.registerLoginComponent=Il;exports.serialize=or;exports.setAttribute=ws;exports.sortFns=Gc;exports.splitProps=Ma;exports.spread=za;exports.stringify=Ac;exports.template=Uo;exports.untrack=ke;exports.updateNestedDataByPath=Ut;exports.use=Va;exports.useActivePage=tt;exports.useBuilderPageData=rn;exports.useChaiAuth=Ue;exports.useChaiFetch=yu;exports.useChaiUserInfo=ct;exports.useContext=mo;exports.useCurrentPage=Pe;exports.useFallbackLang=Qe;exports.useFetch=ee;exports.useGotoPage=mr;exports.useLanguagePages=Oe;exports.usePageTypes=Ce;exports.useTransition=uo;exports.useUpdateActivePageMetadata=pu;exports.useUserRoleAndPermissions=Sa;exports.useWebsitePages=ot;exports.useWebsiteSetting=He;