@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.
@@ -1,6 +0,0 @@
1
- "use strict";var gr=Object.defineProperty;var wn=e=>{throw TypeError(e)};var xr=(e,s,n)=>s in e?gr(e,s,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[s]=n;var Bs=(e,s,n)=>xr(e,typeof s!="symbol"?s+"":s,n),Nn=(e,s,n)=>s.has(e)||wn("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)?wn("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"),m=require("lodash-es"),g=require("react"),Ee=require("jotai"),R=require("@tanstack/react-query"),J=require("sonner"),O=require("@chaibuilder/sdk"),c=require("@chaibuilder/sdk/ui"),kt=require("date-fns"),N=require("lucide-react"),Hn=require("@chaibuilder/runtime"),hs=require("zod"),pr=require("react-dropzone"),yr=require("@chaibuilder/sdk/web-blocks");function jr(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=jr(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"},L={GENERATE_SEO_FIELD:"GENERATE_SEO_FIELD",UPDATE_PAGE_METADATA:"UPDATE_PAGE_METADATA",GET_BLOCK_ASYNC_PROPS:"GET_BLOCK_ASYNC_PROPS",ASK_AI:"ASK_AI",GET_DRAFT_PAGE:"GET_DRAFT_PAGE",CREATE_PAGE:"CREATE_PAGE",UPDATE_PAGE:"UPDATE_PAGE",DELETE_PAGE:"DELETE_PAGE",DUPLICATE_PAGE:"DUPLICATE_PAGE",CHANGE_SLUG:"CHANGE_SLUG",TAKE_OFFLINE:"TAKE_OFFLINE",PUBLISH_PAGE:"PUBLISH_PAGE",PUBLISH_CHANGES:"PUBLISH_CHANGES",ADD_NEW_LANGUAGE:"ADD_NEW_LANGUAGE",EDIT_LANGUAGE:"EDIT_LANGUAGE",DELETE_LANGUAGE:"DELETE_LANGUAGE",GET_CHANGES:"GET_CHANGES",GET_SERVER_BLOCK:"GET_SERVER_BLOCK",GET_LANGUAGE_PAGES:"GET_LANGUAGE_PAGES",GET_PROJECT_PAGES:"GET_PROJECT_PAGES",GET_WEBSITE_PAGES:"GET_WEBSITE_PAGES",UPDATE_WEBSITE_SETTINGS:"UPDATE_WEBSITE_SETTINGS",GET_COLLECTIONS:"GET_COLLECTIONS",GET_PAGE_TYPES:"GET_PAGE_TYPES",SEARCH_PAGES:"SEARCH_PAGES",GET_WEBSITE_DRAFT_SETTINGS:"GET_WEBSITE_DRAFT_SETTINGS",AI_CONTEXT:"AI_CONTEXT",GET_WEBSITE_DATA:"GET_WEBSITE_DATA",UPDATE_WEBSITE_DATA:"UPDATE_WEBSITE_DATA",GET_CHAI_USER:"GET_CHAI_USER",RELEASE_LOCK:"RELEASE_LOCK",GET_SEO_FIELDS:"GET_SEO_FIELDS",GET_BUILDER_PAGE_DATA:"GET_BUILDER_PAGE_DATA",GET_PAGE_REVISIONS:"GET_PAGE_REVISIONS",DELETE_PAGE_REVISION:"DELETE_PAGE_REVISION",RESTORE_PAGE_REVISION:"RESTORE_PAGE_REVISION",GET_ROLE_AND_PERMISSIONS:"GET_ROLE_AND_PERMISSIONS",UPSERT_LIBRARY_ITEM:"UPSERT_LIBRARY_ITEM",GET_LIBRARIES:"GET_LIBRARIES",GET_LIBRARY_ITEM:"GET_LIBRARY_ITEM",GET_LIBRARY_ITEMS:"GET_LIBRARY_ITEMS",DELETE_LIBRARY_ITEM:"DELETE_LIBRARY_ITEM",MARK_AS_TEMPLATE:"MARK_AS_TEMPLATE",UNMARK_AS_TEMPLATE:"UNMARK_AS_TEMPLATE",GET_TEMPLATES_BY_TYPE:"GET_TEMPLATES_BY_TYPE",GET_DYNAMIC_PAGES:"GET_DYNAMIC_PAGES",UPLOAD_ASSET:"UPLOAD_ASSET",DELETE_ASSET:"DELETE_ASSET",UPDATE_ASSET:"UPDATE_ASSET",GET_ASSETS:"GET_ASSETS",GET_ASSET:"GET_ASSET"},Q="chaibuilder";let vr=0;function En(e,s){const n=`atom${++vr}`,a={toString(){return n}};return typeof e=="function"?a.read=e:(a.init=e,a.read=br,a.write=Sr),s&&(a.write=s),a}function br(e){return e(this)}function Sr(e,s,n){return s(this,typeof n=="function"?n(e(this)):n)}const wr=Symbol(""),Nr=e=>typeof(e==null?void 0:e.then)=="function";function Er(e=()=>{try{return window.localStorage}catch{return}},s){var n;let a,r;const i={getItem:(u,d)=>{var h,f;const b=p=>{if(p=p||"",a!==p){try{r=JSON.parse(p,s==null?void 0:s.reviver)}catch{return d}a=p}return r},j=(f=(h=e())==null?void 0:h.getItem(u))!=null?f:null;return Nr(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,f)=>u(d,b=>{let j;try{j=JSON.parse(b||"")}catch{j=f}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=f=>{f.storageArea===e()&&f.key===u&&d(f.newValue)};return window.addEventListener("storage",h),()=>{window.removeEventListener("storage",h)}}),o&&(i.subscribe=l(o)),i}const Cr=Er();function Wn(e,s,n=Cr,a){const r=En(s);return r.onMount=l=>{l(n.getItem(e,s));let o;return n.subscribe&&(o=n.subscribe(e,l,s)),o},En(l=>l(r),(l,o,u)=>{const d=typeof u=="function"?u(l(r)):u;return d===wr?(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 Qn="__logged_in_user",Ar=Wn(Qn,null),Fe=()=>{const[e,s]=Ee.useAtom(Ar),n=g.useCallback(()=>{s(null),localStorage.removeItem(Qn)},[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}},en=async(e,s,n={})=>await fetch(e,{method:"POST",headers:{"Content-Type":"application/json",...n},body:JSON.stringify(s)}),Yn=()=>{const{user:e}=Fe(),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}=Fe(),s=R.useQueryClient(),{getAccessToken:n}=Yn();return g.useCallback(async(a,r,i={})=>{const l=await n();if(!l)return null;try{const o=m.get(r,"action","").toLowerCase(),u=await en(a+(o?`?action=${o}`:""),r,{...i,Authorization:`Bearer ${l}`});if(u.status===401)return console.log("401 Response",u),s.invalidateQueries({queryKey:[Q]}),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])},Jn=()=>{const e=oe(),s=R.useQueryClient(),n=ee();return R.useMutation({mutationFn:async a=>n(e,{action:L.RELEASE_LOCK,data:a}),onSuccess:()=>{s.invalidateQueries({queryKey:[Q,L.GET_DRAFT_PAGE]})}})},Xn=()=>{const e=oe(),s=R.useQueryClient(),n=ee();return R.useMutation({mutationFn:async a=>n(e,{action:L.UPDATE_WEBSITE_SETTINGS,data:a}),onSuccess:(a,r)=>{var i;s.invalidateQueries({queryKey:[Q,L.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})}})},Tr=()=>{const e=oe(),s=R.useQueryClient(),n=ee();return R.useMutation({mutationFn:async a=>n(e,{action:L.UPDATE_WEBSITE_DATA,data:a}),onSuccess:()=>{s.invalidateQueries({queryKey:[Q,L.GET_WEBSITE_DATA]}),J.toast.success("Website data updated successfully.")},onError:a=>{J.toast.error("Failed to update website data",{description:a.message})}})};function Le(){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 Pr=Ee.atom({}),Zn=()=>Ee.useAtom(Pr),kr=()=>{const[e]=Le(),s=e.get("page"),n=g.useRef(""),{mutate:a}=Jn();g.useEffect(()=>{!m.isEmpty(n.current)&&s!==n.current&&a({id:n.current}),n.current=s},[s,a,n])},qe=(e,s)=>{const[n]=Zn();return g.useMemo(()=>m.get(n,e,s),[n,e,s])},oe=()=>qe("apiUrl","/chai/api"),Es=()=>qe("usersApiUrl","/chai/users"),ns=()=>qe("assetsApiUrl","/chai/assets"),ea=()=>qe("realtimeInstance",null),Ue=e=>{const s=oe(),[n]=Le(),a=e??n.get("page"),r=ee();return R.useQuery({queryKey:[Q,L.GET_LANGUAGE_PAGES,a],initialData:[],queryFn:async()=>{if(!a)return null;const i=await r(s,{action:L.GET_LANGUAGE_PAGES,data:{id:a}});return m.reverse(m.sortBy(i,"primaryPage"))},enabled:!!a})},He=()=>{const e=oe(),s=ee();return R.useQuery({queryKey:[Q,L.GET_WEBSITE_DRAFT_SETTINGS],initialData:{theme:{},fallbackLang:"en",languages:[]},queryFn:async()=>s(e,{action:L.GET_WEBSITE_DRAFT_SETTINGS,data:{draft:!0}})})},ta=e=>{const{fallbackLang:s}=O.useLanguages(),{data:n}=He(),{data:a,isFetching:r}=Ue(),i=g.useMemo(()=>{const l={[s]:!0};return m.each(m.get(n,"languages"),o=>{const u=m.find(a,{lang:o});l[o]=!!u}),l},[s,a,n]);return r||m.isEmpty(e)||e&&i[e]},tn=()=>{const e=R.useQueryClient(),{data:s}=R.useQuery({queryKey:[Q,L.AI_CONTEXT],initialData:"",queryFn:()=>"",staleTime:0});return{setAiContext:g.useCallback(a=>{e.setQueryData([Q,L.AI_CONTEXT],a)},[e]),aiContext:s}},Lr=Ee.atom(null),sa=()=>Ee.useAtom(Lr),sn=()=>{const[e]=sa();return(e==null?void 0:e.slug)||""};function Ir(e,s){const[n,a]=g.useState(e);return g.useEffect(()=>{const r=setTimeout(()=>a(e),s);return()=>clearTimeout(r)},[e,s]),n}const _r=({query:e,uuid:s})=>{const{selectedLang:n,fallbackLang:a}=O.useLanguages(),{data:r}=ke(),i=r==null?void 0:r.pageType,l=oe(),o=ee(),{data:u,isFetching:d}=R.useQuery({queryKey:[L.GET_DYNAMIC_PAGES,e,i,s],initialData:[],queryFn:async()=>await o(l,{action:L.GET_DYNAMIC_PAGES,data:{query:e,pageType:i,uuid:s}})||[],enabled:!!i}),h=g.useMemo(()=>n===""?u.filter(f=>f.lang===""||f.lang===a):u.filter(f=>f.lang===n),[n,a,u]);return{allLangPages:u,data:h,isFetching:d}},na=()=>{const{selectedLang:e,fallbackLang:s}=O.useLanguages(),[n,a]=sa(),[r,i]=g.useState(""),l=Ir(r,500),{allLangPages:o,data:u,isFetching:d}=_r({query:l}),h=g.useCallback(j=>a(j),[a]),f=g.useCallback(j=>i(j),[i]),b=g.useCallback(()=>{if(!n)return;const j=!(n!=null&&n.primaryPage),p=e.length===0,y=j?n==null?void 0:n.id:n==null?void 0:n.primaryPage,S=o.filter(E=>(E==null?void 0:E.primaryPage)===y||E.id===y).find(E=>p?E.lang===e||E.lang===s:E.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:f,onChangeLanguage:b}},We=()=>{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:[Q,L.GET_WEBSITE_PAGES],staleTime:1e3*60*5,queryFn:async()=>e(s,{action:L.GET_WEBSITE_PAGES})||[],placeholderData:n=>n||[]})},Dr=e=>{const s=ee(),n=oe(),a=We();return R.useQuery({queryKey:[Q,L.GET_WEBSITE_PAGES,e,a],staleTime:1e3*60*5,enabled:!!e&&a!==e,queryFn:async()=>{const r=await s(n,{action:L.GET_WEBSITE_PAGES,data:{lang:e}})||[];return m.keyBy(m.map(r,i=>({...i,lang:e})),"primaryPage")},placeholderData:r=>r||{}})},Br=Ee.atom({lastSaved:void 0}),Cs=()=>Ee.useAtom(Br),ke=()=>{const[e]=Le(),s=e.get("page"),[n]=aa(),{data:a,isFetching:r}=ot();return{data:g.useMemo(()=>({...m.find(a,{id:s})||{},metadata:n}),[a,s,n]),isFetching:r}},tt=()=>{const[e]=Le(),s=e.get("lang")??"",{data:n,isFetching:a}=Ue();return{data:g.useMemo(()=>m.find(n,{lang:s})||{},[n,s]),isFetching:a}},Mr=Ee.atom({}),aa=()=>Ee.useAtom(Mr),ra=()=>{const{data:e}=tt(),s=sn(),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=Es(),n=ee();return R.useQuery({queryKey:[Q,"chaiUserInfo",e],queryFn:async()=>await n(s,{action:L.GET_CHAI_USER,data:{userId:e}}),enabled:!m.isEmpty(e)})},Gr=Ee.atom(void 0),nn=Ee.atom({status:"checking",requestedBy:"",isTakeOverRequested:!1}),as=()=>{const[e]=Le(),s=e.get("page"),{user:n}=Fe(),[a,r]=Ee.useAtom(Gr),[i]=Ee.useAtom(nn),l=O.useChaiFeatureFlag("realtime-page-lock");return g.useMemo(()=>({isLocked:l?s&&i.status==="locked":s&&(n==null?void 0:n.id)!==a,currentEditor:a,setCurrentEditor:o=>r(o)}),[l,s,i.status,n==null?void 0:n.id,a,r])},Rr=()=>{const e=ea(),{data:s}=ke(),{user:n}=Fe(),a=s==null?void 0:s.id,[r,i]=Ee.useAtom(nn),l=g.useRef(!1),o=O.useChaiFeatureFlag("realtime-page-lock");return g.useEffect(()=>{r.status==="locked"||!a||!(n!=null&&n.id)||!e||!o||l.current||setTimeout(()=>{l.current||(l.current=!0,e==null||e.listenEvent("TAKE_OVER_REQUESTED",u=>{(u==null?void 0:u.requesterUserId)!==(n==null?void 0:n.id)&&i({...r,requestedBy:u==null?void 0:u.requesterUserId})}))},1e3)},[r,e,i,a,o,n==null?void 0:n.id]),g.useEffect(()=>{if(!o||!e||!a||!(n!=null&&n.id))return;async function u(){const d=await(e==null?void 0:e.joinPage(a,n==null?void 0:n.id));i({...r,status:d?"editing":"locked",requestedBy:""})}return u(),()=>{e==null||e.leavePage(a,n==null?void 0:n.id)}},[a,o]),{}},ia=()=>{const e=ea(),{data:s}=ke(),{user:n}=Fe(),a=s==null?void 0:s.id,[r,i]=Ee.useAtom(nn),{saveState:l,savePage:o}=O.useSavePage(),u=R.useQueryClient(),d=g.useCallback(()=>{!e||!a||!(n!=null&&n.id)||(i({...r,isTakeOverRequested:!0}),e==null||e.requestTakeOver(a,n==null?void 0:n.id),e==null||e.listenEvent("TAKE_OVER_REQUEST_ACCEPTED",()=>{J.toast.success("Your Page Take Over Request Accepted",{position:"top-center"}),i({status:"editing",requestedBy:"",isTakeOverRequested:!1}),u.invalidateQueries({queryKey:[Q,L.GET_DRAFT_PAGE]})}),e==null||e.listenEvent("TAKE_OVER_REQUEST_REJECTED",()=>{i({...r,isTakeOverRequested:!1}),J.toast.warning("Your Page Take Over Request Rejected",{position:"top-center",closeButton:!0,duration:1/0})}))},[e,a,n==null?void 0:n.id,i,r,u]),h=g.useCallback(async()=>{!e||!a||!(n!=null&&n.id)||(l!=="SAVED"&&(o(),await new Promise(b=>setTimeout(b,1500))),e==null||e.acceptTakeOver(a,n==null?void 0:n.id),i({status:"locked",requestedBy:"",isTakeOverRequested:!1}))},[a,e,n==null?void 0:n.id,i,o,l]),f=g.useCallback(()=>{!e||!a||!(n!=null&&n.id)||(e==null||e.rejectTakeOver(a,n==null?void 0:n.id),i({status:"editing",requestedBy:"",isTakeOverRequested:!1}))},[a,e,n==null?void 0:n.id,i]);return{pageLock:r,requestTakeOver:d,acceptTakeOver:h,rejectTakeOver:f}},la=()=>{const[e]=Le(),s=e.get("page"),n=oe(),{setAiContext:a}=tn(),{setCurrentEditor:r}=as(),[,i]=Cs(),[,l]=aa(),o=ee();return R.useQuery({queryKey:[Q,L.GET_DRAFT_PAGE,s],staleTime:1/0,gcTime:1/0,queryFn:async()=>{r("");const u=await o(n,{action:L.GET_DRAFT_PAGE,data:{id:s,draft:!0}});r(u.currentEditor);const d=u.blocks??[],h=m.find(d,{_type:"@chai/ai-context"});return a(m.get(h,"_value","")||""),i(f=>({...f,lastSaved:u.lastSaved})),l(m.get(u,"metadata",{})),d},enabled:!!s})},an=()=>{const{data:e}=ke(),{data:s}=tt(),n=oe(),a=ee(),r=We(),i=sn();return R.useQuery({queryKey:[Q,L.GET_BUILDER_PAGE_DATA,s==null?void 0:s.id,i],initialData:{},queryFn:async()=>a(n,{action:L.GET_BUILDER_PAGE_DATA,data:{pageType:e==null?void 0:e.pageType,lang:(s==null?void 0:s.lang)||r,dynamic:e==null?void 0:e.dynamic,pageProps:{slug:(s==null?void 0:s.slug)+i,searchParams:{},pageType:s==null?void 0:s.pageType,fallbackLang:r,lastSaved:s.lastSaved,pageId:e.id,primaryPageId:s.primaryPage||e.id,pageBaseSlug:s==null?void 0:s.slug,dynamic:e==null?void 0:e.dynamic,languagePageId:s.id}}}),enabled:!!(s!=null&&s.pageType)})},Fr=({currentEditor:e})=>{const{user:s}=Fe(),{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(N.LockIcon,{className:"h-3 w-3"})}),t.jsx(c.TooltipContent,{children:t.jsxs("p",{children:[n.name," is editing"]})})]})})},Cn=({userId:e})=>{const{data:s}=ct(e);return(s==null?void 0:s.name)||"Unknown"};function Or({avatar:e,name:s,email:n,lastSaved:a,onTakeOver:r,pageLock:i,realtimePageLockEnabled:l}){const[o,u]=g.useState(!1),d=()=>{u(!1),r()};return t.jsx("div",{className:"fixed bottom-0 left-0 right-0 top-[50px] z-[20] flex w-screen items-center justify-center bg-black/30 backdrop-blur-sm",children:t.jsxs(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(N.LockIcon,{className:"h-6 w-6 text-yellow-500"}),"Page locked for editing"]})}),t.jsx(c.CardContent,{className:"grid gap-4",children:t.jsxs("div",{children:[t.jsxs("div",{className:"flex items-center space-x-4",children:[e?t.jsx("img",{src:e,alt:s,className:"h-12 w-12 rounded-full border border-gray-300"}):t.jsx(N.UserIcon,{className:"h-12 w-12 rounded-full border border-gray-300 p-2"}),t.jsxs("div",{className:"space-y-1",children:[t.jsx("h3",{className:"font-semibold",children:s}),n&&t.jsx("p",{className:"text-sm text-muted-foreground",children:n}),a&&t.jsxs("p",{className:"text-sm text-muted-foreground",children:["Last saved:"," ",kt.formatDistanceToNow(new Date(a),{addSuffix:!0})]})]})]}),t.jsx("div",{className:"mt-4 text-sm",children:t.jsx("p",{children:"This user is currently editing the page. You cannot make changes."})})]})}),t.jsx(c.CardFooter,{children:l?t.jsx(c.Button,{disabled:i.isTakeOverRequested,onClick:d,className:"w-full",variant:"destructive",children:i.isTakeOverRequested?"Page take is requested.":"Request take over"}):t.jsxs(c.AlertDialog,{open:o,onOpenChange:u,children:[t.jsx(c.AlertDialogTrigger,{asChild:!0,children:t.jsxs("span",{className:"flex flex-col items-center",children:[t.jsx(c.Button,{className:"w-full",variant:"destructive",children:"Take over"}),t.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:"If you need to edit, you can take over the lock, but be aware that the other user might lose unsaved changes."})]})}),t.jsxs(c.AlertDialogContent,{className:"z-[99]",children:[t.jsxs(c.AlertDialogHeader,{children:[t.jsx(c.AlertDialogTitle,{children:"Are you sure you want to take over?"}),t.jsxs(c.AlertDialogDescription,{children:[t.jsxs("span",{className:"flex items-center space-x-2 text-yellow-500",children:[t.jsx(N.AlertTriangleIcon,{className:"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:d,children:"Yes, Take Over"})]})]})]})})]})})}const Ur=()=>{const{pageLock:e,acceptTakeOver:s,rejectTakeOver:n}=ia();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-2xl",children:[t.jsx(N.AccessibilityIcon,{className:"h-6 w-6 text-yellow-500"}),t.jsx(Cn,{userId:e==null?void 0:e.requestedBy})," has requested to take over this page"]})}),t.jsx(c.CardContent,{className:"grid gap-4",children:t.jsx("div",{children:t.jsx("div",{className:"mt-4 text-sm",children:t.jsxs("p",{children:[t.jsx(Cn,{userId:e==null?void 0:e.requestedBy})," has requested to take over this page. Do you want to accept the request?"]})})})}),t.jsxs(c.CardFooter,{className:"flex items-center justify-end gap-2",children:[t.jsx(c.Button,{onClick:s,children:"Yes"}),t.jsx(c.Button,{variant:"outline",onClick:n,children:"No"})]})]})})},qr=()=>{const{isLocked:e,currentEditor:s}=as(),{data:n}=ct(s),[a]=Le(),r=a.get("page"),{mutate:i}=Jn(),{isFetching:l}=la(),[o]=Cs(),{pageLock:u,requestTakeOver:d}=ia(),h=O.useChaiFeatureFlag("realtime-page-lock"),f=g.useCallback(()=>{h?d():i({id:r})},[r,i,d,h]);return h&&(u!=null&&u.requestedBy)?t.jsx(Ur,{}):(h?u.status!=="locked":!e||l)?t.jsx("div",{className:""}):t.jsx(Or,{...n,name:(n==null?void 0:n.name)||"Unknown User",email:(n==null?void 0:n.email)||"",lastSaved:(o==null?void 0:o.lastSaved)||"",onTakeOver:f,pageLock:u,realtimePageLockEnabled:h})},$r=()=>{const[e,s]=Le(),n=e.get("lang"),a=ta(n),{setSelectedLang:r}=O.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=m.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(N.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"})})]})})},zr=e=>{const s=oe(),n=ee();return R.useMutation({mutationFn:async a=>n(s,{action:L.UPSERT_LIBRARY_ITEM,data:a}),onSuccess:a=>{e(a)},onError:a=>{console.error("Error saving block:",a),J.toast.error("Failed to save block",{description:a instanceof Error?a.message:"Unknown error"})}})},Vr=e=>{const s=oe(),n=ee();return R.useQuery({queryKey:[Q,"uiBlockDetails",e],enabled:!!e,queryFn:async()=>{if(!e)return null;try{return await n(s,{action:L.GET_LIBRARY_ITEM,data:{id:e}})}catch(a){throw console.error(a),new Error("The block could not be found on the server. It may have been deleted.")}},retry:!1})},Kr=e=>{const s=oe(),n=ee();return R.useMutation({mutationFn:async a=>n(s,{action:L.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"})}})},Hr=({blockId:e,libBlockId:s,isOpen:n,onClose:a,blockName:r,trigger:i})=>{const[l,o]=g.useState(!1),u=O.useUpdateBlocksPropsRealtime(),d=Kr(()=>{u([e],{_libBlockId:void 0}),J.toast.success("Block deleted successfully"),o(!1),a()}),h=()=>{o(!0),d.mutate(s)},f=t.jsxs(c.Button,{type:"button",variant:"destructive",size:"sm",onClick:b=>b.preventDefault(),disabled:l,children:[t.jsx(N.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||f}),t.jsx(c.PopoverContent,{className:"w-72 p-4 z-[9999]",sideOffset:5,align:"center",children:t.jsxs("div",{className:"space-y-3",children:[t.jsx("h4",{className:"font-medium",children:"Delete Block"}),t.jsxs("p",{className:"text-sm",children:["Are you sure you want to delete the block",t.jsxs("span",{className:"font-medium",children:[' "',r,'"']}),"?"]}),t.jsx("p",{className:"text-xs text-muted-foreground",children:"This block will be permanently removed from the library. This action cannot be undone."}),t.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[t.jsx(c.Button,{type:"button",variant:"outline",size:"sm",onClick:a,disabled:l,children:"Cancel"}),t.jsx(c.Button,{type:"button",variant:"destructive",size:"sm",onClick:h,disabled:l,children:l?"Deleting...":"Delete"})]})]})})]})},Wr=({blockId:e,libBlockId:s,blockName:n,size:a="sm",className:r="",close:i})=>{const[l,o]=g.useState(!1);return t.jsx(Hr,{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(N.Trash2,{className:"h-4 w-4 mr-2"}),"Delete"]})})},Qr=()=>{const e=oe(),s=ee(),n=R.useQueryClient(),{data:a=[],isLoading:r,error:i}=R.useQuery({queryKey:[Q,"library-groups"],queryFn:async()=>{try{return await s(e,{action:"GET_LIBRARY_GROUPS"})||[]}catch(u){return console.error("Error fetching library groups:",u),[]}},initialData:[]}),{mutateAsync: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:[Q,"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}},Yr=({value:e,onChange:s})=>{const[n,a]=g.useState(!1),[r,i]=g.useState(""),l=g.useRef(null),{groups:o}=Qr(),[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(p=>p.id===j.id))],[o,u]),f=()=>{const j=r.trim();if(!j)return;const p={id:j,name:j};d(y=>[...y,p]),s(p.id),i(""),a(!1)};g.useEffect(()=>{n&&l.current&&l.current.focus()},[n]);const b=j=>{j.key==="Enter"&&(j.preventDefault(),f())};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:f,children:"Create"})]})]}):t.jsxs("div",{className:"flex gap-2",children:[t.jsxs("select",{className:"w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",value:e,onChange: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(p=>p.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(N.Plus,{className:"h-4 w-4"})})]})},Jr=10*1024*1024,Xr=({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>Jr){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 f=new FileReader;f.onloadend=()=>{s(f.result),a(!1)},f.readAsDataURL(d)}catch(f){console.error("Error reading file:",f),a(!1),J.toast.error("Failed to process image",{description:f instanceof Error?f.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(N.ImageIcon,{className:"h-4 w-4"}),"Select image"]})}),e&&t.jsx(c.Button,{type:"button",variant:"outline",size:"icon",onClick:l,children:t.jsx(N.X,{className:"h-4 w-4"})})]}),e&&t.jsx("div",{className:"rounded-md max-h-[200px] h-[200px] overflow-hidden border aspect-video",children:t.jsx("img",{src:e,alt:"Preview",className:"w-full h-full object-contain"})})]})},ve={...O.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"},Zr=e=>{const{blocks:s,close:n,blockId:a}=e,{getPartailBlocks:r}=O.usePartailBlocksStore(),i=s.find(C=>C._id===a),l=i==null?void 0:i._libBlockId,o=!!l,u=g.useMemo(()=>s.some(C=>C._type==="PartialBlock"||C._type==="GlobalBlock"),[s]),d=g.useMemo(()=>{let C=[];for(const F of s)if(F._type==="PartialBlock"||F._type==="GlobalBlock"){let T=r(F.partialBlockId);F._parent&&(T==null?void 0:T.length)>0&&(T=T.map(U=>(m.isEmpty(U._parent)&&m.set(U,"_parent",F._parent),U))),C=[...C,...T]}else C.push(F);return C},[s,r]),[h,f]=g.useState(""),[b,j]=g.useState(""),[p,y]=g.useState(""),[v,S]=g.useState(""),[E,D]=g.useState({}),[I,_]=g.useState(!1),[M,X]=g.useState(o),[$,P]=g.useState(!1),{hasPermission:G}=O.usePermissions(),H=G(ve.DELETE_LIBRARY_BLOCK),K=O.useUpdateBlocksPropsRealtime(),W=()=>{K([a],{_libBlockId:void 0}),J.toast.success("Block delinked from library"),n()},{data:Z,isLoading:k,isError:q}=Vr(l);g.useEffect(()=>{q&&o&&(P(!0),X(!1))},[q,o]),g.useEffect(()=>{Z&&!k&&(f(Z.name||""),j(Z.group||""),y(Z.description||""),S(Z.preview||""),X(!1))},[Z,k]),g.useEffect(()=>{const C=h.trim().length>=2,F=b.trim()!=="";_(C&&F)},[h,b]);const fe=()=>{const C={};return h.trim()?h.length<2&&(C.name="Name must be at least 2 characters"):C.name="Name is required",b||(C.group="Group is required"),D(C),Object.keys(C).length===0},{resetLibrary:be}=O.useLibraryBlocks({id:""}),ue=zr(C=>{o||K([a],{_libBlockId:C.id}),J.toast.success(`Block ${o?"updated":"saved"} successfully`),be(C.library),n()}),w=async C=>{if(C.preventDefault(),!fe())return;const F=d.map(T=>(m.has(T,"_libBlockId")&&delete T._libBlockId,T));ue.mutate({name:h.trim(),group:b,blocks:F,description:p.trim(),...v&&v.startsWith("data:")?{previewImage:v}:{},...o?{id:l}:{}})},x=ue.isPending;return M||k?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:W,variant:"destructive",children:"Delink Block"})]})]}):t.jsxs("div",{children:[u&&t.jsxs("div",{className:"mb-4 p-3 border border-destructive/50 bg-destructive/10 text-destructive rounded-md flex items-start gap-2",children:[t.jsx(N.AlertCircle,{className:"h-5 w-5 flex-shrink-0 mt-0.5"}),t.jsxs("div",{children:[t.jsx("p",{className:"font-medium",children:"Partial Blocks Detected"}),t.jsx("p",{className:"text-xs mt-1",children:"This block contains one or more Partial Blocks. Partial blocks will be merged into the library block"})]})]}),t.jsxs("form",{onSubmit:w,className:"space-y-4",children:[t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Label,{htmlFor:"name",className:E.name?"text-destructive":"",children:"Name"}),t.jsx(c.Input,{id:"name",placeholder:"Enter block name",value:h,onChange:C=>f(C.target.value),className:E.name?"border-destructive":""}),E.name&&t.jsx("p",{className:"text-xs text-destructive",children:E.name})]}),t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Label,{htmlFor:"group",className:E.group?"text-destructive":"",children:"Group"}),t.jsx(Yr,{value:b,onChange:j}),E.group&&t.jsx("p",{className:"text-xs text-destructive",children:E.group})]}),t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Label,{htmlFor:"description",children:"Description (optional)"}),t.jsx(c.Input,{id:"description",placeholder:"Enter a brief description",className:"resize-none",value:p,onChange:C=>y(C.target.value)})]}),t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Label,{htmlFor:"previewImage",children:"Preview Image (optional)"}),t.jsx(Xr,{value:v,onChange:S})]}),t.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[o&&H&&t.jsx(Wr,{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||!I,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."},ei={SLUG_ALREADY_USED:"This slug is already in use. Please choose a different one."},Ce=()=>{const e=oe(),s=ee();return R.useQuery({queryKey:[Q,L.GET_PAGE_TYPES],initialData:[],queryFn:async()=>s(e,{action:L.GET_PAGE_TYPES})})},oa=e=>{const{data:s}=Ce();return g.useMemo(()=>s==null?void 0:s.find(n=>n.key===e),[s,e])},ti=()=>{const e=oe(),s=ee();return R.useMutation({mutationFn:async({pageType:n,query:a})=>{try{return s(e,{action:L.SEARCH_PAGES,data:{pageType:n,query:Array.isArray(a)&&a.length>0?a[0]:a}})||[]}catch(r){return console.error(r),[]}}})},ca=()=>{const e=oe(),s=R.useQueryClient(),n=ee(),{data:a}=Ce();return R.useMutation({mutationFn:async r=>await n(e,{action:L.CREATE_PAGE,data:r}),onSuccess:(r,i)=>{var o;i&&(i!=null&&i.primaryPage)?(s.invalidateQueries({queryKey:[Q,L.GET_LANGUAGE_PAGES,i==null?void 0:i.primaryPage]}),s.invalidateQueries({queryKey:[Q,L.GET_WEBSITE_PAGES,i==null?void 0:i.lang]})):s.invalidateQueries({queryKey:[Q,L.GET_WEBSITE_PAGES]});const l=i.template?`Page created from "${i.template.name}" template`:i.hasSlug===!1?"New "+((o=m.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=m.find(a,{key:i.pageType});J.toast.error(`Failed to add new ${l!=null&&l.hasSlug?"page":l.name}.`,{description:m.get(ei,r.message,r.message)})}})},rn=()=>{const e=oe(),s=R.useQueryClient(),n=ee(),{data:a}=Ce();return R.useMutation({mutationFn:async r=>await n(e,{action:L.UPDATE_PAGE,data:r}),onSuccess:(r,i)=>{i&&(i!=null&&i.primaryPage||i!=null&&i.seo)?(s.invalidateQueries({queryKey:[Q,L.GET_LANGUAGE_PAGES,i==null?void 0:i.primaryPage]}),s.invalidateQueries({queryKey:[Q,L.GET_WEBSITE_PAGES]})):s.invalidateQueries({queryKey:[Q,L.GET_WEBSITE_PAGES]})},onError:(r,i)=>{const l=m.find(a,{key:i.pageType});J.toast.error(`Failed to update ${l!=null&&l.hasSlug?"page":l.name}.`,{description:r.message})}})},si=()=>{const e=oe(),s=R.useQueryClient(),n=ee(),{data:a}=Ce();return R.useMutation({mutationFn:async r=>n(e,{action:L.DELETE_PAGE,data:{id:r==null?void 0:r.id}}),onSuccess:(r,i)=>{if(r.code==="PAGE_LOCKED"){J.toast.error("Delete not allowed",{description:"Page is currently being edited by another user."});return}i&&(i!=null&&i.primaryPage)?(s.invalidateQueries({queryKey:[Q,L.GET_LANGUAGE_PAGES,i==null?void 0:i.primaryPage]}),s.invalidateQueries({queryKey:[Q,L.GET_WEBSITE_PAGES]})):s.invalidateQueries({queryKey:[Q,L.GET_WEBSITE_PAGES]})},onError:(r,i)=>{const l=m.find(a,{key:i.pageType});J.toast.error(`Failed to delete ${l!=null&&l.hasSlug?"page":l.name}.`,{description:r.message})}})},ni=()=>{const e=oe(),s=R.useQueryClient(),n=ee(),{data:a}=Ce();return R.useMutation({mutationFn:async r=>n(e,{action:L.TAKE_OFFLINE,data:{id:r==null?void 0:r.id}}),onSuccess:(r,i)=>{i&&(i!=null&&i.primaryPage)?s.invalidateQueries({queryKey:[Q,L.GET_LANGUAGE_PAGES,i==null?void 0:i.primaryPage]}):s.invalidateQueries({queryKey:[Q,L.GET_WEBSITE_PAGES]});const l=m.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=m.find(a,{key:i.pageType});J.toast.error(`Failed to take offline ${l!=null&&l.hasSlug?"page":l.name}.`,{description:r.message})}})},ai=()=>{const{savePageAsync:e,saveState:s}=O.useSavePage();return async n=>s!=="SAVED"&&(n.includes("THEME")?n.length>1:n.length>0)?(await e(),!0):!1},ln=()=>{const e=oe(),s=ee(),n=R.useQueryClient(),{data:a}=ke(),r=ai();return R.useMutation({mutationFn:async({ids:i})=>(await r(i),s(e,{action:L.PUBLISH_CHANGES,data:{ids:i}})),onSuccess:()=>{n.invalidateQueries({queryKey:[Q,L.GET_CHANGES]}),n.invalidateQueries({queryKey:[Q,L.GET_WEBSITE_PAGES]}),n.invalidateQueries({queryKey:[Q,L.GET_LANGUAGE_PAGES,a==null?void 0:a.id]})},onError:i=>{console.log("##",i),J.toast.error("Failed to publish pages.")}})},ri=()=>{const e=oe(),s=ee(),n=R.useQueryClient();return R.useMutation({mutationFn:async a=>{var r;return s(e,{action:L.MARK_AS_TEMPLATE,data:{id:(r=a.page)==null?void 0:r.id,name:a.name,description:a.description,pageType:a.pageType,previewImage:a.previewImage}})},onSuccess:()=>{n.invalidateQueries({queryKey:[Q,L.GET_WEBSITE_PAGES]}),J.toast.success("Page marked as template successfully.")},onError:()=>{J.toast.error("Failed to mark page as template.")}})},ii=()=>{const e=oe(),s=ee(),n=R.useQueryClient();return R.useMutation({mutationFn:async a=>s(e,{action:L.UNMARK_AS_TEMPLATE,data:{id:a==null?void 0:a.id}}),onSuccess:()=>{n.invalidateQueries({queryKey:[Q,L.GET_WEBSITE_PAGES]}),J.toast.success("Page unmarked as template successfully.")},onError:()=>{J.toast.error("Failed to unmark page as template.")}})},li=()=>{const e=oe(),s=ee(),n=R.useQueryClient();return R.useMutation({mutationFn:async({id:a,slug:r})=>s(e,{action:L.CHANGE_SLUG,data:{id:a,slug:r}}),onSuccess:(a,{primaryPage:r})=>{J.toast.success(le.SLUG_CHANGE_SUCCESS),r?n.invalidateQueries({queryKey:[Q,L.GET_LANGUAGE_PAGES,r]}):n.invalidateQueries({queryKey:[Q,L.GET_WEBSITE_PAGES]})},onError:()=>{J.toast.error("Failed to change slug")}})};var on={};(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 w=new OffscreenCanvas(1,1),x=w.getContext("2d");x.fillRect(0,0,1,1);var C=w.transferToImageBitmap();try{x.createPattern(C,"no-repeat")}catch{return!1}return!0}();function u(){}function d(w){var x=n.exports.Promise,C=x!==void 0?x:s.Promise;return typeof C=="function"?new C(w):(w(u,u),null)}var h=function(w,x){return{transform:function(C){if(w)return C;if(x.has(C))return x.get(C);var F=new OffscreenCanvas(C.width,C.height),T=F.getContext("2d");return T.drawImage(C,0,0),x.set(C,F),F},clear:function(){x.clear()}}}(o,new Map),f=function(){var w=Math.floor(16.666666666666668),x,C,F={},T=0;return typeof requestAnimationFrame=="function"&&typeof cancelAnimationFrame=="function"?(x=function(U){var se=Math.random();return F[se]=requestAnimationFrame(function V(ie){T===ie||T+w-1<ie?(T=ie,delete F[se],U()):F[se]=requestAnimationFrame(V)}),se},C=function(U){F[U]&&cancelAnimationFrame(F[U])}):(x=function(U){return setTimeout(U,w)},C=function(U){return clearTimeout(U)}),{frame:x,cancel:C}}(),b=function(){var w,x,C={};function F(T){function U(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 U(V,null),x;var Y=Math.random().toString(36).slice(2);return x=d(function(te){function me(z){z.data.callback===Y&&(delete C[Y],T.removeEventListener("message",me),x=null,h.clear(),de(),te())}T.addEventListener("message",me),U(V,Y),C[Y]=me.bind(null,{data:{callback:Y}})}),x},T.reset=function(){T.postMessage({reset:!0});for(var V in C)C[V](),delete C[V]}}return function(){if(w)return w;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{w=new Worker(URL.createObjectURL(new Blob([T])))}catch(U){return typeof console!==void 0&&typeof console.warn=="function"&&console.warn("🎊 Could not load worker",U),null}F(w)}return w}}(),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 p(w,x){return x?x(w):w}function y(w){return w!=null}function v(w,x,C){return p(w&&y(w[x])?w[x]:j[x],C)}function S(w){return w<0?0:Math.floor(w)}function E(w,x){return Math.floor(Math.random()*(x-w))+w}function D(w){return parseInt(w,16)}function I(w){return w.map(_)}function _(w){var x=String(w).replace(/[^0-9a-f]/gi,"");return x.length<6&&(x=x[0]+x[0]+x[1]+x[1]+x[2]+x[2]),{r:D(x.substring(0,2)),g:D(x.substring(2,4)),b:D(x.substring(4,6))}}function M(w){var x=v(w,"origin",Object);return x.x=v(x,"x",Number),x.y=v(x,"y",Number),x}function X(w){w.width=document.documentElement.clientWidth,w.height=document.documentElement.clientHeight}function $(w){var x=w.getBoundingClientRect();w.width=x.width,w.height=x.height}function P(w){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=w,x}function G(w,x,C,F,T,U,se,V,ie){w.save(),w.translate(x,C),w.rotate(U),w.scale(F,T),w.arc(0,0,1,se,V,ie),w.restore()}function H(w){var x=w.angle*(Math.PI/180),C=w.spread*(Math.PI/180);return{x:w.x,y:w.y,wobble:Math.random()*10,wobbleSpeed:Math.min(.11,Math.random()*.1+.05),velocity:w.startVelocity*.5+Math.random()*w.startVelocity,angle2D:-x+(.5*C-Math.random()*C),tiltAngle:(Math.random()*(.75-.25)+.25)*Math.PI,color:w.color,shape:w.shape,tick:0,totalTicks:w.ticks,decay:w.decay,drift:w.drift,random:Math.random()+2,tiltSin:0,tiltCos:0,wobbleX:0,wobbleY:0,gravity:w.gravity*3,ovalScalar:.6,scalar:w.scalar,flat:w.flat}}function K(w,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 C=x.tick++/x.totalTicks,F=x.x+x.random*x.tiltCos,T=x.y+x.random*x.tiltSin,U=x.wobbleX+x.random*x.tiltCos,se=x.wobbleY+x.random*x.tiltSin;if(w.fillStyle="rgba("+x.color.r+", "+x.color.g+", "+x.color.b+", "+(1-C)+")",w.beginPath(),l&&x.shape.type==="path"&&typeof x.shape.path=="string"&&Array.isArray(x.shape.matrix))w.fill(fe(x.shape.path,x.shape.matrix,x.x,x.y,Math.abs(U-F)*.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(U-F)*.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=w.createPattern(h.transform(x.shape.bitmap),"no-repeat");z.setTransform(me),w.globalAlpha=1-C,w.fillStyle=z,w.fillRect(x.x-Y/2,x.y-te/2,Y,te),w.globalAlpha=1}else if(x.shape==="circle")w.ellipse?w.ellipse(x.x,x.y,Math.abs(U-F)*x.ovalScalar,Math.abs(se-T)*x.ovalScalar,Math.PI/10*x.wobble,0,2*Math.PI):G(w,x.x,x.y,Math.abs(U-F)*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,Oe=Math.PI/Ne;Ne--;)B=x.x+Math.cos(ne)*De,ce=x.y+Math.sin(ne)*De,w.lineTo(B,ce),ne+=Oe,B=x.x+Math.cos(ne)*Ae,ce=x.y+Math.sin(ne)*Ae,w.lineTo(B,ce),ne+=Oe;else w.moveTo(Math.floor(x.x),Math.floor(x.y)),w.lineTo(Math.floor(x.wobbleX),Math.floor(T)),w.lineTo(Math.floor(U),Math.floor(se)),w.lineTo(Math.floor(F),Math.floor(x.wobbleY));return w.closePath(),w.fill(),x.tick<x.totalTicks}function W(w,x,C,F,T){var U=x.slice(),se=w.getContext("2d"),V,ie,de=d(function(Y){function te(){V=ie=null,se.clearRect(0,0,F.width,F.height),h.clear(),T(),Y()}function me(){a&&!(F.width===r.width&&F.height===r.height)&&(F.width=w.width=r.width,F.height=w.height=r.height),!F.width&&!F.height&&(C(w),F.width=w.width,F.height=w.height),se.clearRect(0,0,F.width,F.height),U=U.filter(function(z){return K(se,z)}),U.length?V=f.frame(me):te()}V=f.frame(me),ie=te});return{addFettis:function(Y){return U=U.concat(Y),de},canvas:w,promise:de,reset:function(){V&&f.cancel(V),ie&&ie()}}}function Z(w,x){var C=!w,F=!!v(x||{},"resize"),T=!1,U=v(x,"disableForReducedMotion",Boolean),se=i&&!!v(x||{},"useWorker"),V=se?b():null,ie=C?X:$,de=w&&V?!!w.__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),Oe=v(ne,"startVelocity",Number),Is=v(ne,"decay",Number),_s=v(ne,"gravity",Number),Ds=v(ne,"drift",Number),_t=v(ne,"colors",I),Dt=v(ne,"ticks",Number),st=v(ne,"shapes"),is=v(ne,"scalar"),ls=!!v(ne,"flat"),A=M(ne),he=B,Be=[],Ie=w.width*A.x,Ge=w.height*A.y;he--;)Be.push(H({x:Ie,y:Ge,angle:ce,spread:Ne,startVelocity:Oe,color:_t[he%_t.length],shape:st[E(0,st.length)],ticks:Dt,decay:Is,gravity:_s,drift:Ds,scalar:is,flat:ls}));return te?te.addFettis(Be):(te=W(w,Be,ie,Ae,De),te.promise)}function z(ne){var Ae=U||v(ne,"disableForReducedMotion",Boolean),De=v(ne,"zIndex",Number);if(Ae&&Y)return d(function(Oe){Oe()});C&&te?w=te.canvas:C&&!w&&(w=P(De),document.body.appendChild(w)),F&&!de&&ie(w);var B={width:w.width,height:w.height};V&&!de&&V.init(w),de=!0,V&&(w.__confetti_initialized=!0);function ce(){if(V){var Oe={getBoundingClientRect:function(){if(!C)return w.getBoundingClientRect()}};ie(Oe),V.postMessage({resize:{width:Oe.width,height:Oe.height}});return}B.width=B.height=null}function Ne(){te=null,F&&(T=!1,s.removeEventListener("resize",ce)),C&&w&&(document.body.contains(w)&&document.body.removeChild(w),w=null,de=!1)}return F&&!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 k;function q(){return k||(k=Z(null,{useWorker:!0,resize:!0})),k}function fe(w,x,C,F,T,U,se){var V=new Path2D(w),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)*U,Math.cos(se)*U,C,F])),de}function be(w){if(!l)throw new Error("path confetti are not supported in this browser");var x,C;typeof w=="string"?x=w:(x=w.path,C=w.matrix);var F=new Path2D(x),T=document.createElement("canvas"),U=T.getContext("2d");if(!C){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)U.isPointInPath(F,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);C=[De,0,0,De,-Math.round(te/2+V)*De,-Math.round(me/2+ie)*De]}return{type:"path",path:x,matrix:C}}function ue(w){var x,C=1,F="#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 w=="string"?x=w:(x=w.text,C="scalar"in w?w.scalar:C,T="fontFamily"in w?w.fontFamily:T,F="color"in w?w.color:F);var U=10*C,se=""+U+"px "+T,V=new OffscreenCanvas(U,U),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=F,ie.fillText(x,z,ne);var Ae=1/C;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||{}}(),on,!1);const oi=on.exports;on.exports.create;const ci={particleCount:350,spread:120,origin:{y:.6},angle:90},ui={TOP_RIGHT:{angle:225,origin:{x:.9,y:0}},BOTTOM_RIGHT:{angle:100,origin:{x:.9,y:.9}}},Ft=e=>{let s=ui[e];s||(s={});const n={...ci,...s};oi(n)},di=()=>{const[e]=O.useTheme(),{mutate:s,isPending:n}=ln(),{mutateAsync:a,isPending:r}=Xn(),i=()=>{a({settings:{theme:e}})},l=async()=>{await a({settings:{theme:e}}),s({ids:["THEME"]},{onSuccess:()=>{Ft("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"})]})},As=Ee.atom(null),hi=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}=hi(e);return s};function mi(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 fi=e=>e&&Ze(e),An=(e,s)=>{const n=Ze(e||"");return!n||n==="/"?`/${s}`:`${n}/${s}`};function cn({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 f=b=>{const p=b.target.value.replace(/\//g,"").replace(/\s+/g,"-").replace(/[^a-zA-Z0-9-_.]/g,"-").replace(/-+/g,"-").replace(/^-+/,"").toLowerCase(),y=(p.match(/\./g)||[]).length,v=y<=1;y>1?h("Invalid slug. Only one dot (.) is allowed in the slug"):h(null),r&&r(v),u(p),s(p)};return t.jsxs("div",{children:[a&&t.jsx("div",{className:"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:fi(a)})]})}),t.jsxs("div",{className:"relative",children:[t.jsx(c.Input,{disabled:i,value:o,onChange:f,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 ua=({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&&(m.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))]})]}),da=({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})]}),gi=({dynamic:e,isNonSlugPageType:s,isRootPage:n,lang:a,useLanguagePrefix:r,setUseLanguagePrefix:i,isHomePage:l,parentSlug:o,parentHasSelectedLanguagePage:u,slug:d,setSlug:h,setIsSlugValid:f,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(cn,{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:f,fullSlug:b()})]}),ha=({parentHasSelectedLanguagePage:e,name:s,lang:n,slug:a,edit:r,id:i,primaryPageObject:l,pages:o,isNonSlugPageType:u,isHomePage:d,useLanguagePrefix:h,isSlugValid:f,isPending:b})=>{const j=b||!s||!n||o.some(p=>(r?p.id!==i:!0)&&p.parent===(l==null?void 0:l.id)&&p.lang===n)||!u&&!(d&&h)&&(!f||!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(p=>(r?p.id!==i:!0)&&p.parent===(l==null?void 0:l.id)&&p.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."]})})})},xi=({onSubmit:e,edit:s,lang:n,languages:a,name:r,setLang:i,setName:l,primaryPageObject:o,parentHasSelectedLanguagePage:u,id:d,pages:h,isNonSlugPageType:f,isHomePage:b,useLanguagePrefix:j,slug:p,isSlugValid:y,isPending:v})=>t.jsxs("form",{onSubmit:e,children:[t.jsxs("div",{className:"grid gap-4 py-4",children:[t.jsx(ua,{edit:s,lang:n,languages:a,name:r,setLang:i,setName:l,primaryPageObject:o}),t.jsx(da,{lang:n,name:r,setName:l,parentHasSelectedLanguagePage:u})]}),t.jsx(ha,{parentHasSelectedLanguagePage:u,name:r,lang:n,slug:p,edit:s,id:d,primaryPageObject:o,pages:h,isNonSlugPageType:f,isHomePage:b,useLanguagePrefix:j,isSlugValid:y,isPending:v})]}),pi=({loading:e,onSubmit:s,edit:n,lang:a,languages:r,name:i,setLang:l,setName:o,primaryPageObject:u,parentHasSelectedLanguagePage:d,isNonSlugPageType:h,isRootPage:f,useLanguagePrefix:b,setUseLanguagePrefix:j,isHomePage:p,parentSlug:y,slug:v,setSlug:S,isSlugValid:E,setIsSlugValid:D,getSlug:I,isPending:_,id:M,pages:X})=>e?t.jsx("div",{className:"flex h-80 items-center justify-center",children:t.jsx(N.Loader,{className:"animate-spin"})}):h?t.jsx(xi,{onSubmit:s,edit:n,lang:a,languages:r,name:i,setLang:l,setName:o,primaryPageObject:u,parentHasSelectedLanguagePage:d,id:M,pages:X,isNonSlugPageType:h,isHomePage:p,useLanguagePrefix:b,slug:v,isSlugValid:E,isPending:_}):t.jsxs("form",{onSubmit:s,children:[t.jsxs("div",{className:"grid gap-4 py-4",children:[t.jsx(ua,{edit:n,lang:a,languages:r,name:i,setLang:l,setName:o,primaryPageObject:u}),t.jsx(da,{lang:a,name:i,setName:o,parentHasSelectedLanguagePage:d}),t.jsx(gi,{dynamic:u==null?void 0:u.dynamic,isNonSlugPageType:h,isRootPage:f,lang:a,useLanguagePrefix:b,setUseLanguagePrefix:j,isHomePage:p,parentSlug:y,parentHasSelectedLanguagePage:d,slug:v,setSlug:S,isSlugValid:E,setIsSlugValid:D,getSlug:I})]}),t.jsx(ha,{parentHasSelectedLanguagePage:d,name:i,lang:a,slug:v,edit:n,id:M,primaryPageObject:u,pages:X,isNonSlugPageType:h,isHomePage:p,useLanguagePrefix:b,isSlugValid:E,isPending:_})]}),yi=({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,f]=g.useState(""),[b,j]=g.useState(""),[p,y]=g.useState(!0),[v,S]=g.useState(!0),{mutate:E,isPending:D}=ca(),{mutate:I,isPending:_}=rn(),M=D||_,{data:X,isFetching:$}=He(),P=We(),{data:G,isFetching:H}=Ue(a),{data:K=[],isFetching:W}=Ue(o==null?void 0:o.parent),{data:Z=[],isFetching:k}=Ce(),{setSelectedLang:q}=O.useLanguages(),[,fe]=Le(),[,be]=O.useSidebarActivePanel(),ue=$||H||W||k,w=g.useMemo(()=>m.filter(X==null?void 0:X.languages,Y=>!m.find(G,{lang:Y})),[X,G]),x=g.useMemo(()=>Z.find(Y=>Y.key===(o==null?void 0:o.pageType)),[Z,o==null?void 0:o.pageType]),C=!(x!=null&&x.hasSlug),F=(o==null?void 0:o.slug)==="/";g.useEffect(()=>{if(!r&&o&&i&&(f(i),d(`${o.name} - ${Te[i]}`)),!r||!o)return;const Y=G==null?void 0:G.find(ne=>ne.id===e);if(!Y)return;d(Y.name),f(Y.lang);const te=Y.slug||"",{initSlug:me,prefix:z}=mi(te,o);j(me),S(z)},[r,e,G,o,i]),g.useEffect(()=>{i&&f(i)},[i]);const{parentSlug:T,isRootPage:U}=g.useMemo(()=>{if(F||!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,F]),se=g.useMemo(()=>U?!0:!!(K!=null&&K.some(Y=>(Y==null?void 0:Y.lang)===h)),[h,K,U]),V=()=>{let Y="";return U?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:C?"":V(),pageType:o==null?void 0:o.pageType,...r&&{id:e}},me=()=>{!r&&h&&(q(h),ie(h)),be("outline"),n()};r?I(te,{onSuccess:me}):E(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(pi,{id:e,pages:l,loading:ue,onSubmit:de,edit:r,lang:h,languages:w,name:u,setLang:f,setName:d,primaryPageObject:o,parentHasSelectedLanguagePage:se,isNonSlugPageType:C,isRootPage:U,useLanguagePrefix:v,setUseLanguagePrefix:S,isHomePage:F,parentSlug:T,slug:b,setSlug:j,isSlugValid:p,setIsSlugValid:y,getSlug:V,isPending:M})]})})};function ji({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 p=j.target.value;if(!p.startsWith(a)){const I=p.replace(a,""),_=a+I;d(_),s(I);return}const v=p.substring(a.length).replace(/\//g,"").replace(/\s+/g,"-").replace(/[^a-zA-Z0-9-_.]/g,"-").replace(/-+/g,"-").replace(/^-+/,"").toLowerCase(),S=(v.match(/\./g)||[]).length,E=S<=1;S>1?l("Invalid slug. Only one dot (.) is allowed in the slug"):l(null),r&&r(E);const D=a+v;d(D),s(v)},f=()=>{if(o.current){const j=o.current;setTimeout(()=>{const p=a.length;j.setSelectionRange(p,p)},0)}},b=j=>{const p=j.currentTarget;(p.selectionStart||0)<=a.length&&setTimeout(()=>{const v=a.length;p.setSelectionRange(v,v)},0)};return t.jsx("div",{children:t.jsxs("div",{className:"relative",children:[t.jsxs("p",{className:"text-gray-500 text-xs mb-2",children:[`${a}`," is a dynamic segment of slug"]}),t.jsx(c.Input,{ref:o,value:u,onChange:h,onFocus:f,onClick:b,placeholder:n,className:i?"border-red-500":""}),i&&t.jsx("div",{className:"text-red-500 text-xs mt-1",children:i})]})})}const fs=({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 vi({pages:e,selectedParentId:s,onChange:n,className:a,id:r="parentPage"}){const[i,l]=g.useState(!1),[o,u]=g.useState(""),d=O.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=>!m.isEmpty(S.slug)).filter(S=>S.slug!=="/").sort((S,E)=>S.slug.localeCompare(E.slug)),[e]),f=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),p=v=>{if(v==="/")return"/";const S=v.split("/").filter(Boolean);if(S.length<=1){const E=S[0]||"";return`/${Ze(E)}`}return`/${Ze(S[S.length-1])}`},y=()=>{if(!s||s==="none")return"None";const v=h.find(S=>S.id===s);return v?`${v.name} (${p(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:[y(),t.jsx(N.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(N.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(fs,{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(N.Check,{className:Ms("mr-2 h-4 w-4",s?"opacity-0":"opacity-100")})]}),f.map(v=>{const S=j(b(v.slug)),E=p(v.slug),D=t.jsxs("span",{className:"flex items-center text-sm",children:[S,v.name,t.jsxs("span",{className:"text-xs text-gray-500",children:[" (",E,")"]})]});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:D}),t.jsx(N.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),E=S>0?j(S):"",D=p(v.slug);return t.jsxs("option",{value:v.id,children:[E,v.name," (",D,")"]},v.id)})]})]})}const bi=(...e)=>e.filter(Boolean).join(" "),Si=({templates:e,selectedTemplateId:s,onSelectTemplate:n,isLoading:a=!1})=>{const[r,i]=g.useState(""),[l,o]=g.useState(!1),[u,d]=g.useState(""),h=O.useChaiFeatureFlag("enable-add-page-dropdown");if(g.useEffect(()=>{if(s){const y=e.find(v=>v.id===s);i((y==null?void 0:y.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 f={};e.forEach(y=>{const v=y.libraryName;f[v]||(f[v]=[]),f[v].push(y)});const b=Object.entries(f).reduce((y,[v,S])=>{const E=S.filter(D=>D.name.toLowerCase().includes(u.toLowerCase())||v.toLowerCase().includes(u.toLowerCase()));return E.length>0&&(y[v]=E),y},{}),j=e.find(y=>y.id===s),p=j?m.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:[p,t.jsx(N.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(N.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:y=>d(y.target.value)})]})}),t.jsxs(fs,{className:"max-h-[300px] overflow-y-auto",children:[t.jsx(c.CommandEmpty,{children:"No templates found."}),Object.entries(b).map(([y,v])=>t.jsx(c.CommandGroup,{heading:y,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:[m.startCase(S.name),t.jsx(N.Check,{className:bi("mr-2 h-4 w-4",s===S.id?"opacity-100":"opacity-0")})]},S.id))},y))]})]})})]}):t.jsxs("select",{className:"w-full rounded-md border border-gray-300 px-3 py-2",value:s,onChange:y=>n(y.target.value),children:[t.jsx("option",{value:"",children:"No Template"}),Object.entries(f).map(([y,v])=>t.jsx("optgroup",{label:y,children:v.map(S=>t.jsx("option",{value:S.id,children:m.startCase(S.name)},S.id))},y))]}),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"})]})]})},wi=()=>{const e=oe(),s=ee();return R.useQuery({queryKey:[Q,L.GET_LIBRARIES],queryFn:async()=>await s(e,{action:L.GET_LIBRARIES})||[]})},Ni=e=>{const s=oe(),n=ee();return R.useQuery({queryKey:[Q,L.GET_TEMPLATES_BY_TYPE,e],enabled:!!e,queryFn:async()=>{const a=await n(s,{action:L.GET_TEMPLATES_BY_TYPE,data:{pageType:e}});return(e?m.filter(a,{pageType:e}):a)||[]}})},Ei=e=>{const{data:s=[],isLoading:n}=Ni(e),{data:a=[],isLoading:r}=wi(),i=g.useMemo(()=>n||r?[]:s.map(o=>{const u=m.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(()=>m.groupBy(i,"libraryName"),[i]);return{data:i,groupedData:l,isLoading:n||r}},un=()=>{const[,e]=Le();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])},gs=(e,s)=>{const n={seo:{keyword:"",title:"",description:"",noIndex:!1,noFollow:!1,canonicalUrl:"",ogTitle:"",ogDescription:"",jsonLD:""},jsonLD:{}};e!=null&&e.defaultSeo&&(m.has(e.defaultSeo,s)&&m.isObject(e.defaultSeo[s])?n.seo={...n.seo,...e.defaultSeo[s]}:n.seo={...n.seo,...e.defaultSeo});let a={};return e!=null&&e.defaultJSONLD&&(m.has(e.defaultJSONLD,s)&&m.isObject(e.defaultJSONLD[s])?(a=e.defaultJSONLD[s],m.set(n,"seo.jsonLD",JSON.stringify(a))):(a=e.defaultJSONLD,m.set(n,"seo.jsonLD",JSON.stringify(a)))),{seo:n.seo,jsonLD:a}},nt=(...e)=>e.filter(Boolean).join(" ");function Ci({addEditPage:e,additionalPageTypes:s=[],close:n,closePanel:a}){var is,ls;const r=un(),i=!!(e!=null&&e.id),{data:l}=ot(),{mutate:o,isPending:u}=ca(),{mutate:d,isPending:h}=rn(),[f,b]=g.useState(null),[j,p]=g.useState(!0),[y,v]=g.useState((e==null?void 0:e.pageType)??"page"),{hasPermission:S}=O.usePermissions(),E=S(ve.CHANGE_PAGE_TYPE),[D,I]=g.useState(!1),[_,M]=g.useState(""),{selectedLang:X,fallbackLang:$}=O.useLanguages(),P=X||$,[G,H]=g.useState(""),[K,W]=g.useState(!1),Z=g.useMemo(()=>{const A=s.find(he=>he.key===y);return(A==null?void 0:A.hasSlug)===!1},[y,s]),[k,q]=g.useState((e==null?void 0:e.parent)??""),[fe,be]=g.useState((e==null?void 0:e.name)??""),[ue,w]=g.useState((e==null?void 0:e.dynamic)??!1),[x,C]=g.useState(ue?"":((e==null?void 0:e.slug)??"").split("/").pop()||""),[F,T]=g.useState((e==null?void 0:e.dynamicSlugCustom)??""),[U,se]=g.useState(!0),[V,ie]=g.useState(""),{data:de,isLoading:Y}=Ei(y),te=u||h,me=O.useChaiFeatureFlag("enable-add-page-dropdown"),z=s.find(A=>A.key===y),ne=A=>{if(i&&y!==A){M(A),I(!0),H(""),W(!1);return}v(A),H(""),W(!1)},Ae=()=>{v(_),I(!1),w(!1)},De=A=>{w(A),A?C(""):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(/^\/+/,"");C(Ie)}else C(x.replace(/^\/+/,""))}else C(x?`${x}`:"")},ce=A=>{ie(A)},Ne=()=>fe.trim()?ue&&!m.isEmpty(x)?(b("Slug must be empty when using dynamic slug"),!1):ue&&!U?(b("Dynamic slug is invalid"),!1):!0:(J.toast.error("Name is required"),!1),Oe=()=>{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)}})},Is=(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(os=>Ie===`/${os}`||(Ie==null?void 0:Ie.startsWith(`/${os}/`)))?(b("Slugs cannot start with a language code for primary page"),!1):!0},_s=(A,he)=>{const Be=Ze(he),Ie=An(Be,A),Ge={pageType:y,name:fe,slug:Ie.replace(/\/$/,""),parent:k,dynamic:ue,hasSlug:!0,template:V||void 0,tracking:{},seo:{},jsonLD:{}};if(ue&&(Ge.dynamicSlugCustom=F),i)d({id:e==null?void 0:e.id,...Ge},{onSuccess:()=>{J.toast.success("Page updated successfully"),n()}});else{const Ve=m.find(s,{key:y});Ve!=null&&Ve.trackingDefault&&(Ge.tracking=Ve.trackingDefault);const{seo:os,jsonLD:mr}=gs(Ve,P);m.set(Ge,"seo",os),m.set(Ge,"jsonLD",mr),o(Ge,{onSuccess:fr=>{n(),r(fr.page.id,a)}})}},Ds=()=>{const A={pageType:y,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=m.find(s,{key:y});he!=null&&he.trackingDefault&&(A.tracking=he.trackingDefault);const{seo:Be,jsonLD:Ie}=gs(he,P);m.set(A,"seo",Be),m.set(A,"jsonLD",Ie),o(A,{onSuccess:Ge=>{var Ve;(Ve=Ge==null?void 0:Ge.page)!=null&&Ve.id&&r(Ge.page.id,a),n()}})}},_t=A=>{if(A.preventDefault(),b(null),!!Ne()){if(!(z!=null&&z.hasSlug)){Oe();return}if(k&&k!=="none"){const he=l==null?void 0:l.find(Ie=>Ie.id===k),Be=(he==null?void 0:he.slug)||"";if(!Is(x,Be))return;_s(x,Be)}else Ds()}},{pagesType:Dt,partialsType:st}=g.useMemo(()=>{const A=he=>G?he.name.toLowerCase().includes(G.toLowerCase())||he.key.toLowerCase().includes(G.toLowerCase()):!0;return{pagesType:s.filter(he=>he.hasSlug!==!1&&A(he)),partialsType:s.filter(he=>he.hasSlug===!1&&A(he))}},[s,G]);return z!=null&&z.hasSlug?t.jsxs("form",{onSubmit:_t,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:W,children:[t.jsx(c.PopoverTrigger,{asChild:!0,children:t.jsxs(c.Button,{variant:"outline",role:"combobox",disabled:i&&!E,className:nt("w-full justify-between",i&&!E?"cursor-not-allowed text-gray-500":""),children:[(z==null?void 0:z.name)||"Select page type",t.jsx(N.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(N.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:G,onChange:A=>H(A.target.value)})]})}),t.jsxs(fs,{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(N.Check,{className:nt("mr-2 h-4 w-4",y===A.key?"opacity-100":"opacity-0")})]},A.key))}):t.jsx(c.CommandGroup,{heading:"Pages",children:Dt.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(N.Check,{className:nt("mr-2 h-4 w-4",y===A.key?"opacity-100":"opacity-0")})]},A.key))}):t.jsxs(t.Fragment,{children:[Dt.length>0&&t.jsx(c.CommandGroup,{heading:"Pages",children:Dt.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(N.Check,{className:nt("mr-2 h-4 w-4",y===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(N.Check,{className:nt("mr-2 h-4 w-4",y===A.key?"opacity-100":"opacity-0")})]},A.key))})]})]})]})})]}):t.jsx("select",{id:"pageType",value:y,disabled:i&&!E,onChange:A=>ne(A.target.value),className:`w-full rounded-md border border-gray-300 px-3 py-2 ${i&&!E?"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))})]})}),D&&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:()=>I(!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(Si,{templates:de,selectedTemplateId:V,onSelectTemplate:ce,isLoading:Y})]}),t.jsx(vi,{pages:l,selectedParentId:k,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)&&k&&k!=="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(ji,{value:F,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(cn,{value:x,onChange:C,placeholder:k&&k!=="none"?"Enter page slug":y==="page"?"Leave empty for home page":"Required - e.g. your-slug",parentSlug:k&&k!=="none"?(ls=l==null?void 0:l.find(A=>A.id===k))==null?void 0:ls.slug:void 0,onValidationChange:p}),f&&t.jsx("p",{className:"text-xs text-red-500",children:f})]}),t.jsx(c.Button,{disabled:te||!j&&(!(z!=null&&z.dynamicSegments)||!ue)||ue&&!U,type:"submit",className:"w-full",children:i?te?"Updating...":"Update page":te?"Creating...":"Create Page"})]}):t.jsxs("form",{onSubmit:_t,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:W,children:[t.jsx(c.PopoverTrigger,{asChild:!0,children:t.jsxs(c.Button,{variant:"outline",role:"combobox",disabled:i&&!E,className:nt("w-full justify-between",i&&!E?"cursor-not-allowed text-gray-500":""),children:[(z==null?void 0:z.name)||"Select page type",t.jsx(N.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(N.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:G,onChange:A=>H(A.target.value)})]})}),t.jsxs(fs,{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),W(!1)},className:"flex cursor-pointer items-center justify-between",children:[A.name,t.jsx(N.Check,{className:nt("mr-2 h-4 w-4",y===A.key?"opacity-100":"opacity-0")})]},A.key))})]})]})})]}):t.jsx("select",{id:"pageType",value:y,disabled:i&&!E,onChange:A=>ne(A.target.value),className:`w-full rounded-md border border-gray-300 px-3 py-2 ${i&&!E?"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))})}),D&&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:()=>I(!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:(is=s.find(A=>A.key===y))==null?void 0:is.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 dn=({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(Ci,{closePanel:n,addEditPage:e,close:()=>s(void 0),additionalPageTypes:a??[]})]})})};function Ts({page:e,onClose:s}){const[,n]=Le(),{mutate:a,isPending:r}=si(),{data:i}=Ce(),{setSelectedLang:l,fallbackLang:o}=O.useLanguages(),[,u]=O.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(f=>f.key===(e==null?void 0:e.pageType));return t.jsx(c.Dialog,{open:!!e,onOpenChange:s,children:t.jsxs(c.DialogContent,{children:[t.jsxs(c.DialogHeader,{children:[t.jsx(c.DialogTitle,{children:"Confirm Deletion"}),t.jsxs(c.DialogDescription,{className:"py-4 text-slate-500",children:[t.jsxs("div",{children:["Are you sure you want to remove ",t.jsx("b",{children:(e==null?void 0:e.name)??(e==null?void 0:e.slug)})," ",h!=null&&h.hasSlug?(h==null?void 0:h.name)+"?":`page? ${e!=null&&e.primaryPage?"":"This will also delete all associated language pages."}`]}),e.lang&&t.jsxs("div",{className:"py-2 text-sm",children:["Language:"," ",t.jsx("span",{className:"font-medium text-gray-500",children:m.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 Ai=()=>{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:[Q,L.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"})}})},hn=({page:e,onClose:s})=>{const{mutate:n,isPending:a}=Ai(),[r,i]=g.useState(null),[l,o]=g.useState(`${e.name} (Copy)`),u=m.isEmpty(e.slug),[d,h]=g.useState(u?"":`${e.slug.split("/").pop()}-copy`),f=u?"":m.initial(e.slug.split("/")).join("/"),[b,j]=g.useState(!1),p=y=>{if(y.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=`${f}/${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:p,className:"space-y-4",children:[t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Label,{htmlFor:"name",className:"text-sm",children:"Name"}),t.jsx(c.Input,{id:"name",value:l,onChange:y=>o(y.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(cn,{value:d,onChange:y=>h(y),parentSlug:f,onValidationChange:y=>{i(y?null:"Invalid slug")}})]}),r&&t.jsxs(c.Alert,{variant:"destructive",className:"py-2",children:[t.jsx(N.AlertCircle,{className:"h-4 w-4"}),t.jsx("span",{className:"text-sm",children: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"})]})]})]})})},Ti=1*1024*1024,mn=({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),f=ri(),{data:b}=Ce(),j=b==null?void 0:b.find(D=>D.key===e.pageType),p=(j==null?void 0:j.name)||m.startCase(e.pageType),y=g.useCallback(D=>{var _;const I=(_=D.target.files)==null?void 0:_[0];if(I){if(I.size>Ti){J.toast.error("File too large",{description:`Maximum file size is 1MB. Selected file is ${(I.size/1024).toFixed(2)}KB.`}),h.current&&(h.current.value="");return}try{d(!0);const M=new FileReader;M.onloadend=()=>{o(M.result),d(!1)},M.readAsDataURL(I)}catch(M){console.error("Error reading file:",M),d(!1),J.toast.error("Failed to process image",{description:M instanceof Error?M.message:"Unknown error"})}}},[]),v=()=>{o(""),h.current&&(h.current.value="")},S=()=>{var D;(D=h.current)==null||D.click()},E=()=>{a(!0),f.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(N.Tag,{className:"w-4 h-4 text-slate-500"}),t.jsx("span",{className:"font-medium text-slate-500",children:"Page Name:"}),t.jsx("span",{className:"font-semibold",children:m.startCase(e.name)})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(N.File,{className:"w-4 h-4 text-slate-500"}),t.jsx("span",{className:"font-medium text-slate-500",children:"Type:"}),t.jsx("span",{className:"font-semibold",children:p})]})]}),t.jsxs("div",{children:[t.jsx(c.Label,{htmlFor:"description",className:"text-xs font-medium",children:"Description (Optional)"}),t.jsx(c.Textarea,{id:"description",placeholder:"Describe this template's purpose",className:"text-xs resize-none h-24 mt-1",value:r,onChange:D=>i(D.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:y,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(N.ImageIcon,{className:"h-4 w-4"}),"Select image"]})}),l&&t.jsx(c.Button,{type:"button",variant:"outline",size:"icon",onClick:v,children:t.jsx(N.X,{className:"h-4 w-4"})})]}),l&&t.jsx("div",{className:"rounded-md overflow-hidden border aspect-video",children:t.jsx("img",{src:l,alt:"Preview",className:"w-full h-full max-h-[200px] object-contain"})}),t.jsx("p",{className:"text-xs text-muted-foreground",children:"max 1mb"})]})]})]}),t.jsxs(c.DialogFooter,{className:n?"opacity-75 pointer-events-none":"",children:[t.jsx(c.Button,{variant:"outline",onClick:D=>{D.stopPropagation(),s()},children:"Cancel"}),t.jsx(c.Button,{variant:"default",disabled:n,onClick:E,children:"Mark as template"})]})]})})},fn=({page:e,setDuplicatePage:s,setAddEditPage:n,setUnpublishPage:a,setDeletePage:r,setMarkAsTemplate:i,setUnmarkAsTemplate:l,children:o,isLanguagePage:u})=>{const{hasPermission:d}=O.usePermissions(),{data:h}=Ce(),f=g.useMemo(()=>m.find(h,{key:e.pageType}),[h,e.pageType]),b=g.useMemo(()=>!!e.isTemplate,[e.isTemplate]),j=g.useMemo(()=>!!(f!=null&&f.hasSlug),[f==null?void 0:f.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:y=>y.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:y=>{y.stopPropagation(),s(e)},children:[t.jsx(N.CopyPlusIcon,{className:"size-3"}),"Duplicate page"]}),d(ve.EDIT_PAGE)&&t.jsxs(c.DropdownMenuItem,{className:"flex cursor-pointer items-center gap-2",onClick:y=>{y.stopPropagation(),n({...e,global:!(f!=null&&f.hasSlug)})},children:[t.jsx(N.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:y=>{y.stopPropagation(),a(e)},children:[t.jsx(N.Power,{className:"size-3"}),le.UNPUBLISH]}),d(ve.DELETE_PAGE)&&t.jsxs(c.DropdownMenuItem,{className:"flex cursor-pointer items-center gap-2",onClick:y=>{y.stopPropagation(),r(e)},children:[t.jsx(N.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:y=>{y.stopPropagation(),l(e)},children:[t.jsx(N.SquareLibrary,{className:"size-3"}),le.UNMARK_AS_TEMPLATE]}):t.jsxs(c.DropdownMenuItem,{className:"flex cursor-pointer items-center gap-2",onClick:y=>{y.stopPropagation(),i(e)},children:[t.jsx(N.SquareLibrary,{className:"size-3"}),le.MARK_AS_TEMPLATE]})})]})]})},gn=({page:e,onClose:s})=>{const[n,a]=g.useState(!1),r=ii(),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"})]})]})})},rs=({page:e,onClose:s})=>{const{mutate:n,isPending:a}=ni(),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})]})]})})},Pi=Wn("expandedPagesState",[]),xn=e=>m.flatMap(e,s=>[s,...s.children?xn(s.children):[]]),ki=(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)||[]},ma=(e,s)=>{if(!s)return[];const n=xn(e),a=m.find(n,r=>r.id===s);if(a){if(a.parent)return[...ma(e,a.parent),s];const r=ki(e,s);if(!m.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&&!m.isEmpty(i.children)&&n(i.children,l)})};return n(e),Array.from(s)},Lt=e=>{const[s,n]=Ee.useAtom(Pi),a=e?m.includes(s,e):!1,r=g.useCallback(()=>{n(d=>a?m.filter(d,h=>h!==e):[...d,e])},[n,a,e]),i=g.useCallback((d,h)=>{if(!h||m.isEmpty(d))return;const f=xn(d),b=ma(f,h);if(!Array.isArray(b)||m.isEmpty(b))return;const j=b.slice(0,-1);m.isEmpty(j)||n(p=>m.uniq([...p,...j]))},[n]),l=g.useCallback(d=>{if(m.isEmpty(d))return;const h=Li(d);m.isEmpty(h)||n(f=>m.union(f,h))},[n]),o=g.useCallback(d=>{if(m.isEmpty(d))return;const h=m.flatMap(d,f=>{const b=j=>[j.id,...j.children?m.flatMap(j.children,b):[]];return b(f)});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)?[]:m.isEmpty(s)?e:m.compact(m.filter(e,n=>{const a=m.toLower(s);return m.includes(m.toLower((n==null?void 0:n.name)||""),a)||m.includes(m.toLower((n==null?void 0:n.slug)||""),a)})),Ii=(e,s)=>{const n=new Set,a=m.keyBy(e,"id");return s.forEach(r=>{let i=r;for(;i.parent&&a[i.parent];)n.add(i.parent),i=a[i.parent]}),Array.from(n).map(r=>a[r])},Us=(e,s,n)=>m.isEmpty(s)?e:e.map(a=>{if(!n(a.pageType))return{...a,shouldExpandOnSearch:!0,children:a.children?Us(a.children,s,n):[]};const r=a.children&&a.children.some(i=>m.includes(m.toLower(i.name||""),m.toLower(s))||m.includes(m.toLower(i.slug||""),m.toLower(s)));return{...a,shouldExpandOnSearch:r,children:a.children?Us(a.children,s,n):[]}}),_i=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},fa=e=>!e||!e.length?[]:[...e].sort((n,a)=>(n.name||"").localeCompare(a.name||"")).map(n=>({...n,children:n.children?fa(n.children):[]})),ga=(e,s,n,a)=>{if(!e||!e.length)return[];let r=e;if(n!=="all"&&(r=m.compact(m.filter(e,{pageType:n}))),m.isEmpty(s))r=Tn(r,s);else{const h=Tn(r,s),f=Ii(e,h);r=m.uniqBy([...h,...f],"id")}const i=fa(_i(r)),l=Us(i,s,a),o=m.filter(l,h=>a(h.pageType)).sort((h,f)=>(h.name||"").localeCompare(f.name||"")),u=m.keyBy(m.filter(l,h=>!a(h.pageType)),"pageType"),d=Object.values(m.mapValues(u,(h,f)=>({...h,name:m.startCase(f),isPartialGroup:!0,children:l.filter(b=>b.pageType===f)})));return[...o,...d]},Di=({parentSlug:e,page:s,active:n,closePanel:a,setUnpublishPage:r,setDeletePage:i,setAddEditPage:l,setMarkAsTemplate:o,setUnmarkAsTemplate:u,setDuplicatePage:d,hasChildren:h,isExpanded:f,onToggleExpand:b})=>{const j=un(),{data:p}=Ce(),[,y]=O.useSidebarActivePanel(),v=g.useMemo(()=>m.find(p,{key:s.pageType}),[p,s.pageType]),S=g.useMemo(()=>{const _=m.get(s,"slug",""),M=e?Ze(e):"",X=M?_.replace(M,""):_;return X||"/"},[s,e]),E=g.useMemo(()=>!!s.isTemplate,[s.isTemplate]),D=g.useCallback(()=>{y("outline"),j(m.get(s,"id"),a)},[j,a,s,y]),I=g.useCallback(_=>{_.stopPropagation(),b()},[b]);return t.jsxs("div",{onClick:D,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:I,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(N.ChevronRight,{size:16,className:`h-5 w-4 transition-transform duration-200 ${f?"rotate-90":""}`})}),s.dynamic?t.jsx("div",{className:"h-4 w-4 stroke-[1] text-slate-500",children:t.jsx(N.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(N.File,{className:"h-4 w-4 stroke-[1] text-slate-500"}):t.jsx(N.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:[m.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}),E&&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(Fr,{currentEditor:s.currentEditor}),t.jsx(fn,{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(N.MoreHorizontal,{className:"h-4 w-4",onClick:_=>_.stopPropagation()})})})]})]})},Bi=({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(m.get(T,"name","")).toLowerCase().includes(l.toLowerCase())||String(m.get(T,"key","")).toLowerCase().includes(l.toLowerCase()):!0,[f,b]=g.useState(null),[j,p]=g.useState(null),[y,v]=g.useState(null),[S,E]=g.useState(null),{data:D,isFetching:I}=ot(),[_,M]=g.useState(""),{hasPermission:X}=O.usePermissions(),{updateForSelectedPage:$,expandPagesOnSearch:P,expandAll:G,collapseAll:H}=Lt(null),[K,W]=Le(),Z=K.get("page"),k=g.useRef(null),{data:q}=Ce(),fe=O.useChaiFeatureFlag("enable-add-page-dropdown"),be=g.useCallback(T=>{var U;return(U=m.find(q,{key:T}))==null?void 0:U.hasSlug},[q]);g.useEffect(()=>{if(!m.isEmpty(_))return;const T=sessionStorage.getItem("pageTypeFilter")||"all";!m.isEmpty(q)&&T&&(m.find(q,{key:T})?M(T):M("all"))},[q,_]);const ue=T=>{M(T),sessionStorage.setItem("pageTypeFilter",T),o("")},w=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()}`),W(V),window.dispatchEvent(new PopStateEvent("popstate")),e()},[W,e]);g.useEffect(()=>{if(Z&&!I){const T=m.find(D,{id:Z});T&&(T!=null&&T.pageType)?s(U=>[...U,T==null?void 0:T.pageType]):(window.history.replaceState(null,"","/"),W(new URLSearchParams({})),window.dispatchEvent(new PopStateEvent("popstate")))}},[D,Z,I,W]);const x=g.useMemo(()=>D?ga(D,r,_,be):[],[D,r,_,be]);g.useEffect(()=>{Z&&!I&&!m.isEmpty(x)&&($(x,Z),k.current&&k.current.scrollIntoView({behavior:"smooth",block:"end"}))},[Z,I,x,$]),g.useEffect(()=>{!m.isEmpty(r)&&!m.isEmpty(x)&&P(x)},[r,x,P]);const C=g.useCallback(()=>{G(x)},[G,x]),F=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(N.Search,{strokeWidth:2.5,className:"absolute left-3 top-2.5 h-4 w-4 text-gray-400"}),t.jsx(c.Input,{placeholder:"Search pages...",className:"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)}),!m.isEmpty(_)&&t.jsxs(c.Select,{value:_,onValueChange:ue,children:[t.jsx(c.SelectTrigger,{className:`${_==="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(N.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"),!m.isEmpty(m.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"}),m.map([...m.filter(q,T=>T.hasSlug&&h(T))].sort((T,U)=>m.get(T,"name","").localeCompare(m.get(U,"name",""))),T=>t.jsx(c.SelectItem,{value:m.get(T,"key"),children:m.get(T,"name")},m.get(T,"key")))]}),!m.isEmpty(m.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"}),m.map([...m.filter(q,T=>!T.hasSlug&&h(T))].sort((T,U)=>m.get(T,"name","").localeCompare(m.get(U,"name",""))),T=>t.jsx(c.SelectItem,{value:m.get(T,"key"),children:m.get(T,"name")},m.get(T,"key")))]}),m.isEmpty(m.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:C,className:"p-1 text-gray-500",children:t.jsx(N.ChevronsUpDown,{})}),t.jsx(c.Button,{variant:"outline",size:"icon",onClick:F,className:"p-1 text-gray-500",children:t.jsx(N.ChevronsDownUp,{})})]})]}),I?t.jsx("div",{className:"space-y-2",children:m.map([...Array(5).keys()],T=>t.jsx("div",{className:"h-9 w-full animate-pulse rounded bg-gray-200"},T))}):m.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(N.File,{className:"h-6 w-6 stroke-[1]"}),"Empty List!",t.jsx("span",{className:"font-light",children:"Add new page to start"})]}):t.jsx("div",{className:"h-[70vh] space-y-2 overflow-y-auto text-sm text-slate-700",children:m.map(x,T=>{const U=T.id===Z;return t.jsx("div",{ref:U?k:null,children:t.jsx(xa,{item:T,currentPage:Z,close:e,setUnpublishPage:b,setDeletePage:d,setAddEditPage:p,setMarkAsTemplate:v,setUnmarkAsTemplate:E,setDuplicatePage:a,level:0})},`page-item-${T.id}`)})})]}),X(ve.ADD_PAGE)&&t.jsxs(c.Button,{className:"flex gap-x-2 text-sm",onClick:()=>{p({slug:"",name:"",pageType:_==="all"?"page":_})},children:[t.jsx(N.Plus,{className:"h-4 w-4"})," Add New"]}),j&&t.jsx(dn,{closePanel:e,editPage:w,addEditPage:j,setAddEditPage:p}),u&&t.jsx(Ts,{page:u,onClose:()=>d(null)}),f&&t.jsx(rs,{page:f,onClose:()=>b(null)}),y&&t.jsx(mn,{page:y,onClose:()=>v(null)}),S&&t.jsx(gn,{page:S,onClose:()=>E(null)}),n&&t.jsx(hn,{page:n,onClose:()=>a(null)})]})},xa=({item:e,currentPage:s,close:n,setUnpublishPage:a,setDeletePage:r,setAddEditPage:i,setMarkAsTemplate:l,setUnmarkAsTemplate:o,setDuplicatePage:u,parentSlug:d,level:h=0})=>{const f=!m.isEmpty(e==null?void 0:e.children),{isExpanded:b,toggleExpanded:j}=Lt(e==null?void 0:e.id);return t.jsxs("div",{className:"border-0",children:[t.jsx(Di,{closePanel:n,setUnpublishPage:a,setDeletePage:r,setAddEditPage:i,setMarkAsTemplate:l,setUnmarkAsTemplate:o,setDuplicatePage:u,active:s===e.id,page:e,parentSlug:d,hasChildren:f,isExpanded:b,onToggleExpand:j}),f&&b&&t.jsx("div",{className:"bg-white pl-6 pt-2",children:m.map(m.get(e,"children",[]),p=>t.jsx(xa,{item:p,currentPage:s,close:n,setUnpublishPage:a,setDeletePage:r,setAddEditPage:i,setMarkAsTemplate:l,setUnmarkAsTemplate:o,setDuplicatePage:u,parentSlug:e.slug,level:h+1},p.id||`child-${h}-${p.key}`))})]},e.id||`level-${h}-${e.key}`)},Mi=({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(m.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(N.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"}),!m.isEmpty(m.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"}),m.map([...m.filter(r,l=>l.hasSlug&&i(l))].sort((l,o)=>m.get(l,"name","").localeCompare(m.get(o,"name",""))),l=>t.jsx(c.SelectItem,{value:m.get(l,"key"),children:m.get(l,"name")},m.get(l,"key")))]}),!m.isEmpty(m.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"}),m.map([...m.filter(r,l=>!l.hasSlug&&i(l))].sort((l,o)=>m.get(l,"name","").localeCompare(m.get(o,"name",""))),l=>t.jsx(c.SelectItem,{value:m.get(l,"key"),children:m.get(l,"name")},m.get(l,"key")))]}),m.isEmpty(m.filter(r,i))&&t.jsx("div",{className:"px-3 py-2 text-center text-sm text-gray-500",children:"No matching page types found"})]})]})},Gi=({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(N.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(Mi,{selectedPageType:n,setSelectedPageType:a})]}),Ri=({pages:e})=>{const{expandAll:s,collapseAll:n,expandedPages:a}=Lt(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(N.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(N.ChevronsDownUp,{})})}),t.jsx(c.TooltipContent,{children:"Collapse All"})]})]})},pa=({languages:e,selectedLanguage:s,setSelectedLanguage:n})=>{const a=We();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(N.Star,{size:4,className:`p-0.5 ${s===a?"fill-white":"fill-black"}`}),Te[r]||""]},r))})},Fi=()=>{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:[Q,L.GET_WEBSITE_PAGES]}),className:"h-6 w-6",children:t.jsx(N.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})=>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(Gi,{search:s,setSearch:n,selectedPageType:o,setSelectedPageType:u}),t.jsx(Ri,{pages:e}),t.jsxs(c.Button,{variant:"default",onClick:r,className:"rounded px-3 font-normal",children:[t.jsx(N.Plus,{strokeWidth:2,className:"stroke-white stroke-[3]"}),t.jsx("span",{className:"font-normal text-white",children:"Add Page"})]})]}),t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx(pa,{languages:a,selectedLanguage:i,setSelectedLanguage:l}),t.jsx(Fi,{})]})]});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 Ui=({page:e})=>{var a,r;const{isExpanded:s,toggleExpanded:n}=Lt(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(N.ChevronRight,{size:12,className:`stroke-[4] transition-transform duration-200 ${s?"rotate-90":""}`})})},qi=({page:e,pageType:s})=>t.jsx("div",{className:"flex h-full items-center justify-center gap-x-1",children:e.dynamic?t.jsx(N.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(N.File,{size:12,className:"stroke-[1] text-slate-500"}):t.jsx(N.Globe,{size:12,className:"stroke-[1] text-slate-500"})}),$i=({isOnline:e})=>t.jsx("div",{className:`h-2 w-2 rounded-full ${e?"bg-green-300":"bg-gray-300"}`}),zi=({page:e,pageTypes:s,currentPage:n,onClickAction:a,languagePages:r,selectedLanguage:i})=>{const l=We(),o=n===e.id,u=!!e.isTemplate,d=g.useMemo(()=>m.find(s,{key:e.pageType}),[s,e.pageType]);let h=m.get(r,e==null?void 0:e.id);h=m.get(h,"lang")===i?h:null;const f=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 p=g.useMemo(()=>{const y="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 f?`${y} ${v}`:`${y} bg-gray-100 opacity-50 group-hover:border-gray-200 border-transparent group-hover:bg-blue-100`},[f,o]);return t.jsxs("div",{className:"group relative",children:[t.jsxs("div",{onClick:()=>f&&a("select",e==null?void 0:e.id),className:p,children:[t.jsx(Ui,{page:e}),!e.isPartialGroup&&t.jsx($i,{isOnline:e.online}),t.jsx(qi,{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(N.NotepadText,{size:16})})}),!e.isPartialGroup&&f&&t.jsx("div",{className:"duration absolute right-0.5 top-[3px]",children:t.jsx(fn,{isLanguagePage:!!h,page:h||e,setDuplicatePage:y=>a("duplicate",y),setAddEditPage:y=>a("edit",h||y),setUnpublishPage:y=>a("unpublish",y),setDeletePage:y=>a("delete",h||y),setMarkAsTemplate:y=>a("markAsTemplate",y),setUnmarkAsTemplate:y=>a("unmarkAsTemplate",y),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(N.MoreHorizontal,{className:"h-4 w-4",onClick:y=>y.stopPropagation()})})})})]}),t.jsx(t.Fragment,{children:!f&&!e.isPartialGroup&&t.jsxs("button",{onClick:y=>{y.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(N.Plus,{size:12,className:"stroke-[3]"})," ",t.jsxs("span",{className:"text-[10px]",children:["Add ",m.get(Te,i)," Page"]})]})})]})},ya=({pages:e,tier:s,pageTypes:n,currentPage:a,onClickAction:r,languagePages:i,selectedLanguage:l})=>{const{expandedPages:o}=Lt();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(zi,{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(ya,{pages:u.children,tier:s+1,pageTypes:n,currentPage:a,onClickAction:r,languagePages:i,selectedLanguage:l})]},u.id))})},Vi=({close:e})=>{const{languages:s,setSelectedLang:n,selectedLang:a}=O.useLanguages(),{data:r}=Ce(),{data:i,isFetching:l}=ot(),[o,u]=Le(),{updateForSelectedPage:d}=Lt(null),h=We(),f=o.get("page"),[b,j]=g.useState(""),[p,y]=g.useState(null),[v,S]=g.useState(null),[E,D]=g.useState(null),[I,_]=g.useState(null),[M,X]=g.useState(""),[$,P]=g.useState(null),[G,H]=g.useState(null),[K,W]=g.useState(a||h),[,Z]=Ee.useAtom(As),{data:k,isFetching:q}=Dr(K),fe=g.useCallback(x=>{var C;return(C=m.find(r,{key:x}))==null?void 0:C.hasSlug},[r]),be=g.useMemo(()=>i?ga(i,b,M,fe):[],[i,fe,b,M]);g.useEffect(()=>{if(!m.isEmpty(M))return;const x=sessionStorage.getItem("pageTypeFilter")||"all";!m.isEmpty(r)&&x&&(m.find(r,{key:x})?X(x):X("all"))},[r,M]),g.useEffect(()=>{f&&!l&&(m.find(i,{id:f})||(window.history.replaceState(null,"","/"),u(new URLSearchParams({})),window.dispatchEvent(new PopStateEvent("popstate"))))},[i,f,l,u]),g.useEffect(()=>{f&&!l&&!m.isEmpty(be)&&d(be,f)},[f,l,be,d]);const ue=g.useCallback(x=>{const C=new URLSearchParams({page:x});K!==h&&C.set("lang",K),n(K),window.history.pushState({},"",`?${C.toString()}`),u(C),window.dispatchEvent(new PopStateEvent("popstate")),e()},[e,u,K,n,h]),w=(x,C)=>{var F;if(C)switch(x){case"add":S(C);break;case"select":ue(C);break;case"edit":K!==h?Z({edit:!0,id:C==null?void 0:C.id,primaryPage:C==null?void 0:C.primaryPage}):S(C);break;case"delete":y(C);break;case"unpublish":D(C);break;case"markAsTemplate":_(C);break;case"unmarkAsTemplate":H(C);break;case"duplicate":P(C);break;case"addLanguagePage":Z({edit:!1,primaryPage:((F=C==null?void 0:C.page)==null?void 0:F.id)||"",preselectedLang:(C==null?void 0:C.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:W,selectedPageType:M,setSelectedPageType:X,onAddPage:x=>w("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:m.map([...Array(15).keys()],x=>t.jsx("div",{className:"h-7 w-full animate-pulse rounded border border-gray-300 bg-gray-200"},x))}):m.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(N.File,{className:"h-6 w-6 stroke-[1]"}),"Empty List!",t.jsx("span",{className:"font-light",children:"Add new page to start"})]}):t.jsx(ya,{tier:0,pages:be,pageTypes:r,currentPage:f||"",onClickAction:w,languagePages:k,selectedLanguage:K})})]}),v&&t.jsx(dn,{closePanel:e,editPage:ue,addEditPage:v,setAddEditPage:S}),p&&t.jsx(Ts,{page:p,onClose:()=>y(null)}),E&&t.jsx(rs,{page:E,onClose:()=>D(null)}),I&&t.jsx(mn,{page:I,onClose:()=>_(null)}),G&&t.jsx(gn,{page:G,onClose:()=>H(null)}),$&&t.jsx(hn,{page:$,onClose:()=>P(null)})]})},Ki=()=>{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},Hi=()=>{const[e]=Le(),s=e.get("page"),{data:n,isFetching:a}=ke(),[r,i]=g.useState(!1),{savePage:l}=O.useSavePage(),o=!!s&&!m.isEmpty(n),u=!s||!a&&m.isEmpty(n)||r,d=O.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(N.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(N.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(Vi,{close:()=>i(!1)}):t.jsx(Bi,{close:()=>i(!1)})})]})})]})},pn=({showAdd:e=!0,variant:s="ghost"})=>{const{fallbackLang:n,languages:a,selectedLang:r,setSelectedLang:i}=O.useLanguages(),l=m.isEmpty(r)?n:r,[,o]=Le();g.useEffect(()=>{const p=new URLSearchParams(window.location.search),y=p.get("lang");y&&(a.includes(y)?i(y):(p.delete("lang"),o(p),i("")))},[a,o,i]);const[,u]=Ee.useAtom(As),{data:d}=ke(),{data:h}=He(),{data:f}=Ue(),b=g.useMemo(()=>{const p=m.compact(m.map(m.get(h,"languages"),y=>{const v=m.find(f,{lang:y});return{key:y,value:m.get(Te,y,y),isLangPageAdded:!!v}})).filter(Boolean);return[{key:n,value:m.get(Te,n),isLangPageAdded:!0},...p]},[n,f,h]),j=p=>{i(p);const y=new URLSearchParams(window.location.search);p===n?y.delete("lang"):y.set("lang",p);const v=y.toString(),S=`${window.location.pathname}${v?`?${v}`:""}`;window.history.pushState({},"",S),o(y),window.dispatchEvent(new PopStateEvent("popstate"))};return m.isEmpty(a)?null: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,{variant:s,size:"sm",className:"ml-px h-max gap-2 py-1.5",children:[t.jsx(N.Languages,{className:"h-4 w-4"}),m.get(Te,l,l),t.jsx(N.ChevronDown,{className:"h-4 w-4"})]})}),t.jsxs(c.DropdownMenuContent,{className:"space-y-1 border-border",children:[m.map(b.filter(p=>p.isLangPageAdded),p=>t.jsxs(c.DropdownMenuItem,{className:O.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:()=>j(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(N.Star,{fill:"orange",className:"h-2 w-2"}),"Primary"]})]},p.value)),e&&!m.isEmpty(b.filter(p=>!p.isLangPageAdded))&&t.jsxs(t.Fragment,{children:[t.jsx(c.Separator,{}),t.jsxs(c.Button,{size:"sm",variant:"ghost",onClick:()=>{d&&u({edit:!1,primaryPage:d.id})},className:"text-xs font-normal duration-200 hover:bg-slate-300 hover:text-slate-800",children:[t.jsx(N.Plus,{className:"mr-1 h-3 w-3"})," Add Langauge"]})]})]})]})})};function Wi(){const[e,s]=Ee.useAtom(As);return t.jsxs("div",{className:"relative z-10 flex items-center justify-end gap-1",children:[t.jsx(Ki,{}),t.jsx(Hi,{}),e&&t.jsx(yi,{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}=O.usePermissions();return e&&!r(e)||s&&!s.some(i=>r(i))?a:n};function Qi(e){const s=oe(),n=ee();return R.useQuery({queryKey:[Q,"revisions",e],queryFn:async()=>await n(s,{action:L.GET_PAGE_REVISIONS,data:{pageId:e}}),enabled:!!e,gcTime:0,staleTime:0})}const Yi=()=>{const e=oe(),s=ee(),n=R.useQueryClient();return R.useMutation({mutationFn:async a=>await s(e,{action:L.DELETE_PAGE_REVISION,data:{revisionId:a}}),onSuccess:()=>{n.invalidateQueries({queryKey:[Q,"revisions"]})}})},Ji=()=>{const e=oe(),s=ee(),n=R.useQueryClient();return R.useMutation({mutationFn:async({revisionId:a,discardCurrent:r})=>await s(e,{action:L.RESTORE_PAGE_REVISION,data:{revisionId:a,discardCurrent:r}}),onSuccess:()=>{n.invalidateQueries({queryKey:[Q,"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(N.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(N.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 Xi({compare:e,setCompare:s,isComparisonEnabled:n}){const{data:a}=ke(),{saveState:r}=O.useSavePage(),[i]=Cs();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:!m.isEmpty(i.lastSaved)&&t.jsxs("span",{children:["Last updated"," ",kt.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(ja,{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 Zi(){var W,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}=ke(),{data:f,isFetching:b,error:j,refetch:p}=Qi(h==null?void 0:h.id),{mutate:y,isPending:v}=Yi(),{mutate:S,isPending:E}=Ji(),D=R.useQueryClient(),I=ra(),_=O.useChaiFeatureFlag("enable-page-revisions-compare"),{selectedLang:M,fallbackLang:X}=O.useLanguages(),$=M||X;g.useEffect(()=>s([]),[h==null?void 0:h.id]);const P=k=>{r&&S({revisionId:r.uid,discardCurrent:k},{onSuccess:()=>{o(!1),i(null),D.invalidateQueries({queryKey:[Q,L.GET_DRAFT_PAGE]})}})},G=k=>{i(k),o(!0)},H=k=>{i(k),d(!0)},K=()=>{r&&y(r.uid,{onSuccess:()=>{d(!1),i(null)}})};return g.useEffect(()=>{n&&p()},[n,p]),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(N.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 ",kt.format(new Date(h.createdAt),"MMM d, yyyy 'at' h:mm a")]})]}),b?t.jsx(el,{}):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:[_&&t.jsx(sl,{lang:$,compare:e,setCompare:s}),t.jsx(Xi,{compare:e,setCompare:s,isComparisonEnabled:_}),(W=f==null?void 0:f.filter(k=>k.uid==="current"))==null?void 0:W.map((k,q)=>t.jsx(Pn,{lang:$,pageId:h==null?void 0:h.id,revision:k,isLatest:!0,onRestore:()=>G(k),onDelete:()=>H(k),revisionNumber:q,compare:e,setCompare:s,pageLiveFullSlug:I,isComparisonEnabled:_},k.uid)),t.jsx(c.ScrollArea,{className:"min-h-0 flex-1",children:t.jsx("div",{className:"space-y-2",children:(Z=f==null?void 0:f.filter(k=>k.uid!=="current"))==null?void 0:Z.map((k,q)=>t.jsx(Pn,{lang:$,pageId:h==null?void 0:h.id,revision:k,isLatest:k.uid==="current",onRestore:()=>G(k),onDelete:()=>H(k),revisionNumber:q+1,compare:e,setCompare:s,pageLiveFullSlug:I,isComparisonEnabled:_},k.uid))})})]})]})]}),t.jsx(c.TooltipContent,{side:"bottom",children:t.jsx("p",{children:"Revision history"})})]})}),t.jsx(al,{open:l,onOpenChange:o,revision:r,onRestore:P,isRestoring:E}),t.jsx(rl,{open:u,onOpenChange:d,revision:r,onDelete:K,isDeleting:v})]})}function el(){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:f}=ct(e.currentEditor),b=(f==null?void 0:f.name)||"Unknown",j=!!i.find(y=>{var v;return s?(v=y==null?void 0:y.uid)==null?void 0:v.startsWith("live"):(y==null?void 0:y.uid)===e.uid}),p=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:kt.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(N.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(nl,{revision:e,onRestore:n,onDelete:a})})]}),d&&t.jsx(ja,{checked:j,disabled:p,onChange:()=>{l(j?i.filter(y=>s?y.uid!==`live:${o}`:y.uid!==e.uid):[...i,{uid:s?`live:${o}`:e.uid,label:s?"live":`#${r}`}])}})]})}function tl(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 sl({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(N.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(N.X,{className:"h-2.5 w-2.5"}),"Clear"]}),e.length===2?t.jsx("a",{target:"_blank",href:tl(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(N.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(N.ExternalLink,{className:"ml-1 h-2.5 w-2.5"})]})]})]})}function ja({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 nl({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(N.MoreHorizontal,{className:"h-4 w-4"}),t.jsx("span",{className:"sr-only",children:"More options"})]})}),t.jsxs(c.DropdownMenuContent,{align:"end",className:"text-xs",children:[t.jsx(Re,{permission:ve.RESTORE_REVISION,children:t.jsxs(c.DropdownMenuItem,{onClick:s,className:"cursor-pointer text-sm",children:[t.jsx(N.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(N.Trash,{className:"mr-2 h-4 w-4"}),t.jsx("span",{children:"Delete this version"})]})]})})]})]})}function al({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"," ",kt.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(N.CloudOff,{className:"mr-2 h-4 w-4"}),"Save as draft"]})}),t.jsx(c.Button,{variant:"default",className:"sm:flex-1",onClick:()=>a(!0),disabled: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(N.Undo2,{className:"mr-2 h-4 w-4"}),"Discard current"]})})]})]})}):null}function rl({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"," ",kt.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(N.Trash,{className:"mr-2 h-4 w-4"}),"Delete Revision"]})})]})]})}):null}const il=()=>{const e=oe(),s=ee();return R.useQuery({queryKey:[Q,L.GET_CHANGES],queryFn:async()=>s(e,{action:L.GET_CHANGES})})};function ll({showModal:e=!1,onClose:s=()=>console.log("Cancelled")}){const[n,a]=g.useState([]),r=We(),[i,l]=g.useState(r),{data:o,isFetching:u}=il(),{data:d}=Ce(),h=g.useCallback(P=>{var G;return(G=m.find(d,{key:P}))==null?void 0:G.hasSlug},[d]),f=g.useMemo(()=>m.filter(d,P=>!h(P.key)).map(P=>P.key),[h,d]),j=m.uniq(m.map(o,"lang")).filter(Boolean),p=g.useMemo(()=>m.filter(o,P=>P.pageType==="theme"?!1:i===r?P.lang===i||P.lang==="":P.lang===i),[o,i,r]),y=g.useMemo(()=>m.filter(p,P=>!f.includes(P.pageType)),[p,f]),v=g.useMemo(()=>m.filter(p,P=>f.includes(P.pageType)),[p,f]),{mutate:S,isPending:E}=ln();g.useEffect(()=>{const P=m.map(m.filter(p,{online:!0}),"id");a(P)},[p]);const D=n.length===(p==null?void 0:p.length),I=P=>{a(G=>m.includes(G,P)?m.filter(G,H=>H!==P):m.concat(G,P))},_=()=>{a(D?[]:m.map(p,"id"))},M=()=>{S({ids:m.uniq(n)},{onSuccess:()=>{s(),Ft("CENTER_CENTER"),l(r)}})},X=P=>{if(P==="theme")return"Theme";const G=m.find(d,{key:P});return G?G==null?void 0:G.name:P},$=g.useMemo(()=>{const P=[{label:"Updated",top:"pt-2"},...m.orderBy(m.filter(y,{online:!0}),"pageType"),...m.orderBy(m.filter(v,{online:!0}),"pageType")].filter(H=>H.pageType!=="theme"),G=[{label:"Offline",top:"pt-6"},...m.orderBy(m.filter(y,{online:!1}),"pageType"),...m.orderBy(m.filter(v,{online:!1}),"pageType")];return[...P,...G]},[y,v]);return t.jsx(c.Dialog,{open:e,onOpenChange:E?()=>{}: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(pa,{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:D,onClick:P=>{P.stopPropagation(),_()},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:m.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:m.includes(n,P==null?void 0:P.id),onClick:G=>{G.stopPropagation(),I(P==null?void 0:P.id)},type:"checkbox",className:"cursor-pointer rounded focus:outline-none focus:ring-0"})," ",h(P.pageType)?t.jsx(N.File,{className:"h-4 w-4"}):t.jsx(N.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:m.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:E,variant:"outline",onClick:s,children:"Cancel"}),t.jsx(c.Button,{disabled:E||u||m.isEmpty(n),onClick:M,children:E?"Publishing...":"Publish Selected"})]})]})})}const ol=()=>{const e=ee(),s=oe();return R.useQuery({queryKey:[L.GET_WEBSITE_DATA],staleTime:1e3*60*5,queryFn:async()=>e(s,{action:L.GET_WEBSITE_DATA,data:{draft:!0}})})};function cl({onClose:e}){const{data:s,isFetching:n}=ol(),{mutateAsync:a,isPending:r}=Tr(),i=qe("settingComponent",null),l=m.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 ul=()=>{const{selectedLang:e,fallbackLang:s}=O.useLanguages(),n=qe("getPreviewUrl",async f=>f),[a,r]=g.useState(""),{data:i}=ke(),{data:l}=Ue(),{data:o}=Ce(),u=g.useMemo(()=>{var f;return(f=l==null?void 0:l.find(b=>(b==null?void 0:b.lang)===e))==null?void 0:f.slug},[e,l]),d=g.useCallback(f=>{var b;return(b=m.find(o,{key:f}))==null?void 0:b.hasSlug},[o]),h=e===s?"":e;return g.useEffect(()=>{(async()=>{if(typeof n=="function"){const f=!d(i==null?void 0:i.pageType),b=await n(f?`${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(N.Eye,{className:"h-4 w-4"})," ",le.PREVIEW]})})})},dl=()=>{const[e,s]=O.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(N.Palette,{className:"h-4 w-4"})})}),t.jsx("div",{className:"h-4 w-px bg-gray-200 dark:bg-gray-700"})]})},hl=()=>{const[e,s]=g.useState(!1),{isLocked:n}=as(),{savePage:a,saveState:r}=O.useSavePage();g.useEffect(()=>{const h=f=>{r==="UNSAVED"&&(f.preventDefault(),f.returnValue=!1)};return r==="UNSAVED"&&window.addEventListener("beforeunload",h),()=>{window.removeEventListener("beforeunload",h)}},[r]);const i=g.useCallback(async()=>{s(!0),await a(!1)},[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(N.Save,{className:"h-4 w-4"}),buttonClass:"flex items-center gap-x-1 leading-tight"};case"SAVING":return{tooltipContent:le.SAVING,buttonIcon:t.jsx(N.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(N.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]})},ml=()=>{const{selectedLang:e}=O.useLanguages(),{data:s}=tt(),{data:n}=Ue(),[a,r]=g.useState(!1),[i,l]=g.useState(!1),[o,u]=g.useState(null),{data:d}=ke(),{mutate:h,isPending:f}=ln(),{buttonText:b,buttonClassName:j,isPublished:p}=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]),y=async()=>{const S=[s==null?void 0:s.id,s==null?void 0:s.primaryPage];h({ids:m.compact(S)},{onSuccess:()=>Ft("TOP_RIGHT")})},v=g.useMemo(()=>m.map(n??[],"id"),[n]);return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex",children:[t.jsxs(c.Button,{size:"sm",onClick:y,disabled:f||!(d!=null&&d.id),className:`relative flex items-center gap-1 overflow-hidden rounded-r-none text-white transition-all duration-300 ease-in-out ${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:p?t.jsx(N.Send,{className:"h-4 w-4"}):t.jsx(N.Rocket,{className:"h-4 w-4"})}),t.jsx("span",{className:`absolute inset-0 left-3 flex items-center transition-transform duration-300 ease-in-out ${i?"":"translate-y-10"}`,children:p?t.jsx(N.Rocket,{className:"h-4 w-4"}):t.jsx(N.Send,{className:"h-4 w-4"})}),t.jsx("span",{children:b}),e?`(${m.upperCase(e)})`:""]}),t.jsxs(c.DropdownMenu,{children:[t.jsx(c.DropdownMenuTrigger,{asChild:!0,children:t.jsx(c.Button,{size:"sm",disabled:f||!(d!=null&&d.id),className:`rounded-l-none border-l border-white/50 px-2 text-white ${j}`,children:t.jsx(N.ChevronDown,{className:"h-4 w-4"})})}),t.jsxs(c.DropdownMenuContent,{align:"end",className:"w-52",children:[t.jsxs(c.DropdownMenuItem,{disabled:f,className:"cursor-pointer text-xs",onClick:()=>h({ids:v},{onSuccess:()=>Ft("TOP_RIGHT")}),children:[le.PUBLISH," with translation pages"]}),!p&&t.jsxs(c.DropdownMenuItem,{disabled:f,className:"cursor-pointer text-xs",onClick:()=>h({ids:[d==null?void 0:d.id]},{onSuccess:()=>Ft("TOP_RIGHT")}),children:[le.PUBLISH," page"]}),t.jsxs(c.DropdownMenuItem,{onClick:()=>r(!0),className:"cursor-pointer text-xs",children:[le.OPEN," publish menu"]}),p&&t.jsxs(c.DropdownMenuItem,{onClick:()=>u(s),className:"cursor-pointer text-xs",children:[le.UNPUBLISH," page ",e?`(${m.upperCase(e)})`:""]})]})]})]}),t.jsx(ll,{showModal:a,onClose:()=>r(!1)}),o&&t.jsx(rs,{page:o,onClose:()=>u(null)})]})},fl=()=>{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(N.Settings,{className:"h-4 w-4"})})}),s&&t.jsx(cl,{onClose:()=>n(!1)}),t.jsx("div",{className:"h-4 w-px bg-gray-200 dark:bg-gray-700"})]}):null};function gl(){const{isLocked:e}=as(),[s]=Le(),n=s.get("lang"),a=ta(n);return e||!a?t.jsx("div",{}):t.jsxs("div",{className:"flex items-center justify-end gap-1",children:[t.jsx(Zi,{}),t.jsx(Re,{permission:ve.EDIT_THEME,children:t.jsx(dl,{})}),t.jsx(Re,{permission:ve.EDIT_SETTINGS,children:t.jsx(fl,{})}),t.jsx(ul,{}),t.jsx(Re,{permission:ve.SAVE_PAGE,children:t.jsx(hl,{})}),t.jsx(Re,{permission:ve.PUBLISH_PAGE,children:t.jsx(ml,{})})]})}const xl=({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()}),pl=({dynamicPage:e,setDynamicPage:s,searchQuery:n,setSearchQuery:a,dynamicPages:r})=>{const{selectedLang:i,fallbackLang:l}=O.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?m.get(e,"name"):"Select Page",t.jsx(N.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(xl,{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))]})]})},yl=()=>{const{dynamicPage:e,dynamicPages:s,allLangPages:n,selectedLang:a,searchQuery:r,updateDynamicPage:i,updateSearchQuery:l,onChangeLanguage:o}=na(),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(pl,{dynamicPage:e,setDynamicPage:i,searchQuery:r,setSearchQuery:l,dynamicPages:n})})},jl=()=>{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,f]=g.useState(null),{data:b,isFetching:j}=tt(),{selectedLang:p,fallbackLang:y}=O.useLanguages(),{data:v}=Ue(),S=v==null?void 0:v.find(E=>E.lang===p);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(N.Loader,{className:"h-4 w-4 animate-spin text-slate-400"}):m.get(S||b,"name")??""}),t.jsx(fn,{page:b,setDuplicatePage:E=>d(E),setAddEditPage:E=>f(E),setUnpublishPage:E=>a(E),setDeletePage:E=>s(E),setMarkAsTemplate:E=>i(E),setUnmarkAsTemplate:E=>o(E),isLanguagePage:p.length>0&&p!==y,children:t.jsx("div",{className:"cursor-pointer rounded p-[7px] hover:bg-gray-200",children:t.jsx(N.MoreHorizontal,{className:"h-4 w-4",onClick:E=>E.stopPropagation()})})})]}),h&&t.jsx(dn,{closePanel:()=>f(null),editPage:()=>{},addEditPage:h,setAddEditPage:f}),e&&t.jsx(Ts,{page:e,onClose:()=>s(null)}),n&&t.jsx(rs,{page:n,onClose:()=>a(null)}),r&&t.jsx(mn,{page:r,onClose:()=>i(null)}),l&&t.jsx(gn,{page:l,onClose:()=>o(null)}),u&&t.jsx(hn,{page:u,onClose:()=>d(null)})]}):null},vl=({hasDynamicPage:e,className:s=""})=>t.jsx("div",{className:`z-[9999] fixed bottom-0 left-0 right-0 z-[20] flex items-center justify-center w-screen top-[50px] bg-black/30 backdrop-blur-sm ${s}`,children:t.jsxs("div",{className:"bg-white rounded-md p-4 shadow-xl min-w-[300px] max-w-[400px] flex flex-col items-center justify-center",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"})]})}),bl=()=>{const{data:e}=tt(),s=sn(),{data:n,isFetching:a}=ke(),r=m.get(n,"dynamic",!1),i=O.useChaiFeatureFlag("dynamic-page-selector"),{dynamicPage:l,allLangPages:o}=na(),u=o.length>0,d=e==null?void 0:e.slug,h=!d,f=ra(),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:O.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(jl,{})}),t.jsxs("div",{className:O.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(pn,{}),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:f,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(N.ExternalLink,{className:"h-4 w-4",strokeWidth:1})})})]})]}),r&&!a&&i&&t.jsxs("div",{className:"relative",children:[!l&&t.jsx(vl,{hasDynamicPage:u}),t.jsx(yl,{})]})]})},Sl=()=>t.jsxs("div",{className:"flex h-full w-full items-center justify-between px-2",children:[t.jsx(Wi,{}),t.jsx(bl,{}),t.jsx(gl,{})]}),wl=()=>{const e=oe(),{aiContext:s}=tn(),n=ee();return g.useCallback(async(a,r,i,l)=>n(e,{action:L.ASK_AI,data:{type:a,prompt:r,blocks:i,context:s,lang:l}}),[e,s,n])},Nl=(e,s)=>s.map(n=>{if(m.has(e,n._type)){const a=Hn.getDefaultBlockProps(n._type);return{...a,...m.pick(n,[...m.keys(a),"_type","_id","_name","_parent","_bindings"]),...m.pickBy(n,(r,i)=>m.endsWith(i,"_attrs")),...n}}return n}),El=e=>{const s=Hn.useRegisteredChaiBlocks();return g.useMemo(()=>{if(!e||m.isEmpty(e))return{blocks:[]};const n=m.filter(e,a=>!m.includes(a==null?void 0:a._type,"@chai/"));return{blocks:Nl(s,n)}},[e,s])},kn={async getUILibraryBlock(e,s,n){const a=await s(n,{action:"GET_LIBRARY_ITEM",data:{id:e.id}}),r=m.get(a,"html",""),i=m.get(a,"blocks",[]);return m.isArray(i)?i:O.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),[]}}},Cl=()=>{const e=oe(),s=ee();return R.useQuery({queryKey:[Q,"uiLibraries"],initialData:[],queryFn:async()=>{const a=(await s(e,{action:"GET_LIBRARIES"})).map(r=>({...r}));return a.forEach(r=>{O.registerChaiLibrary(r.id,{name:r.name,description:r.description,getBlocksList:i=>kn.getUILibraryBlocks(i,s,e),getBlock:({block:i})=>kn.getUILibraryBlock(i,s,e)})}),a}})},va=()=>{const e=Es(),s=ee(),{user:n}=Fe(),a=n==null?void 0:n.id;return R.useQuery({queryKey:[Q,"permissions",a],queryFn:()=>s(e,{action:L.GET_ROLE_AND_PERMISSIONS,data:{userId:a}}),enabled:!!a})},Al=()=>{const e=oe(),s=ee(),{setCurrentEditor:n}=as(),[,a]=Cs();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")}}}},Tl=()=>{const{data:e}=ot(),s=oe(),n=ee();return{getPartialBlocks:g.useCallback(async()=>{const a={};for(const r of e??[])m.isEmpty(r==null?void 0:r.slug)&&(a[r.id]={type:r.pageType,name:m.startCase(r.name??r.slug),description:""});return a},[e]),getPartialBlockBlocks: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 m.filter(r.blocks,i=>m.has(i,"_id"))}catch(r){return console.error(r),[]}},[n,s])}},Ln=hs.z.object({email:hs.z.string().email({message:"Please enter a valid email address"}),password:hs.z.string().min(6,{message:"Password must be at least 6 characters"})}),Pl=()=>{const{setUser:e,logout:s}=Fe(),n=Es(),[a,r]=g.useState(""),[i,l]=g.useState(""),[o,u]=g.useState({}),[d,h]=g.useState(!1),[f,b]=g.useState(""),j=R.useMutation({mutationFn:async v=>{b("");const S=await en(n,{action:"LOGIN",data:v});if(!S.ok){const D=await S.json();throw new Error(D.error||"Login failed")}const E=await S.json();if(m.has(E,"id")&&m.has(E,"email")&&m.has(E,"accessToken")&&m.has(E,"refreshToken"))e(E);else throw s(),new Error("Something went wrong. Please try again.");return E},onSuccess:()=>{u({}),b("")},onError:v=>{u({email:" ",password:" "}),b(v.message||"Something went wrong")}}),p=async v=>{v.preventDefault(),u({});const S={email:a,password:i};try{const E=Ln.parse(S);j.mutate(E)}catch(E){if(E instanceof hs.z.ZodError){const D=E.errors.reduce((I,_)=>{const M=_.path[0];return I[M]=_.message,I},{});u(D)}}},y=Ln.safeParse({email:a,password:i}).success;return t.jsx("div",{className:"flex justify-center items-center min-h-screen bg-slate-50",children:t.jsxs(c.Card,{className:"w-full max-w-md",children:[t.jsxs(c.CardHeader,{children:[t.jsx(c.CardTitle,{className:"text-2xl",children:"Sign in"}),t.jsx(c.CardDescription,{children:"Enter your credentials to sign in to visual builder"})]}),t.jsx(c.CardContent,{children:t.jsxs("form",{onSubmit:p,className:"space-y-4",children:[t.jsxs("div",{className:"space-y-1",children:[t.jsx(c.Label,{htmlFor:"email",children:"Email"}),t.jsx(c.Input,{id:"email",placeholder:"you@example.com",type:"email",value:a,onChange: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(N.EyeOff,{className:"h-4 w-4"}):t.jsx(N.Eye,{className:"h-4 w-4"})})]}),o.password&&t.jsx("p",{className:"text-sm text-destructive",children:o.password})]}),t.jsx("div",{children:t.jsx("p",{className:"text-sm text-destructive",children:f})}),t.jsx(c.Button,{type:"submit",className:"w-full",disabled:!y||j.isPending,children:j.isPending?t.jsxs(t.Fragment,{children:[t.jsx(N.Loader2,{className:"mr-2 h-4 w-4 animate-spin"}),"Logging in..."]}):"Login"})]})}),t.jsxs(c.CardFooter,{className:"flex flex-col justify-center",children:[t.jsxs("p",{className:"text-sm text-muted-foreground",children:["Forgot your password?"," ",t.jsx("a",{target:"_blank",href:"https://chaibuilder.com/forgot-password",className:"text-primary hover:underline",children:"Reset password"})]}),t.jsx("br",{}),t.jsx("br",{}),t.jsxs("div",{className:"flex items-center border-t pt-2 px-10 gap-2",children:["Powered by"," ",t.jsxs("a",{target:"_blank",href:"https://chaibuilder.com",className:"text-primary hover:underline flex items-center gap-1",children:[t.jsx("img",{src:"https://ucarecdn.com/a82e256c-1cf2-4755-b65c-5d85e7652daa/-/preview/400x400",alt:"Chai Builder",className:"w-4 h-4 rounded uppercase font-bold"}),"Chai Builder"]})]})]})]})})};let qs=Pl;const kl=()=>g.useMemo(()=>qs,[qs]),Ll=e=>{qs=e},Il=()=>{const e=kl();return t.jsx(g.Suspense,{fallback:t.jsx("div",{children:"Loading..."}),children:t.jsx(e,{})})},_l=({page:e,onClose:s})=>{const[n,a]=g.useState(e.slug||""),{mutate:r,isPending:i}=li(),{data:l}=Ce(),o=m.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}`||m.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(N.AlertCircle,{className:"h-4 w-4"}),"Changing the slug may have impact on your SEO. Please proceed with caution."]})})]}),t.jsxs("form",{onSubmit:u,children:[t.jsxs("div",{className:"space-y-4 py-4 text-sm ",children:[t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{children:[t.jsx("span",{children:"Type:"}),t.jsxs("span",{className:"font-medium text-gray-600",children:[" ",(o==null?void 0:o.name)||(e==null?void 0:e.pageType)]})]}),t.jsxs("div",{children:[t.jsx("span",{children:"Name:"}),t.jsxs("span",{className:"font-medium text-gray-600",children:[" ",e.name]})]})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsxs(c.Label,{htmlFor:"slug",className:"text-right",children:["Slug"," ",t.jsxs("small",{className:"font-light text-gray-500",children:["Slug should start with /",d]})]}),t.jsx(c.Input,{id:"slug",value:n,onChange:h=>{const f=h.target.value;m.startsWith(f,`/${d}`)&&a(f)},className:"col-span-3",required:!0,pattern:"^/.*",title:"Slug must start with /",placeholder:"Enter page slug"})]})]}),t.jsx(c.DialogFooter,{children:t.jsx(c.Button,{type:"submit",disabled:i||!m.startsWith(n,`/${d}`)||m.isEqual(e==null?void 0:e.slug,n),children:i?"Changing...":"Change Slug"})})]})]})})},Dl=()=>{const[,e]=Ee.useAtom(As),{selectedLang:s,fallbackLang:n,setSelectedLang:a}=O.useLanguages(),{data:r,isFetching:i}=Ue(),{data:l}=ke(),{data:o}=Ce(),u=g.useMemo(()=>{const S=o==null?void 0:o.find(E=>E.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),[f,b]=g.useState(null),[j,p]=g.useState(null),{data:y}=He(),v=m.filter(m.get(y,"languages")||["en"],S=>!m.find(r,{lang:S})&&S!==m.get(y,"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"})]}):m.map(r,S=>{const E=S.lang,D=S.slug,I=!S.primaryPage,_=E===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 ${_?"bg-gray-200":"hover:bg-gray-100"}`,onClick:()=>a(E),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"}`}),m.get(Te,I?n:E,E)]}),t.jsxs("div",{children:[D&&t.jsxs("div",{className:"text-[11px] font-light text-slate-600",children:["Slug: ",t.jsx("b",{className:"font-mono font-medium",children:u?`${D}/${u}`:D})]}),t.jsxs("div",{className:"text-[11px] font-light text-slate-600",children:["Name:",t.jsxs("b",{className:"font-medium",children:[" ",S.name," "]})]})]})]}),I?t.jsxs("div",{className:"flex items-center gap-x-1 text-[11px] text-orange-500",children:[t.jsx(N.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:M=>M.stopPropagation(),children:t.jsx(c.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",children:t.jsx(N.MoreHorizontal,{className:"h-4 w-4"})})}),t.jsxs(c.DropdownMenuContent,{align:"end",className:"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:M=>{M.stopPropagation(),e({edit:!0,id:S.id,primaryPage:S.primaryPage})},children:[t.jsx(N.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:M=>{M.stopPropagation(),b(S)},children:[t.jsx(N.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:M=>{M.stopPropagation(),h(S)},children:[t.jsx(N.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:m.isEmpty(v),onClick:()=>{e({primaryPage:l==null?void 0:l.id,edit:!1})},children:le.ADD_NEW_LANGUAGE})})}),d&&t.jsx(Ts,{page:d,onClose:()=>h(null)}),f&&t.jsx(rs,{page:f,onClose:()=>b(null)}),j&&t.jsx(_l,{page:j,onClose:()=>p(null)})]})},Bl=({isActive:e,show:s})=>{const{data:n}=He();return!m.has(n,"languages")||!m.get(n,"languages",[]).length?null:t.jsx(c.Button,{size:"sm",onClick:s,variant:e?"default":"ghost",children:t.jsx(N.LanguagesIcon,{className:"w-4 h-4"})})},ba="lang",Ml={id:ba,label:"Languages",position:"top",panel:Dl,button:Bl,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=p=>Array.isArray(p)?"array":typeof p=="object"&&p!==null?"object":"value",f=Se.useCallback(p=>{const y=v=>n==="value"?v==="value"||v==="object":n==="array"?v==="array":v===n;p.type==="object"?(o(v=>[...v,p.key]),d(p.value)):y(p.type)&&(s([...l,p.key].join(".")),i(!1))},[l,s,n]),b=Se.useCallback(()=>{if(l.length>0){const p=l.slice(0,-1);o(p),d(p.reduce((y,v)=>y[v],e))}},[l,e]),j=Se.useMemo(()=>Object.entries(u).map(([p,y])=>({key:p,value:y,type:h(y)})).filter(p=>n==="value"?p.type==="value"||p.type==="object":n==="array"?p.type==="array"||p.type==="object":n==="object"?p.type==="object":!0),[u,n]);return t.jsxs(c.Popover,{open:r,onOpenChange:i,children:[t.jsxs(c.Tooltip,{children:[t.jsx(c.TooltipTrigger,{asChild:!0,children:t.jsx(c.PopoverTrigger,{asChild:!0,children:t.jsx(c.Button,{size:"sm",variant:"outline",className:"h-6 w-6 px-1 py-0 text-[9px] text-muted-foreground",role:"combobox","aria-expanded":r,disabled:a,children:t.jsx(N.DatabaseIcon,{className:"h-3 w-3"})})})}),t.jsx(c.TooltipContent,{children:"Add field"})]}),t.jsx(c.PopoverContent,{className:"w-[200px] z-[9999] p-0",children:t.jsxs(c.Command,{children:[t.jsx(c.CommandInput,{className:"border-none",placeholder:"Search..."}),t.jsxs(c.CommandList,{onWheel:p=>{try{p.preventDefault();const y=p.currentTarget;y.scrollTop+=p.deltaY}catch{p.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(N.ChevronLeft,{className:"w-4 h-4 mr-2"}),"Back"]}),j.map(p=>t.jsxs(c.CommandItem,{onSelect:()=>f(p),className:"flex items-center justify-between",children:[t.jsx("span",{children:p.key}),t.jsxs("div",{className:"flex items-center gap-2",children:[n==="object"&&p.type==="object"&&t.jsx(c.Button,{size:"sm",variant:"ghost",className:"h-6 px-2 hover:bg-primary hover:text-primary-foreground",onClick:y=>{y.stopPropagation(),s([...l,p.key].join(".")),i(!1)},children:"Select"}),(p.type==="object"||p.type==="array")&&t.jsx("div",{className:"p-1 rounded hover:bg-muted cursor-pointer",children:t.jsx(N.ChevronRight,{className:"w-4 h-4 opacity-50"})})]})]},p.key))]})]})]})})]})}const Gl=()=>{const{selectedLang:e}=O.useLanguages(),{data:s,isFetching:n}=Ue();return{data:g.useMemo(()=>m.find(s,{lang:e||""})||{},[s,e]),isFetching:n}},Rl=()=>{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>/,"")},Bt=({keyword:e,onComplete:s,field:n})=>{const a=ee(),r=oe(),{selectedLang:i,fallbackLang:l}=O.useLanguages(),o=O.useBuilderProp("aiContext",""),{mutate:u,isPending:d}=R.useMutation({mutationFn:async()=>{const h=Rl();return await a(r,{action:L.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(N.Loader2,{className:"h-3 w-3 animate-spin text-yellow-500"}):t.jsx(N.Sparkle,{className:"text-yellow-500"})})},Fl=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),In=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 f=a.substring(0,u).split(`
3
- `);d=f.length,h=f[f.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},Ul=(e,s)=>{if(!e)return"";let n=JSON.stringify(e,null,2);const a=/{{([^{}]+)}}/g;let r;for(;(r=a.exec(n))!==null;){const i=r[1],l=m.get(s,i,null);n=n.replace(r[0],l)}return n},Sa=({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"),[f,b]=g.useState(null),[j,p]=g.useState(""),y=g.useRef(null),v=I=>{if(a)return;const _=I.target.value;s(_)},S=I=>{if(I.key==="Tab"){I.preventDefault();const _=I.currentTarget,M=_.selectionStart,X=_.selectionEnd;if(M!==X){const P=e.substring(M,X).split(`
4
- `);if(I.shiftKey){const H=P.map(W=>W.startsWith(" ")?W.substring(2):W).join(`
5
- `),K=e.substring(0,M)+H+e.substring(X);s(K),setTimeout(()=>{_.selectionStart=M,_.selectionEnd=M+H.length},0)}else{const H=P.map(W=>` ${W}`).join(`
6
- `),K=e.substring(0,M)+H+e.substring(X);s(K),setTimeout(()=>{_.selectionStart=M,_.selectionEnd=M+H.length},0)}}else{const $=e.substring(0,M)+" "+e.substring(X);s($),setTimeout(()=>{_.selectionStart=_.selectionEnd=M+2},0)}}};g.useEffect(()=>{const I=In(e);if(I.isValid)if(b(null),I.parsed){const _=Ul(I.parsed,o);p(_)}else p("");else b(I.error),p("")},[e,o]);const E=()=>{const I=In(e);if(I.isValid&&I.parsed){const _=Ol(I.parsed,I.placeholders);s(_)}},D=()=>{f!=null&&f.position&&y.current&&(y.current.focus(),y.current.setSelectionRange(f.position,f.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(N.Code,{className:"h-4 w-4"}),t.jsx("span",{children:"Edit"})]}),t.jsxs(c.TabsTrigger,{value:"preview",className:"flex items-center gap-1",disabled:!e.trim()||f!==null,children:[t.jsx(N.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:I=>u&&u(I,l)}),t.jsx(c.Button,{type:"button",variant:"outline",size:"sm",onClick:E,disabled:!e.trim()||n||f!==null,children:"Format"})]})]}),t.jsxs(c.TabsContent,{value:"edit",className:"mt-0",children:[t.jsx(c.Textarea,{ref:y,id:l,name:l,className:`rounded-md border border-input text-xs ${f?"border-red-500":""}`,onChange:v,onKeyDown:S,value:e,placeholder:r,rows:i,disabled:n,readOnly:a}),f&&t.jsxs(c.Alert,{variant:"destructive",className:"mt-2",children:[t.jsx(N.AlertTriangle,{className:"h-4 w-4"}),t.jsxs(c.AlertDescription,{className:"flex flex-col",children:[t.jsx("span",{className:"font-medium",children:"Invalid JSON"}),t.jsx("span",{className:"text-sm",children:f.message}),f.line&&f.column&&t.jsxs("span",{className:"text-sm",children:["Error at line ",f.line,", column ",f.column]}),t.jsx(c.Button,{type:"button",variant:"link",size:"sm",className:"mt-1 h-auto self-start p-0 text-sm",onClick:D,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."})]})]})})},_n=e=>{if(!e)return!0;try{return JSON.parse(e),!0}catch{return!1}},ql=(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}},wa=()=>{const{t:e}=O.useTranslation(),[,s]=O.useSidebarActivePanel(),{data:n}=ke(),{data:a}=an(),{data:r,isFetching:i}=Gl(),l=r==null?void 0:r.seo,o=g.useRef(null),u=n==null?void 0:n.pageType,d=oa(u),{selectedLang:h,fallbackLang:f}=O.useLanguages(),b=h||f,[j,p]=g.useState(!1),[y,v]=g.useState(!1),[S,E]=g.useState({keyword:"",title:"",description:"",cononicalUrl:"",noIndex:!1,noFollow:"",ogTitle:"",ogDescription:"",ogImage:"",ogImageId:"",searchTitle:"",searchDescription:"",jsonLD:"{}",...l}),D=g.useRef({initial:S,updated:S}),{mutate:I,isPending:_}=rn(),M=_||j||y,{hasPermission:X}=O.usePermissions(),$=X(ve.EDIT_SEO);g.useEffect(()=>{!i&&l&&E({title:"",description:"",cononicalUrl:"",noIndex:!1,noFollow:"",ogTitle:"",ogDescription:"",ogImage:"",searchTitle:"",searchDescription:"",jsonLD:"",...l})},[i,l]);const P=async()=>{if(!(!d||!b))try{p(!0);const k=gs(d,b),q={...S,keyword:m.get(k,"seo.keyword",""),title:m.get(k,"seo.title",""),description:m.get(k,"seo.description",""),cononicalUrl:m.get(k,"seo.canonicalUrl",""),noIndex:m.get(k,"seo.noIndex",!1),noFollow:m.get(k,"seo.noFollow",!1),ogTitle:m.get(k,"seo.ogTitle",""),ogDescription:m.get(k,"seo.ogDescription","")};E(q),D.current.updated=q,J.toast.success(e("SEO fields reset to defaults"))}catch(k){J.toast.error(e("Failed to reset SEO fields")),console.error("Reset SEO error:",k)}finally{p(!1)}},G=async()=>{if(!(!d||!b))try{v(!0);const k=gs(d,b),q={...S,jsonLD:m.get(k,"seo.jsonLD","")};E(q),D.current.updated=q,J.toast.success(e("JSON-LD reset to default"))}catch(k){J.toast.error(e("Failed to reset JSON-LD")),console.error("Reset JSON-LD error:",k)}finally{v(!1)}},H=async()=>{I({id:r==null?void 0:r.id,seo:S},{onSuccess:()=>{D.current.initial=S,D.current.updated=S,s("outline"),J.toast.success("SEO & JSON-LD updated successfully")}})},K=(k,q)=>{const fe=document.getElementById(q);if(fe){const{value:be,newCursorPos:ue}=ql(fe,k);o.current={id:q,position:ue},fe.tagName.toLowerCase()==="input"?(fe.value=be,E(C=>({...C,[fe.name]:be})),fe.focus(),fe.setSelectionRange(ue,ue),[0,10,50,100,200].forEach(C=>{setTimeout(()=>{const F=document.getElementById(q);F&&(F.focus(),F.setSelectionRange(ue,ue))},C)})):(E(x=>({...x,[fe.name]:be})),requestAnimationFrame(()=>{const x=document.getElementById(q);x&&(x.focus(),x.setSelectionRange(ue,ue),setTimeout(()=>{const C=document.getElementById(q);C&&(C.focus(),C.setSelectionRange(ue,ue))},50))}))}},W=k=>{const q={...S,[k.target.name]:k.target.name==="noIndex"||k.target.name==="noFollow"?k.target.checked:k.target.value};E(q),D.current.updated=q},Z=k=>q=>{m.isEmpty(q.fieldValue)||W({target:{name:k,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(pn,{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:M||!$||!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=>K(k,"keyword")})]}),t.jsx(c.Input,{type:"text",id:"keyword",name:"keyword",value:S.keyword,onChange:W,disabled:M||!$,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(Bt,{keyword:S.keyword,onComplete:Z("title"),field:"title"}),$&&t.jsx(Ye,{dataType:"value",data:a??{},onSelect:k=>K(k,"title")})]})]}),t.jsx(c.Input,{type:"text",id:"title",name:"title",value:S.title,onChange:W,disabled:M||!$,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(Bt,{keyword:S.keyword,onComplete:Z("description"),field:"description"}),$&&t.jsx(Ye,{data:a??{},onSelect:k=>K(k,"description")})]})]}),t.jsx(c.Textarea,{id:"description",name:"description",rows:5,value:S.description,onChange:W,disabled:M||!$,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=>K(k,"canonicalUrl")})]}),t.jsx(c.Input,{type:"text",id:"canonicalUrl",name:"canonicalUrl",value:S.canonicalUrl,onChange:W,disabled:M||!$,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:W,disabled:M||!$,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:W,disabled:M||!$,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(Bt,{keyword:S.keyword,onComplete:Z("ogTitle"),field:"ogTitle"}),$&&t.jsx(Ye,{dataType:"value",data:a??{},onSelect:k=>K(k,"ogTitle")})]})]}),t.jsx(c.Input,{type:"text",id:"ogTitle",name:"ogTitle",value:S.ogTitle,onChange:W,disabled:M||!$,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(Bt,{keyword:S.keyword,onComplete:Z("ogDescription"),field:"ogDescription"}),$&&t.jsx(Ye,{dataType:"value",data:a??{},onSelect:k=>K(k,"ogDescription")})]})]}),t.jsx(c.Textarea,{id:"ogDescription",name:"ogDescription",rows:5,value:S.ogDescription,onChange:W,disabled:M||!$,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:k=>{E({...S,ogImage:k.url,ogImageId:k.id})},disabled:M||!$,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:G,disabled:M||!$||!d,children:e(y?"Resetting...":"Reset to Default")})}),t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx(c.Label,{className:"text-xs",htmlFor:"jsonLD",children:e("JSON-LD")}),t.jsx("div",{className:"flex items-center gap-2",children:t.jsx(Bt,{keyword:S.keyword,onComplete:Z("jsonLD"),field:"jsonLD"})})]}),t.jsx("div",{className:"hidden",children:JSON.stringify(a)}),t.jsx(Sa,{id:"jsonLD",value:S.jsonLD,onChange:k=>{W({target:{name:"jsonLD",value:k}})},placeholder:e("Enter JSON-LD"),disabled:M||!$,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:[_n(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:!_n(S==null?void 0:S.jsonLD)||m.isEqual(D.current.initial,S)||M||!$,children:e(_?"Saving...":"Save")}),t.jsx(c.Button,{variant:"link",className:"text-gray-500 hover:text-gray-700",onClick:()=>s("outline"),children:e("Cancel")})]})]})]})};wa.displayName="SeoPanel";const Na="seo",$l=({isActive:e,show:s})=>{const{data:n}=ke(),a=oa(n==null?void 0:n.pageType);return!m.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"})]})})},zl={id:Na,label:"SEO & JSON-LD",panel:wa,button:$l,position:"top",width:600,view:"modal"},$s={},zs=(e,s)=>{m.has($s,e)&&console.warn(`Site setting ${e} already registered. Overriding...`),m.set($s,e,{id:e,...s})},Vl=()=>m.values($s),Kl=()=>{var i;const e=Vl(),[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"})})})})]})},Hl="site-settings",Wl=({isActive:e,show:s})=>O.useChaiFeatureFlag("enable-site-settings")?t.jsx(c.Button,{size:"sm",className:"my-1",onClick:s,variant:e?"default":"ghost",children:t.jsx(N.Settings,{className:"h-4 w-4"})}):null,Ql={id:Hl,label:"Site Settings",panel:Kl,button:Wl,position:"bottom",width:800,view:"modal"},Yl="user-info",Jl=()=>{const{user:e,logout:s}=Fe(),n=R.useQueryClient(),a=qe("onLogout",m.noop);return e?t.jsxs(c.HoverCard,{children:[t.jsx(c.HoverCardTrigger,{asChild:!0,children:t.jsx(c.Button,{variant:"ghost",className:"text-sm font-medium",children:t.jsx(N.User,{className:"w-4 h-4"})})}),t.jsxs(c.HoverCardContent,{className:"w-auto p-4 space-y-2",children:[t.jsx("div",{className:"text-sm font-medium",children:e.name??e.email}),t.jsx("div",{className:"text-xs text-muted-foreground",children:e.email}),t.jsxs(c.AlertDialog,{children:[t.jsx(c.AlertDialogTrigger,{asChild:!0,children:t.jsx(c.Button,{variant:"outline",size:"sm",className:"w-full",children:"Logout"})}),t.jsxs(c.AlertDialogContent,{children:[t.jsxs(c.AlertDialogHeader,{children:[t.jsx(c.AlertDialogTitle,{children:"Are you sure you want to logout?"}),t.jsx(c.AlertDialogDescription,{children:"You will be redirected to the login page."})]}),t.jsxs(c.AlertDialogFooter,{children:[t.jsx(c.AlertDialogCancel,{children:"Cancel"}),t.jsx(c.AlertDialogAction,{onClick:()=>{s(),n.invalidateQueries({queryKey:[Q]}),m.isFunction(a)&&a()},children:"Logout"})]})]})]})]})]}):null},Xl={id:Yl,label:"User Info",button:Jl,position:"bottom"},Zl=()=>{O.registerChaiSidebarPanel(Na,zl),O.registerChaiSidebarPanel(ba,Ml),O.registerChaiSidebarPanel("site-settings",Ql),O.registerChaiSidebarPanel("user-info",Xl)};var re={context:void 0,registry:void 0,effects:void 0,done:!1,getContextId(){return Dn(this.context.count)},getNextContextId(){return Dn(this.context.count++)}};function Dn(e){const s=String(e),n=s.length-1;return re.context.id+(n?String.fromCharCode(96+n):"")+s}function Mt(e){re.context=e}var eo=(e,s)=>e===s,xs=Symbol("solid-proxy"),Ea=typeof Proxy=="function",yn=Symbol("solid-track"),ps={equals:eo},Ca=_a,Qe=1,ys=2,Aa={owned:null,cleanups:null,context:null,owner:null},Gs={},ge=null,Rs=null,to=null,ye=null,_e=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?Aa:{owned:null,cleanups:null,context:i?i.context:null,owner:i},o=r?e:()=>e(()=>Pe(()=>qt(l)));ge=l,ye=null;try{return ze(o,!0)}finally{ye=n,ge=a}}function we(e,s){s=s?Object.assign({},ps,s):ps;const n={value:e,observers:null,observerSlots:null,comparator:s.equals||void 0},a=r=>(typeof r=="function"&&(r=r(n.value)),Ia(n,r));return[La.bind(n),a]}function Ta(e,s,n){const a=ks(e,s,!0,Qe);It(a)}function Xe(e,s,n){const a=ks(e,s,!1,Qe);It(a)}function jn(e,s,n){Ca=xo;const a=ks(e,s,!1,Qe);(!n||!n.render)&&(a.user=!0),Ke?Ke.push(a):It(a)}function Me(e,s,n){n=n?Object.assign({},ps,n):ps;const a=ks(e,s,!0,0);return a.observers=null,a.observerSlots=null,a.comparator=n.equals||void 0,It(a),La.bind(a)}function so(e){return e&&typeof e=="object"&&"then"in e}function no(e,s,n){let a,r,i;arguments.length===1?(a=!0,r=e,i={}):(a=e,r=s,i={});let l=null,o=Gs,u=null,d=!1,h="initialValue"in i,f=typeof a=="function"&&Me(a);const b=new Set,[j,p]=(i.storage||we)(i.initialValue),[y,v]=we(void 0),[S,E]=we(void 0,{equals:!1}),[D,I]=we(h?"ready":"unresolved");re.context&&(u=re.getNextContextId(),i.ssrLoadFrom==="initial"?o=i.initialValue:re.load&&re.has(u)&&(o=re.load(u)));function _(P,G,H,K){return l===P&&(l=null,K!==void 0&&(h=!0),(P===o||G===o)&&i.onHydrated&&queueMicrotask(()=>i.onHydrated(K,{value:G})),o=Gs,M(G,H)),G}function M(P,G){ze(()=>{G===void 0&&p(()=>P),I(G!==void 0?"errored":h?"ready":"unresolved"),v(G);for(const H of b.keys())H.decrement();b.clear()},!1)}function X(){const P=mo,G=j(),H=y();if(H!==void 0&&!l)throw H;return ye&&ye.user,G}function $(P=!0){if(P!==!1&&d)return;d=!1;const G=f?f():a;if(G==null||G===!1){_(l,Pe(j));return}const H=o!==Gs?o:Pe(()=>r(G,{value:j(),refetching:P}));return so(H)?(l=H,"value"in H?(H.status==="success"?_(l,H.value,void 0,G):_(l,void 0,Vs(H.value),G),H):(d=!0,queueMicrotask(()=>d=!1),ze(()=>{I(h?"refreshing":"pending"),E()},!1),H.then(K=>_(H,K,void 0,G),K=>_(H,void 0,Vs(K),G)))):(_(l,H,void 0,G),H)}return Object.defineProperties(X,{state:{get:()=>D()},error:{get:()=>y()},loading:{get(){const P=D();return P==="pending"||P==="refreshing"}},latest:{get(){if(!h)return X();const P=y();if(P&&!l)throw P;return j()}}}),f?Ta(()=>$(!1)):$(!1),[X,{refetch:$,mutate:p}]}function ao(e){return ze(e,!1)}function Pe(e){if(ye===null)return e();const s=ye;ye=null;try{return e()}finally{ye=s}}function ro(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=Pe(()=>s(o,r,l));return r=o,u}}function Pa(e){jn(()=>Pe(e))}function Tt(e){return ge===null||(ge.cleanups===null?ge.cleanups=[e]:ge.cleanups.push(e)),e}function Bn(){return ge}function io(e,s){const n=ge,a=ye;ge=e,ye=null;try{return ze(s,!0)}catch(r){vn(r)}finally{ge=n,ye=a}}function lo(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[oo,vu]=we(!1);function co(){return[oo,lo]}function uo(e,s){const n=Symbol("context");return{id:n,Provider:po(n),defaultValue:e}}function ho(e){let s;return ge&&ge.context&&(s=ge.context[e.id])!==void 0?s:e.defaultValue}function ka(e){const s=Me(e),n=Me(()=>Ks(s()));return n.toArray=()=>{const a=n();return Array.isArray(a)?a:a!=null?[a]:[]},n}var mo;function La(){if(this.sources&&this.state)if(this.state===Qe)It(this);else{const e=_e;_e=null,ze(()=>vs(this),!1),_e=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 Ia(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=Rs&&Rs.running;l&&Rs.disposed.has(i),(l?!i.tState:!i.state)&&(i.pure?_e.push(i):Ke.push(i),i.observers&&Da(i)),l||(i.state=Qe)}if(_e.length>1e6)throw _e=[],new Error},!1)),s}function It(e){if(!e.fn)return;qt(e);const s=Ps;fo(e,e.value,s)}function fo(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=Qe,e.owned&&e.owned.forEach(qt),e.owned=null),e.updatedAt=n+1,vn(l)}finally{ye=i,ge=r}(!e.updatedAt||e.updatedAt<=n)&&(e.updatedAt!=null&&"observers"in e?Ia(e,a):e.value=a,e.updatedAt=n)}function ks(e,s,n,a=Qe,r){const i={fn:e,state:a,updatedAt:null,owned:null,sources:null,sourceSlots:null,cleanups:null,value:s,owner:ge,context:ge?ge.context:null,pure:n};return ge===null||ge!==Aa&&(ge.owned?ge.owned.push(i):ge.owned=[i]),i}function js(e){if(e.state===0)return;if(e.state===ys)return vs(e);if(e.suspense&&Pe(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===Qe)It(e);else if(e.state===ys){const a=_e;_e=null,ze(()=>vs(e,s[0]),!1),_e=a}}function ze(e,s){if(_e)return e();let n=!1;s||(_e=[]),Ke?n=!0:Ke=[],Ps++;try{const a=e();return go(n),a}catch(a){n||(Ke=null),_e=null,vn(a)}}function go(e){if(_e&&(_a(_e),_e=null),e)return;const s=Ke;Ke=null,s.length&&ze(()=>Ca(s),!1)}function _a(e){for(let s=0;s<e.length;s++)js(e[s])}function xo(e){let s,n=0;for(s=0;s<e.length;s++){const a=e[s];a.user?e[n++]=a:js(a)}if(re.context){if(re.count){re.effects||(re.effects=[]),re.effects.push(...e.slice(0,n));return}Mt()}for(re.effects&&(re.done||!re.count)&&(e=[...re.effects,...e],n+=re.effects.length,delete re.effects),s=0;s<n;s++)js(e[s])}function vs(e,s){e.state=0;for(let n=0;n<e.sources.length;n+=1){const a=e.sources[n];if(a.sources){const r=a.state;r===Qe?a!==s&&(!a.updatedAt||a.updatedAt<Ps)&&js(a):r===ys&&vs(a,s)}}}function Da(e){for(let s=0;s<e.observers.length;s+=1){const n=e.observers[s];n.state||(n.state=ys,n.pure?_e.push(n):Ke.push(n),n.observers&&Da(n))}}function qt(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--)qt(e.tOwned[s]);delete e.tOwned}if(e.owned){for(s=e.owned.length-1;s>=0;s--)qt(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 Vs(e){return e instanceof Error?e:new Error(typeof e=="string"?e:"Unknown error",{cause:e})}function vn(e,s=ge){throw Vs(e)}function Ks(e){if(typeof e=="function"&&!e.length)return Ks(e());if(Array.isArray(e)){const s=[];for(let n=0;n<e.length;n++){const a=Ks(e[n]);Array.isArray(a)?s.push.apply(s,a):s.push(a)}return s}return e}function po(e,s){return function(a){let r;return Xe(()=>r=Pe(()=>(ge.context={...ge.context,[e]:a.value},ka(()=>a.children))),void 0),r}}var Hs=Symbol("fallback");function bs(e){for(let s=0;s<e.length;s++)e[s]()}function yo(e,s,n={}){let a=[],r=[],i=[],l=0,o=s.length>1?[]:null;return Tt(()=>bs(i)),()=>{let u=e()||[],d=u.length,h,f;return u[yn],Pe(()=>{let j,p,y,v,S,E,D,I,_;if(d===0)l!==0&&(bs(i),i=[],a=[],r=[],l=0,o&&(o=[])),n.fallback&&(a=[Hs],r[0]=Je(M=>(i[0]=M,n.fallback())),l=1);else if(l===0){for(r=new Array(d),f=0;f<d;f++)a[f]=u[f],r[f]=Je(b);l=d}else{for(y=new Array(d),v=new Array(d),o&&(S=new Array(d)),E=0,D=Math.min(l,d);E<D&&a[E]===u[E];E++);for(D=l-1,I=d-1;D>=E&&I>=E&&a[D]===u[I];D--,I--)y[I]=r[D],v[I]=i[D],o&&(S[I]=o[D]);for(j=new Map,p=new Array(I+1),f=I;f>=E;f--)_=u[f],h=j.get(_),p[f]=h===void 0?-1:h,j.set(_,f);for(h=E;h<=D;h++)_=a[h],f=j.get(_),f!==void 0&&f!==-1?(y[f]=r[h],v[f]=i[h],o&&(S[f]=o[h]),f=p[f],j.set(_,f)):i[h]();for(f=E;f<d;f++)f in y?(r[f]=y[f],i[f]=v[f],o&&(o[f]=S[f],o[f](f))):r[f]=Je(b);r=r.slice(0,l=d),a=u.slice(0)}return r});function b(j){if(i[f]=j,o){const[p,y]=we(f);return o[f]=y,s(u[f],p)}return s(u[f])}}}function jo(e,s,n={}){let a=[],r=[],i=[],l=[],o=0,u;return Tt(()=>bs(i)),()=>{const d=e()||[],h=d.length;return d[yn],Pe(()=>{if(h===0)return o!==0&&(bs(i),i=[],a=[],r=[],o=0,l=[]),n.fallback&&(a=[Hs],r[0]=Je(b=>(i[0]=b,n.fallback())),o=1),r;for(a[0]===Hs&&(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(f));for(;u<a.length;u++)i[u]();return o=l.length=i.length=h,a=d.slice(0),r=r.slice(0,o)});function f(b){i[u]=b;const[j,p]=we(d[u]);return l[u]=p,s(j,u)}}}function bn(e,s){return Pe(()=>e(s||{}))}function cs(){return!0}var Ws={get(e,s,n){return s===xs?n:e.get(s)},has(e,s){return s===xs?!0:e.has(s)},set:cs,deleteProperty:cs,getOwnPropertyDescriptor(e,s){return{configurable:!0,enumerable:!0,get(){return e.get(s)},set:cs,deleteProperty:cs}},ownKeys(e){return e.keys()}};function Fs(e){return(e=typeof e=="function"?e():e)?e:{}}function vo(){for(let e=0,s=this.length;e<s;++e){const n=this[e]();if(n!==void 0)return n}}function Sn(...e){let s=!1;for(let l=0;l<e.length;l++){const o=e[l];s=s||!!o&&xs in o,e[l]=typeof o=="function"?(s=!0,Me(o)):o}if(Ea&&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 f=Object.getOwnPropertyDescriptor(o,h);if(!a[h])a[h]=f.get?{enumerable:!0,configurable:!0,get:vo.bind(n[h]=[f.get.bind(o)])}:f.value!==void 0?f:void 0;else{const b=n[h];b&&(f.get?b.push(f.get.bind(o)):f.value!==void 0&&b.push(()=>f.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 Ba(e,...s){if(Ea&&xs 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 Ma(e){let s,n;const a=r=>{const i=re.context;if(i){const[o,u]=we();re.count||(re.count=0),re.count++,(n||(n=e())).then(d=>{!re.done&&Mt(i),re.count--,u(()=>d.default),Mt()}),s=o}else if(!s){const[o]=no(()=>(n||(n=e())).then(u=>u.default));s=o}let l;return Me(()=>(l=s())?Pe(()=>{if(!i||re.done)return l(r);const o=re.context;Mt(i);const u=l(r);return Mt(o),u}):"")};return a.preload=()=>n||((n=e()).then(r=>s=()=>r.default),n),a}var bo=0;function So(){return re.context?re.getNextContextId():`cl-${bo++}`}var Ga=e=>`Stale read from <${e}>.`;function wo(e){const s="fallback"in e&&{fallback:()=>e.fallback};return Me(yo(()=>e.each,e.children,s||void 0))}function No(e){const s="fallback"in e&&{fallback:()=>e.fallback};return Me(jo(()=>e.each,e.children,s||void 0))}function Eo(e){const s=e.keyed,n=Me(()=>e.when,void 0,{equals:(a,r)=>s?a===r:!a==!r});return Me(()=>{const a=n();if(a){const r=e.children;return typeof r=="function"&&r.length>0?Pe(()=>r(s?a:()=>{if(!Pe(n))throw Ga("Show");return e.when})):r}return e.fallback},void 0,void 0)}function Co(e){let s=!1;const n=(i,l)=>(s?i[1]===l[1]:!i[1]==!l[1])&&i[2]===l[2],a=ka(()=>e.children),r=Me(()=>{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 Me(()=>{const[i,l,o]=r();if(i<0)return e.fallback;const u=o.children;return typeof u=="function"&&u.length>0?Pe(()=>u(s?l:()=>{if(Pe(r)[0]!==i)throw Ga("Match");return o.when})):u},void 0,void 0)}function Ao(e){return e}var To=["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",...To]),ko=new Set(["innerHTML","textContent","innerText","children"]),Lo=Object.assign(Object.create(null),{className:"class",htmlFor:"for"}),Io=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 _o(e,s){const n=Io[e];return typeof n=="object"?n[s]?n.$:void 0:n}var Do=new Set(["beforeinput","click","dblclick","contextmenu","focusin","focusout","input","keydown","keyup","mousedown","mousemove","mouseout","mouseover","mouseup","pointerdown","pointermove","pointerout","pointerover","pointerup","touchend","touchmove","touchstart"]),Bo=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 Go(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 f=o;for(;f<i;)d.set(n[f],f++)}const h=d.get(s[l]);if(h!=null)if(o<h&&h<i){let f=l,b=1,j;for(;++f<r&&f<i&&!((j=d.get(s[f]))==null||j!==h+b);)b++;if(b>h-o){const p=s[l];for(;o<h;)e.insertBefore(n[o++],p)}else e.replaceChild(n[o++],s[l++])}else l++;else s[l++].remove()}}}var Ot="_$DX_DELEGATE";function Ra(e,s,n,a={}){let r;return Je(i=>{r=i,s===document?e():ws(s,e(),s.firstChild?null:void 0,n)},a.owner),()=>{r(),s.textContent=""}}function Ro(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 Fa(e,s=window.document){const n=s[Ot]||(s[Ot]=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,za))}}function Fo(e=window.document){if(e[Ot]){for(let s of e[Ot].keys())e.removeEventListener(s,za);delete e[Ot]}}function Ss(e,s,n){ut(e)||(n==null?e.removeAttribute(s):e.setAttribute(s,n))}function Oo(e,s,n,a){ut(e)||(a==null?e.removeAttributeNS(s,n):e.setAttributeNS(s,n,a))}function Uo(e,s,n){ut(e)||(n?e.setAttribute(s,""):e.removeAttribute(s))}function Oa(e,s){ut(e)||(s==null?e.removeAttribute("class"):e.className=s)}function Ua(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 qo(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 $o(e,s,n){if(!s)return n?Ss(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 qa(e,s={},n,a){const r={};return a||Xe(()=>r.children=$t(e,s.children,r.children)),Xe(()=>typeof s.ref=="function"&&$a(s.ref,e)),Xe(()=>zo(e,s,n,!0,r,!0)),r}function $a(e,s,n){return Pe(()=>e(s,n))}function ws(e,s,n,a){if(n!==void 0&&!a&&(a=[]),typeof s!="function")return $t(e,s,a,n);Xe(r=>$t(e,s(),r,n),a)}function zo(e,s,n,a,r={},i=!1){s||(s={});for(const l in r)if(!(l in s)){if(l==="children")continue;r[l]=Gn(e,l,null,r[l],n,i,s)}for(const l in s){if(l==="children")continue;const o=s[l];r[l]=Gn(e,l,o,r[l],n,i,s)}}function Vo(e){let s,n;return!ut()||!(s=re.registry.get(n=Ho()))?e():(re.completed&&re.completed.add(s),re.registry.delete(n),s)}function ut(e){return!!re.context&&!re.done&&(!e||e.isConnected)}function Ko(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 Gn(e,s,n,a,r,i,l){let o,u,d,h,f;if(s==="style")return $o(e,n,a);if(s==="classList")return qo(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=Do.has(b);if(!j&&a){const p=Array.isArray(a)?a[0]:a;e.removeEventListener(b,p)}(j||n)&&(Ua(e,b,n,j),j&&Fa([b]))}else if(s.slice(0,5)==="attr:")Ss(e,s.slice(5),n);else if(s.slice(0,5)==="bool:")Uo(e,s.slice(5),n);else if((f=s.slice(0,5)==="prop:")||(d=ko.has(s))||!r&&((h=_o(s,e.tagName))||(u=Po.has(s)))||(o=e.nodeName.includes("-")||"is"in l)){if(f)s=s.slice(5),u=!0;else if(ut(e))return n;s==="class"||s==="className"?Oa(e,n):o&&!u&&!d?e[Ko(s)]=n:e[h||s]=n}else{const b=r&&s.indexOf(":")>-1&&Mo[s.split(":")[0]];b?Oo(e,b,s,n):Ss(e,Lo[s]||s,n)}return n}function za(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 $t(e,s,n,a,r){const i=ut(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=dt(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=dt(e,n,a)}else{if(l==="function")return Xe(()=>{let u=s();for(;typeof u=="function";)u=u();n=$t(e,u,n,a)}),()=>n;if(Array.isArray(s)){const u=[],d=n&&Array.isArray(n);if(Qs(u,s,n,r))return Xe(()=>n=$t(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 f=[h];for(;(h=h.nextSibling)!==a;)f.push(h);return n=f}if(u.length===0){if(n=dt(e,n,a),o)return n}else d?n.length===0?Rn(e,u,a):Go(e,n,u):(n&&dt(e),Rn(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=dt(e,n,a,s);dt(e,n,null,s)}else n==null||n===""||!e.firstChild?e.appendChild(s):e.replaceChild(s,e.firstChild);n=s}}return n}function Qs(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=Qs(e,o,u)||r;else if(d==="function")if(a){for(;typeof o=="function";)o=o();r=Qs(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 Rn(e,s,n=null){for(let a=0,r=s.length;a<r;a++)e.insertBefore(s[a],n)}function dt(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 Ho(){return re.getNextContextId()}var Wo="http://www.w3.org/2000/svg";function Va(e,s=!1){return s?document.createElementNS(Wo,e):document.createElement(e)}function Qo(e){const{useShadow:s}=e,n=document.createTextNode(""),a=()=>e.mount||document.body,r=Bn();let i,l=!!re.context;return jn(()=>{l&&(Bn().user=l=!1),i||(i=io(r,()=>Me(()=>e.children)));const o=a();if(o instanceof HTMLHeadElement){const[u,d]=we(!1),h=()=>d(!0);Je(f=>ws(o,()=>u()?f():i(),null)),Tt(h)}else{const u=Va(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}),ws(d,i),o.appendChild(u),e.ref&&e.ref(u),Tt(()=>o.removeChild(u))}},void 0,{render:!l}),n}function Yo(e){const[s,n]=Ba(e,["component"]),a=Me(()=>s.component);return Me(()=>{const r=a();switch(typeof r){case"function":return Pe(()=>r(n));case"string":const i=Bo.has(r),l=re.context?Vo():Va(r,i);return qa(l,n,i),l}})}var Jo=class{constructor(){this.keyToValue=new Map,this.valueToKey=new Map}set(e,s){this.keyToValue.set(e,s),this.valueToKey.set(s,e)}getByKey(e){return this.keyToValue.get(e)}getByValue(e){return this.valueToKey.get(e)}clear(){this.keyToValue.clear(),this.valueToKey.clear()}},Ka=class{constructor(e){this.generateIdentifier=e,this.kv=new Jo}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)}},Xo=class extends Ka{constructor(){super(e=>e.name),this.classToAllowedProps=new Map}register(e,s){typeof s=="object"?(s.allowProps&&this.classToAllowedProps.set(e,s.allowProps),super.register(e,s.identifier)):super.register(e,s)}getAllowedProps(e){return this.classToAllowedProps.get(e)}};function Zo(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 ec(e,s){const n=Zo(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 ms(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 tc=class{constructor(){this.transfomers={}}register(e){this.transfomers[e.name]=e}findApplicable(e){return ec(this.transfomers,s=>s.isApplicable(e))}findByName(e){return this.transfomers[e]}},sc=e=>Object.prototype.toString.call(e).slice(8,-1),Ha=e=>typeof e>"u",nc=e=>e===null,zt=e=>typeof e!="object"||e===null||e===Object.prototype?!1:Object.getPrototypeOf(e)===null?!0:Object.getPrototypeOf(e)===Object.prototype,Ys=e=>zt(e)&&Object.keys(e).length===0,et=e=>Array.isArray(e),ac=e=>typeof e=="string",rc=e=>typeof e=="number"&&!isNaN(e),ic=e=>typeof e=="boolean",lc=e=>e instanceof RegExp,Vt=e=>e instanceof Map,Kt=e=>e instanceof Set,Wa=e=>sc(e)==="Symbol",oc=e=>e instanceof Date&&!isNaN(e.valueOf()),cc=e=>e instanceof Error,On=e=>typeof e=="number"&&isNaN(e),uc=e=>ic(e)||nc(e)||Ha(e)||rc(e)||ac(e)||Wa(e),dc=e=>typeof e=="bigint",hc=e=>e===1/0||e===-1/0,mc=e=>ArrayBuffer.isView(e)&&!(e instanceof DataView),fc=e=>e instanceof URL,Qa=e=>e.replace(/\./g,"\\."),Os=e=>e.map(String).map(Qa).join("."),Ut=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 Ya=[$e(Ha,"undefined",()=>null,()=>{}),$e(dc,"bigint",e=>e.toString(),e=>typeof BigInt<"u"?BigInt(e):e),$e(oc,"Date",e=>e.toISOString(),e=>new Date(e)),$e(cc,"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(lc,"regexp",e=>""+e,e=>{const s=e.slice(1,e.lastIndexOf("/")),n=e.slice(e.lastIndexOf("/")+1);return new RegExp(s,n)}),$e(Kt,"set",e=>[...e.values()],e=>new Set(e)),$e(Vt,"map",e=>[...e.entries()],e=>new Map(e)),$e(e=>On(e)||hc(e),"number",e=>On(e)?"NaN":e>0?"Infinity":"-Infinity",Number),$e(e=>e===0&&1/e===-1/0,"number",()=>"-0",Number),$e(fc,"URL",e=>e.toString(),e=>new URL(e))];function Ls(e,s,n,a){return{isApplicable:e,annotation:s,transform:n,untransform:a}}var Ja=Ls((e,s)=>Wa(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}),gc=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,Uint8ClampedArray].reduce((e,s)=>(e[s.name]=s,e),{}),Xa=Ls(mc,e=>["typed-array",e.constructor.name],e=>[...e],(e,s)=>{const n=gc[s[1]];if(!n)throw new Error("Trying to deserialize unknown typed array");return new n(e)});function Za(e,s){return e!=null&&e.constructor?!!s.classRegistry.getIdentifier(e.constructor):!1}var er=Ls(Za,(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)}),tr=Ls((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)}),xc=[er,Ja,tr,Xa],Un=(e,s)=>{const n=Fn(xc,r=>r.isApplicable(e,s));if(n)return{value:n.transform(e,s),type:n.annotation(e,s)};const a=Fn(Ya,r=>r.isApplicable(e,s));if(a)return{value:a.transform(e,s),type:a.annotation}},sr={};Ya.forEach(e=>{sr[e.annotation]=e});var pc=(e,s,n)=>{if(et(s))switch(s[0]){case"symbol":return Ja.untransform(e,s,n);case"class":return er.untransform(e,s,n);case"custom":return tr.untransform(e,s,n);case"typed-array":return Xa.untransform(e,s,n);default:throw new Error("Unknown transformation: "+s)}else{const a=sr[s];if(!a)throw new Error("Unknown transformation: "+s);return a.untransform(e,n)}},ht=(e,s)=>{const n=e.keys();for(;s>0;)n.next(),s--;return n.next().value};function nr(e){if(ms(e,"__proto__"))throw new Error("__proto__ is not allowed as a property");if(ms(e,"prototype"))throw new Error("prototype is not allowed as a property");if(ms(e,"constructor"))throw new Error("constructor is not allowed as a property")}var yc=(e,s)=>{nr(s);for(let n=0;n<s.length;n++){const a=s[n];if(Kt(e))e=ht(e,+a);else if(Vt(e)){const r=+a,i=+s[++n]==0?"key":"value",l=ht(e,r);switch(i){case"key":e=l;break;case"value":e=e.get(l);break}}else e=e[a]}return e},Js=(e,s,n)=>{if(nr(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(zt(a))a=a[l];else if(Kt(a)){const o=+l;a=ht(a,o)}else if(Vt(a)){if(i===s.length-2)break;const u=+l,d=+s[++i]==0?"key":"value",h=ht(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]):zt(a)&&(a[r]=n(a[r])),Kt(a)){const i=ht(a,+r),l=n(i);i!==l&&(a.delete(i),a.add(l))}if(Vt(a)){const i=+s[s.length-2],l=ht(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 Xs(e,s,n=[]){if(!e)return;if(!et(e)){Pt(e,(i,l)=>Xs(i,s,[...n,...Ut(l)]));return}const[a,r]=e;r&&Pt(r,(i,l)=>{Xs(i,s,[...n,...Ut(l)])}),s(a,n)}function jc(e,s,n){return Xs(s,(a,r)=>{e=Js(e,r,i=>pc(i,a,n))}),e}function vc(e,s){function n(a,r){const i=yc(e,Ut(r));a.map(Ut).forEach(l=>{e=Js(e,l,()=>i)})}if(et(s)){const[a,r]=s;a.forEach(i=>{e=Js(e,Ut(i),()=>e)}),r&&Pt(r,n)}else Pt(s,n);return e}var bc=(e,s)=>zt(e)||et(e)||Vt(e)||Kt(e)||Za(e,s);function Sc(e,s,n){const a=n.get(e);a?a.push(s):n.set(e,[s])}function wc(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?Ys(n)?[a]:[a,n]:Ys(n)?void 0:n}var ar=(e,s,n,a,r=[],i=[],l=new Map)=>{const o=uc(e);if(!o){Sc(e,r,s);const j=l.get(e);if(j)return a?{transformedValue:null}:j}if(!bc(e,n)){const j=Un(e,n),p=j?{transformedValue:j.value,annotations:[j.type]}:{transformedValue:e};return o||l.set(e,p),p}if(ms(i,e))return{transformedValue:null};const u=Un(e,n),d=(u==null?void 0:u.value)??e,h=et(d)?[]:{},f={};Pt(d,(j,p)=>{if(p==="__proto__"||p==="constructor"||p==="prototype")throw new Error(`Detected property ${p}. This is a prototype pollution risk, please remove it from your object.`);const y=ar(j,s,n,a,[...r,p],[...i,e],l);h[p]=y.transformedValue,et(y.annotations)?f[p]=y.annotations:zt(y.annotations)&&Pt(y.annotations,(v,S)=>{f[Qa(p)+"."+S]=v})});const b=Ys(f)?{transformedValue:h,annotations:u?[u.type]:void 0}:{transformedValue:h,annotations:u?[u.type,f]:f};return o||l.set(e,b),b};function rr(e){return Object.prototype.toString.call(e).slice(8,-1)}function qn(e){return rr(e)==="Array"}function Nc(e){if(rr(e)!=="Object")return!1;const s=Object.getPrototypeOf(e);return!!s&&s.constructor===Object&&s===Object.prototype}function Ec(e,s,n,a,r){const i={}.propertyIsEnumerable.call(a,s)?"enumerable":"nonenumerable";i==="enumerable"&&(e[s]=n),r&&i==="nonenumerable"&&Object.defineProperty(e,s,{value:n,enumerable:!1,writable:!0,configurable:!0})}function Zs(e,s={}){if(qn(e))return e.map(r=>Zs(r,s));if(!Nc(e))return e;const n=Object.getOwnPropertyNames(e),a=Object.getOwnPropertySymbols(e);return[...n,...a].reduce((r,i)=>{if(qn(s.props)&&!s.props.includes(i))return r;const l=e[i],o=Zs(l,s);return Ec(r,i,o,e,s.nonenumerable),r},{})}var je=class{constructor({dedupe:e=!1}={}){this.classRegistry=new Xo,this.symbolRegistry=new Ka(s=>s.description??""),this.customTransformerRegistry=new tc,this.allowedErrorProps=[],this.dedupe=e}serialize(e){const s=new Map,n=ar(e,s,this,this.dedupe),a={json:n.transformedValue};n.annotations&&(a.meta={...a.meta,values:n.annotations});const r=wc(s,this.dedupe);return r&&(a.meta={...a.meta,referentialEqualities:r}),a}deserialize(e){const{json:s,meta:n}=e;let a=Zs(s);return n!=null&&n.values&&(a=jc(a,n.values,this)),n!=null&&n.referentialEqualities&&(a=vc(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 ir=je.serialize,Cc=je.stringify;function Ac(e){return e.state.fetchStatus==="fetching"?"fetching":e.getObserversCount()?e.state.fetchStatus==="paused"?"paused":e.isStale()?"stale":"fresh":"inactive"}function Tc(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 kc({status:e,isPaused:s}){return s?"purple":e==="error"?"red":e==="pending"?"yellow":e==="success"?"green":"gray"}function Lc(e){return e==="fresh"?"green":e==="stale"?"yellow":e==="paused"?"purple":e==="inactive"?"gray":"blue"}var Ic=(e,s=!1)=>{const{json:n}=ir(e);return JSON.stringify(n,null,s?2:void 0)},us=e=>e.state.fetchStatus!=="idle"?0:e.getObserversCount()?e.isStale()?2:1:3,_c=(e,s)=>e.queryHash.localeCompare(s.queryHash),lr=(e,s)=>e.state.dataUpdatedAt<s.state.dataUpdatedAt?1:-1,Dc=(e,s)=>us(e)===us(s)?lr(e,s):us(e)>us(s)?1:-1,Bc={status:Dc,"query hash":_c,"last updated":lr},ds=e=>e.state.isPaused?0:e.state.status==="error"?2:e.state.status==="pending"?1:3,or=(e,s)=>e.state.submittedAt<s.state.submittedAt?1:-1,Mc=(e,s)=>ds(e)===ds(s)?or(e,s):ds(e)>ds(s)?1:-1,Gc={status:Mc,"last updated":or},Rc=e=>e*parseFloat(getComputedStyle(document.documentElement).fontSize),Fc=()=>{const[e,s]=we("dark");return Pa(()=>{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),Tt(()=>n.removeEventListener("change",a))}),e},Gt=(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,Gt(a.get(r),i,n)),a}if(e instanceof Set){const a=Gt(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]=Gt(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]=Gt(a[r],i,n),a}return e},Rt=(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,Rt(n.get(a),r)),n}if(e instanceof Set){const n=Rt(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]=Rt(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]=Rt(n[a],r),n}return e},cr=(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)},mt,Ht,Wt,Qt,rt,Yt,ft,gt,xt,pt,yt,jt,Jt,Vn,Oc=(Vn=class{constructor(e){pe(this,mt);pe(this,Ht);pe(this,Wt);pe(this,Qt);pe(this,rt,!1);pe(this,Yt);pe(this,ft);pe(this,gt);pe(this,xt);pe(this,pt);pe(this,yt);pe(this,jt);pe(this,Jt);const{client:s,queryFlavor:n,version:a,onlineManager:r,buttonPosition:i,position:l,initialIsOpen:o,errorTypes:u,styleNonce:d,shadowDOMTarget:h}=e;xe(this,mt,we(s)),xe(this,Wt,n),xe(this,Qt,a),xe(this,Ht,r),xe(this,Yt,d),xe(this,ft,h),xe(this,gt,we(i)),xe(this,xt,we(l)),xe(this,pt,we(o)),xe(this,yt,we(u))}setButtonPosition(e){ae(this,gt)[1](e)}setPosition(e){ae(this,xt)[1](e)}setInitialIsOpen(e){ae(this,pt)[1](e)}setErrorTypes(e){ae(this,yt)[1](e)}setClient(e){ae(this,mt)[1](e)}mount(e){if(ae(this,rt))throw new Error("Devtools is already mounted");const s=Ra(()=>{const n=this,[a]=ae(this,gt),[r]=ae(this,xt),[i]=ae(this,pt),[l]=ae(this,yt),[o]=ae(this,mt);let u;return ae(this,jt)?u=ae(this,jt):(u=Ma(()=>Promise.resolve().then(()=>require("./HO4MOOFI-BKupoTZW.cjs"))),xe(this,jt,u)),cr(ae(this,Yt),ae(this,ft)),bn(u,Sn({get queryFlavor(){return ae(n,Wt)},get version(){return ae(n,Qt)},get onlineManager(){return ae(n,Ht)},get shadowDOMTarget(){return ae(n,ft)}},{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,Jt,s)}unmount(){var e;if(!ae(this,rt))throw new Error("Devtools is not mounted");(e=ae(this,Jt))==null||e.call(this),xe(this,rt,!1)}},mt=new WeakMap,Ht=new WeakMap,Wt=new WeakMap,Qt=new WeakMap,rt=new WeakMap,Yt=new WeakMap,ft=new WeakMap,gt=new WeakMap,xt=new WeakMap,pt=new WeakMap,yt=new WeakMap,jt=new WeakMap,Jt=new WeakMap,Vn),vt,Xt,Zt,es,it,ts,bt,St,wt,Nt,Et,Ct,At,ss,Kn,Uc=(Kn=class{constructor(e){pe(this,vt);pe(this,Xt);pe(this,Zt);pe(this,es);pe(this,it,!1);pe(this,ts);pe(this,bt);pe(this,St);pe(this,wt);pe(this,Nt);pe(this,Et);pe(this,Ct);pe(this,At);pe(this,ss);const{client:s,queryFlavor:n,version:a,onlineManager:r,buttonPosition:i,position:l,initialIsOpen:o,errorTypes:u,styleNonce:d,shadowDOMTarget:h,onClose:f}=e;xe(this,vt,we(s)),xe(this,Zt,n),xe(this,es,a),xe(this,Xt,r),xe(this,ts,d),xe(this,bt,h),xe(this,St,we(i)),xe(this,wt,we(l)),xe(this,Nt,we(o)),xe(this,Et,we(u)),xe(this,Ct,we(f))}setButtonPosition(e){ae(this,St)[1](e)}setPosition(e){ae(this,wt)[1](e)}setInitialIsOpen(e){ae(this,Nt)[1](e)}setErrorTypes(e){ae(this,Et)[1](e)}setClient(e){ae(this,vt)[1](e)}setOnClose(e){ae(this,Ct)[1](()=>e)}mount(e){if(ae(this,it))throw new Error("Devtools is already mounted");const s=Ra(()=>{const n=this,[a]=ae(this,St),[r]=ae(this,wt),[i]=ae(this,Nt),[l]=ae(this,Et),[o]=ae(this,vt),[u]=ae(this,Ct);let d;return ae(this,At)?d=ae(this,At):(d=Ma(()=>Promise.resolve().then(()=>require("./HUY7CZI3-f1kYJ8XZ.cjs"))),xe(this,At,d)),cr(ae(this,ts),ae(this,bt)),bn(d,Sn({get queryFlavor(){return ae(n,Zt)},get version(){return ae(n,es)},get onlineManager(){return ae(n,Xt)},get shadowDOMTarget(){return ae(n,bt)}},{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,ss,s)}unmount(){var e;if(!ae(this,it))throw new Error("Devtools is not mounted");(e=ae(this,ss))==null||e.call(this),xe(this,it,!1)}},vt=new WeakMap,Xt=new WeakMap,Zt=new WeakMap,es=new WeakMap,it=new WeakMap,ts=new WeakMap,bt=new WeakMap,St=new WeakMap,wt=new WeakMap,Nt=new WeakMap,Et=new WeakMap,Ct=new WeakMap,At=new WeakMap,ss=new WeakMap,Kn);function qc(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 $c(e){const s=R.useQueryClient(e.client),n=Se.useRef(null),{errorTypes:a,styleNonce:r,shadowDOMTarget:i}=e,[l]=Se.useState(new Uc({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 zc=process.env.NODE_ENV!=="development"?function(){return null}:qc;process.env.NODE_ENV;const ur=()=>t.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center w-screen h-screen bg-white/40",children:t.jsx("div",{className:"flex items-center justify-center bg-white rounded-full size-10",children:t.jsx(N.Loader2,{className:"size-5 animate-spin"})})}),Vc=()=>{O.registerChaiFeatureFlag("dynamic-page-selector",{description:"Dynamic page selector"}),O.registerChaiFeatureFlag("realtime-page-lock",{description:"Realtime page lock"}),O.registerChaiFeatureFlag("enable-add-page-dropdown",{description:"Enable add page dropdown"}),O.registerChaiFeatureFlag("enable-page-revisions-compare",{description:"Page revisions compare"}),O.registerChaiFeatureFlag("enable-page-manager-v2",{description:"Page manager v2"}),O.registerChaiFeatureFlag("enable-site-settings",{description:"Site settings"})},Kc=()=>{const e=oe(),s=ee();return R.useQuery({queryKey:[Q,L.GET_COLLECTIONS],initialData:[],queryFn:async()=>s(e,{action:L.GET_COLLECTIONS})})},Hc=()=>{const{data:e}=ke(),{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:L.GET_BLOCK_ASYNC_PROPS,data:{block:l,lang:(s==null?void 0:s.lang)||i,pageProps:{slug:s==null?void 0:s.slug,searchParams:{},pageType:s==null?void 0:s.pageType,fallbackLang:i,lastSaved:s.lastSaved,pageId:e.id,primaryPageId:s.primaryPage||e.id,pageBaseSlug:s==null?void 0:s.slug,dynamic:e==null?void 0:e.dynamic,languagePageId:s.id}}})})},dr=()=>{const e=un();return g.useCallback(({pageId:s})=>{e(s)},[e])},Wc=60*5;function Qc(){const{user:e,setUser:s,logout:n,isLoggedIn:a,isSessionExpired:r}=Fe(),i=Es(),l=g.useRef(null),o=qe("getAccessToken",!1),u=g.useCallback(async()=>{if(o===!1&&!(!m.has(e,"expiresAt")||!m.has(e,"accessToken")||!m.has(e,"refreshToken")))try{const d=await en(i,{action:"REFRESH_TOKEN",data:{refreshToken:e.refreshToken,accessToken:e.accessToken}});if(!d.ok){n();return}const h=await d.json();m.has(h,"id")&&m.has(h,"email")&&m.has(h,"accessToken")&&m.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||!m.has(e,"expiresAt")||!m.has(e,"refreshToken")||!m.has(e,"accessToken")){l.current&&(clearInterval(l.current),l.current=null);return}return l.current||(l.current=setInterval(()=>{if(!m.has(e,"expiresAt")||!m.has(e,"refreshToken")||!m.has(e,"accessToken"))return;const 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 Yc=({isActive:e,onClick:s})=>t.jsx(c.Button,{variant:e?"default":"ghost",className:"w-full justify-start text-left",onClick:s,children:"General"}),Jc=()=>{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"})})]})]})},Xc=()=>{const e=ns(),s=R.useQueryClient(),n=ee();return R.useMutation({mutationFn:async({file:a,folderId:r,name:i,optimize:l=!0})=>n(e,{action:L.UPLOAD_ASSET,data:{file:a,folderId:r,name:i,optimize:l}}),onSuccess:a=>{if(a!=null&&a.error)throw new Error(a==null?void 0:a.error);s.invalidateQueries({queryKey:[Q,L.GET_ASSETS]}),J.toast.success("Asset uploaded successfully")},onError:()=>{J.toast.error("Failed to upload asset")}})},Zc=()=>{const e=ns(),s=R.useQueryClient(),n=ee();return R.useMutation({mutationFn:async a=>n(e,{action:L.DELETE_ASSET,data:{id:a}}),onSuccess:a=>{if(a!=null&&a.error)throw new Error(a==null?void 0:a.error);s.invalidateQueries({queryKey:[Q,L.GET_ASSETS]}),J.toast.success("Asset deleted successfully")},onError:()=>{J.toast.error("Failed to delete asset")}})},eu=()=>{const e=ns(),s=R.useQueryClient(),n=ee();return R.useMutation({mutationFn:async a=>n(e,{action:L.UPDATE_ASSET,data:a}),onSuccess:a=>{if(a!=null&&a.error)throw new Error(a==null?void 0:a.error);s.invalidateQueries({queryKey:[Q,L.GET_ASSETS]}),J.toast.success("Asset updated successfully")},onError:()=>{J.toast.error("Failed to update asset")}})},tu=(e={})=>{const s=ns(),n=ee(),{search:a,page:r=1,limit:i=30}=e;return R.useQuery({queryKey:[Q,L.GET_ASSETS,a,r,i],queryFn:async()=>{const l=await n(s,{action:L.GET_ASSETS,data:{search:a,page:r,limit:i}});return l.page=r,l.limit=i,l},staleTime:1e3*60*5,retry:1})},su=e=>{const s=ns(),n=ee();return R.useQuery({queryKey:[Q,L.GET_ASSET,e],queryFn:async()=>e?await n(s,{action:L.GET_ASSET,data:{id:e}}):null,staleTime:1e3*60*5,retry:1})};function nu(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 $n(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 zn(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 au=({assetId:e,onBack:s,onEdit:n,onSave:a,isSaving:r})=>{var f,b,j;const{data:i,isLoading:l,isError:o}=su(e||""),[u,d]=g.useState(""),h=async(p,y)=>{try{await navigator.clipboard.writeText(p),J.toast.success(`${y} copied to clipboard`)}catch(v){J.toast.error(`Failed to copy ${y}`,{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(N.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(N.AlertCircle,{className:"h-12 w-12 text-gray-400"})}),t.jsx("h3",{className:"text-lg font-medium text-gray-900 mb-2",children:"No Asset Found"}),t.jsx("p",{className:"text-sm text-gray-500 mb-6",children:o?"There was an error loading the asset. Please try again later.":"The asset you're looking for doesn't exist or has been removed."}),t.jsxs("div",{className:"flex justify-center gap-4",children:[t.jsx(c.Button,{variant:"outline",onClick:s,children:"Back to Assets"}),o&&t.jsx(c.Button,{variant:"default",onClick:()=>window.location.reload(),children:"Try Again"})]})]})}):t.jsxs("div",{className:"flex-1 flex flex-col gap-y-4 overflow-hidden",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsxs(c.Button,{variant:"outline",size:"sm",onClick:s,disabled:r,children:[t.jsx(N.ChevronLeft,{className:"h-4 w-4"}),"Back to Assets"]}),t.jsxs("div",{className:"flex gap-2",children:[t.jsx(c.Button,{variant:"outline",onClick:s,disabled:r,children:"Cancel"}),t.jsxs(c.Button,{variant:"outline",onClick:()=>h(i.url,"Asset URL"),disabled:r,children:[t.jsx(N.Copy,{className:"h-4 w-4 mr-2"}),"Copy URL"]}),t.jsxs(c.Button,{variant:"default",onClick:()=>n(i),disabled:r,children:[t.jsx(N.Pencil,{className:"h-4 w-4"}),"Edit Image"]})]})]}),t.jsxs("div",{className:"grid grid-cols-2 items-start gap-6 flex-1 overflow-hidden",children:[t.jsx("div",{className:"relative h-[calc(80vh-200px)] w-full flex items-start justify-center",children:t.jsx("img",{src:`${i.url}?v=${((f=i.metadata)==null?void 0:f.updatedAt)||i.createdAt}`,alt:i.name,className:"w-full h-full object-contain rounded-lg max-h-max max-w-max"})}),t.jsxs("div",{className:"space-y-6",children:[t.jsxs("div",{className:"grid gap-3 border rounded-md pt-2 bg-gray-100",children:[t.jsx(c.Label,{className:"w-full text-center",children:"Details"}),t.jsx("div",{className:"grid grid-cols-1 gap-2 text-sm border rounded-md p-2 bg-white",children:[{label:"File Name",value:i.name},{label:"Type",value:i.type,capitalize:!0},{label:"Format",value:((b=i.metadata)==null?void 0:b.format)||i.type,capitalize:!0},{label:"Size",value:nu(i.size)},{label:"Dimensions",value:`${i.width||0} × ${i.height||0}`},{label:"Created",value:$n(i.createdAt)},{label:"Updated",value:$n(((j=i.metadata)==null?void 0:j.updatedAt)||i.createdAt)},{label:"URL",value:i.url,copyable:!0}].map(p=>t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(c.Label,{className:"w-max text-left px-2 w-1/4 font-normal text-gray-700",children:p.label}),":",t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("div",{className:"w-max text-left font-medium text-gray-900"+(p.capitalize?" capitalize":""),children:p.value}),p.copyable&&t.jsx(c.Button,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>h(p.value,p.label),children:t.jsx(N.Link,{className:"h-3 w-3"})})]})]},p.label))})]}),i.usedOn&&i.usedOn.length>0&&t.jsxs("div",{className:"grid gap-3",children:[t.jsx(c.Label,{children:"Used On"}),t.jsx("div",{className:"grid grid-cols-1 gap-2 text-sm border rounded-md p-2",children:i.usedOn.map((p,y)=>t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("div",{className:"w-max text-left font-medium text-gray-900",children:p.name}),t.jsxs("div",{className:"text-gray-500",children:["(",p.slug,")"]})]},y))})]}),t.jsxs("div",{className:"grid gap-3 border rounded-md pt-2 bg-gray-100 relative",children:[t.jsx(c.Label,{className:"w-full text-center",children:"Description"}),t.jsx(c.Textarea,{id:"description",value:u,placeholder:"Enter a description for the asset",onChange:p=>d(p.target.value),rows:3,disabled:r,className:"hover:border-black/40 bg-white"}),t.jsx("div",{className:"flex justify-end items-start absolute top-1.5 right-2",children:t.jsx("button",{type:"button",onClick:()=>a(u),disabled:r||!zn(u,i),className:`py-0 bg-blue-500 text-white px-3 py-0.5 rounded-md text-sm ${r||!zn(u,i)?"opacity-50 cursor-not-allowed":""}`,children:r?t.jsxs(t.Fragment,{children:[t.jsx(N.Loader,{className:"h-4 w-4 mr-2 animate-spin"}),"Saving..."]}):"Save"})})]})]})]})]})},ru=g.lazy(()=>Promise.resolve().then(()=>require("./image-editor-BWLJT1mr.cjs")));function iu(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 lu=({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((p,y)=>{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:E=>{i&&i(E),p(E)},onError:E=>{y(E)}})},S.onerror=E=>y(E)}),[a,l,i]),{getRootProps:h,getInputProps:f,isDragActive:b}=pr.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:O.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",{...f()}),u?t.jsx("div",{className:"flex flex-col items-center px-6",children:t.jsxs("div",{className:"leading-tight flex items-center justify-center gap-2",children:[t.jsx("div",{className:"flex items-center justify-center rounded-full bg-indigo-100 p-2",children:t.jsx(N.Loader,{className:"h-4 w-4 text-indigo-500 animate-spin"})}),t.jsxs("div",{className:"text-left",children:[t.jsx("div",{className:"font-medium",children:e?"Updating file...":"Uploading file..."}),t.jsxs("div",{className:"text-xs text-muted-foreground font-light",children:["Please wait while we ",e?"update":"upload"," ","your file..."]})]})]})}):t.jsxs("div",{className:"flex items-center justify-between w-full px-6",children:[t.jsx("div",{className:"flex flex-col items-center",children:t.jsxs("div",{className:"leading-tight flex items-center justify-between gap-2",children:[t.jsx("div",{className:"flex items-center justify-center rounded-full bg-indigo-100 p-2 border border-indigo-500",children:t.jsx(N.Upload,{className:"h-4 w-4 text-indigo-500"})}),t.jsxs("div",{className:"text-left",children:[t.jsxs("div",{className:"font-medium",children:["Drop your file here or"," ",t.jsx("span",{className:"text-indigo-500 cursor-pointer hover:underline",children:"browse"})]}),t.jsxs("div",{className:"text-xs text-muted-foreground font-light",children:[t.jsxs("span",{className:"",children:["Accepted file types:"," ",t.jsx("span",{className:"capitalize text-indigo-400",children:s.join(", ")})," & "]}),t.jsxs("span",{children:["Max file size:"," ",t.jsxs("span",{className:"capitalize text-indigo-400",children:[n," MB"]})]})]})]})]})}),t.jsxs("div",{className:"text-xs text-muted-foreground flex items-center gap-2",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsxs("span",{className:"text-xs",children:["Optimization:"," ",t.jsx("span",{className:l?"text-indigo-600":"text-gray-400",children:l?"On":"Off"})]}),t.jsx(c.Switch,{checked:l,onCheckedChange: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(N.AlertTriangle,{className:"h-4 w-4 mr-1"})})}),t.jsx(c.TooltipContent,{side:"top",children:t.jsxs("p",{className:"text-white text-xs",children:["Warning: Unoptimized images may affect ",t.jsx("br",{})," performance and page load times"]})})]})})]})]})]})})};function hr({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),[f,b]=g.useState(null),[j,p]=g.useState({show:!1,file:""}),[y,v]=g.useState(!1),[S,E]=g.useState(a?"details":"grid"),[D,I]=g.useState(""),[_,M]=g.useState(""),[X,$]=g.useState(1),[P]=g.useState(30),[G,H]=g.useState([]);g.useEffect(()=>{a&&(u(a),E("details"))},[a]),g.useEffect(()=>{const B=setTimeout(()=>{I(_),$(1)},300);return()=>clearTimeout(B)},[_]);const{data:K,isLoading:W}=tu({search:D.toLowerCase().trim(),page:X,limit:P}),Z=(K==null?void 0:K.assets)||[],k=(K==null?void 0:K.total)||0,q=Math.ceil(k/P),fe=X<q,be=X>1,ue=(Z==null?void 0:Z.length)>0,{mutate:w}=Zc(),{mutate:x,isPending:C}=Xc(),{mutate:F,isPending:T}=eu(),U=g.useCallback(B=>{B>=1&&B<=q&&$(B)},[q]),se=g.useCallback(()=>{fe&&U(X+1)},[X,fe,U]),V=g.useCallback(()=>{be&&U(X-1)},[X,be,U]),ie=B=>{M(B.target.value)},de=g.useCallback(B=>{H(ce=>m.find(ce,{id:B.id})?[]:[B])},[!1]),Y=g.useCallback(()=>{H([])},[]),te=B=>{(B==null?void 0:B.length)!==0&&(s(m.pick(m.first(B||G),["id","url","width","height","description"])),e())},me=async B=>{h(B)},z=async()=>{d&&(b(d==null?void 0:d.id),await w(d.id,{onSuccess:()=>{b(null),h(null)},onError:()=>{b(null)}}),h(null))},ne=B=>{u(B.id),E("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}),p({show:!1,file:""})):(await F({id:j.id||"",file:B}),p({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(lu,{maxFileSize:10,allowedTypes:l,uploadAsset:x,isUpdatingAsset:T,isUploadingAsset:C,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(N.Search,{strokeWidth:3,className:`absolute left-2 top-2.5 h-4 w-4 text-muted-foreground ${_.length>0?"text-indigo-800":""}`}),t.jsx(c.Input,{placeholder:"Search assets...",onChange:ie,value:_,className:"pl-8"})]}),G.length>0?t.jsx("div",{className:"flex justify-between items-center",children:t.jsxs("div",{className:"flex items-center gap-2",children:[G.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(G),disabled:G.length===0,children:"Select Asset"})]})}):null]}),t.jsx("div",{className:"flex-1 overflow-y-auto pb-[66px]",children:W?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"})]}):!W&&!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(N.Archive,{className:"h-9 w-9 text-indigo-500"})}),t.jsx("div",{className:"text-muted-foreground text-lg",children:"No assets found"}),t.jsx("div",{className:"text-muted-foreground text-sm",children:D.length>0?"No assets found for your search: "+D:"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:O.mergeClasses("relative cursor-pointer overflow-hidden transition-all rounded-lg border-2 group max-w-[180px] max-h-[180px] flex flex-col justify-between",G.some(ce=>ce.id===B.id)?"border-blue-500":"hover:border-black/90",f&&(d==null?void 0:d.id)===B.id?"opacity-50 pointer-events-none":"",f===B.id?"opacity-50 pointer-events-none":""),onClick:()=>de(B),onDoubleClick:()=>te([B]),children:[t.jsxs("div",{className:"aspect-square relative overflow-hidden",children:[f===B.id?t.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/50",children:t.jsx(N.Loader,{className:"h-8 w-8 animate-spin text-white"})}):null,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] ${G.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(N.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:iu((B==null?void 0:B.size)||0)})})]}),!G.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(N.ImageIcon,{className:"h-4 w-4"})})}),t.jsx(c.TooltipContent,{children:t.jsx("p",{children:"View Details"})})]})}),t.jsx(c.TooltipProvider,{children:t.jsxs(c.Tooltip,{children:[t.jsx(c.TooltipTrigger,{asChild:!0,children:t.jsx(c.Button,{variant:"secondary",size:"icon",className:"h-8 w-8 rounded-full",onClick:ce=>{ce.stopPropagation(),navigator.clipboard.writeText(B.url),J.toast.success("Asset URL copied to clipboard")},children:t.jsx(N.Copy,{className:"h-4 w-4"})})}),t.jsx(c.TooltipContent,{children:t.jsx("p",{children:"Copy URL"})})]})}),t.jsx(c.TooltipProvider,{children:t.jsxs(c.Tooltip,{children:[t.jsx(c.TooltipTrigger,{asChild:!0,children:t.jsx(c.Button,{variant:"secondary",size:"icon",className:"h-8 w-8 rounded-full",onClick:ce=>{ce.stopPropagation(),p({id:B.id,show:!0,file:B.url,name:B.name})},children:t.jsx(N.Edit,{className:"h-4 w-4"})})}),t.jsx(c.TooltipContent,{children:t.jsx("p",{children:"Edit Image"})})]})}),t.jsx(c.TooltipProvider,{children:t.jsxs(c.Tooltip,{children:[t.jsx(c.TooltipTrigger,{asChild:!0,children:t.jsx(c.Button,{variant:"destructive",size:"icon",className:"h-8 w-8 rounded-full",onClick:ce=>{ce.stopPropagation(),me(B)},children:t.jsx(N.Trash2,{className:"h-4 w-4"})})}),t.jsx(c.TooltipContent,{children:t.jsx("p",{children:"Delete Asset"})})]})})]})}),G.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(N.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:()=>U(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:()=>U(q),children:q})]}),t.jsx(c.Button,{variant:"outline",size:"sm",onClick:se,disabled:!fe,children:"Next"})]})})]})]}):t.jsx(au,{assetId:o||a||"",onBack:()=>{E("grid"),u(null)},onEdit:B=>{p({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 F(m.merge(ce,{description:B}))}finally{v(!1)}}},isSaving:y})]}),j.show&&t.jsx(g.Suspense,{fallback:t.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:t.jsx(N.Loader,{className:"h-8 w-8 animate-spin"})}),children:t.jsx(ru,{imageUrl:j.file,onSave:Ae,onClose:()=>p({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 ou=Object.freeze(Object.defineProperty({__proto__:null,default:hr},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(m.pick(j,["url","id"])),o(!1)},f=()=>{n({url:"",id:""})};return t.jsxs("div",{className:`w-full ${a}`,children:[s?t.jsxs("div",{className:"relative border rounded-md overflow-hidden",children:[t.jsx("img",{onClick:u,src:s,alt:"Selected image",className:"w-full h-auto bg-gray-300 object-contain max-h-[100px]"}),t.jsxs("div",{className:"absolute top-2 right-2 flex gap-2",children:[t.jsx(c.Button,{type:"button",variant:"destructive",size:"icon",className:"h-8 w-8 rounded-full bg-white/80 text-red-500 hover:bg-white/90",onClick:f,disabled:i,children:t.jsx(N.Trash2,{className:"h-4 w-4"})}),t.jsx(c.Button,{type:"button",variant:"secondary",size:"icon",className:"h-8 w-8 rounded-full bg-white/80 hover:bg-white/90",onClick:u,disabled:i,children:t.jsx(N.ImageIcon,{className:"h-4 w-4"})})]})]}):t.jsx("div",{className:`flex items-center justify-center border border-dashed rounded-md p-6 cursor-pointer ${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(N.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(N.X,{className:"h-4 w-4"})})]}),t.jsx("div",{className:"flex-1 p-4 h-full",children:t.jsx(hr,{close:d,onSelect:h,mode:"image",assetId:e})})]})})]})},cu=({isActive:e,onClick:s})=>t.jsx(c.Button,{variant:e?"default":"ghost",className:"w-full justify-start text-left",onClick:s,children:"Branding"}),uu=()=>{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"})})]})]})},du=()=>{zs("general",{label:"General",button:Yc,panel:Jc}),zs("branding",{label:"Branding",button:cu,panel:uu})},hu=g.lazy(()=>Promise.resolve().then(()=>ou));Vc();yr.loadWebBlocks();O.registerChaiTopBar(Sl);Zl();du();O.registerChaiMediaManager(hu);O.registerChaiSaveToLibrary(Zr);const mu=e=>{const s=g.useRef([]),[n]=Le(),a=n.get("page"),{data:r}=ke(),{data:i={role:"",permissions:null}}=va();Cl(),Rr();const{data:l,isFetching:o}=la(),{blocks:u}=El(l),{data:d}=Ce(),{mutateAsync:h}=Xn(),f=wl(),{onSave:b}=Al(),{getPartialBlocks:j,getPartialBlockBlocks:p}=Tl(),{aiContext:y,setAiContext:v}=tn(),{mutateAsync:S}=ti(),[E,D]=g.useState(!1),{data:I}=He(),_=We(),{data:M}=an(),{data:X}=Kc(),{mutateAsync:$}=Hc(),P=dr();kr(),g.useEffect(()=>{const W=()=>{document.hidden?D(!0):D(!1)};return window.addEventListener("visibilitychange",W),()=>window.removeEventListener("visibilitychange",W)},[]),s.current=u;const G=g.useMemo(()=>{const W={};return i&&(W.permissions=m.get(i,"permissions",null),W.role=m.get(i,"role","user")),W},[i]),H=g.useCallback(async(W,Z)=>await S({pageType:W,query:Z}),[S]),K=g.useMemo(()=>m.get(I,"theme",{})||{},[I]);return t.jsxs(t.Fragment,{children:[o&&t.jsx(ur,{}),t.jsx(O.ChaiBuilderEditor,{gotoPage:P,collections:X??[],getBlockAsyncProps:$,pageExternalData:M,themePresets:e.themePresets??[],pageId:r==null?void 0:r.id,loading:o,fallbackLang:_,languages:(I==null?void 0:I.languages)||[],brandingOptions:(I==null?void 0:I.theme)||{},translations:e.translations||{},locale:e.locale||"en",htmlDir:e.htmlDir||"ltr",autoSaveSupport:!E&&(e.autoSaveSupport??!0),autoSaveInterval:e.autoSaveInterval??15,onError:e.onError||console.error,getPartialBlockBlocks:p,getPartialBlocks:j,blocks:o?[]:u,theme:m.cloneDeep(K),pageTypes:d,searchPageTypeItems:H,saveAiContextCallback:async W=>{if(!a)return!0;const Z=s.current,k={_type:"@chai/ai-context",_value:m.isString(W)?W:""},q=[...Z,k];return await b({page:a,blocks:q}),v(W),!0},aiContext:y,askAiCallBack:f,onSave:async({blocks:W,theme:Z})=>{if(!a)return!0;s.current=W;const k={_type:"@chai/ai-context",_value:m.isString(y)?y:""},q=[...W,k];return await b({page:a,blocks:q}),s.current=q,m.isEqual(Z,K)||await h({settings:{theme:Z}}),!0},themePanelComponent:di,...G}),t.jsxs("div",{children:[t.jsx(qr,{}),t.jsx($r,{})]})]})},fu=new R.QueryClient({defaultOptions:{queries:{refetchOnWindowFocus:!1,refetchOnReconnect:!1}}}),gu=e=>{const{isLoggedIn:s,isSessionExpired:n}=Fe(),[,a]=Zn(),[r,i]=g.useState(!1);return Qc(),g.useEffect(()=>(a(m.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:fu,children:[s?n?t.jsx(ur,{}):t.jsx(mu,{...e}):t.jsx(Il,{}),t.jsx(zc,{})]}):t.jsx("div",{})},xu=()=>{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:L.UPDATE_PAGE_METADATA,data:{id:n.id,metadata:r}})},onSuccess:()=>{a.invalidateQueries({queryKey:[Q,L.GET_BUILDER_PAGE_DATA]}),a.invalidateQueries({queryKey:[Q,L.GET_LANGUAGE_PAGES]})},onError:()=>{console.error("Failed to update metadata")}})},pu=()=>{const{logout:e}=Fe(),{getAccessToken:s}=Yn();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 yu{constructor(s){Bs(this,"client");Bs(this,"channel",null);this.client=s}listenEvent(s,n){var a;(a=this.channel)==null||a.on("broadcast",{event:s},({payload:r})=>{n(r)}).subscribe()}async joinPage(s,n){const a=`PAGE:${s}`;return this.channel&&(await this.channel.untrack({userId:n}),await this.channel.unsubscribe()),this.channel=this.client.channel(a,{config:{presence:{key:n}}}),new Promise(r=>{var i;(i=this.channel)==null||i.on("presence",{event:"sync"},()=>{const l=this.getOnlineUsers();l.length>0?l.length===1&&l.includes(n)?r(!0):r(!1):r(!0)}).subscribe(async l=>{var o;l==="SUBSCRIBED"&&await((o=this.channel)==null?void 0:o.track({userId:n,online_at:new Date}))})})}async leavePage(){this.channel&&await this.channel.untrack()}async requestTakeOver(s,n){return new Promise(a=>{var r;(r=this.channel)==null||r.send({type:"broadcast",event:"TAKE_OVER_REQUESTED",payload:{pageId:s,requesterUserId:n,userId:n}}).then(()=>{a()})})}acceptTakeOver(s,n){return new Promise(a=>{var r;(r=this.channel)==null||r.send({type:"broadcast",event:"TAKE_OVER_REQUEST_ACCEPTED",payload:{pageId:s,userId:n}}).then(()=>{this.leavePage(),a()})})}rejectTakeOver(s,n){return new Promise(a=>{var r;(r=this.channel)==null||r.send({type:"broadcast",event:"TAKE_OVER_REQUEST_REJECTED",payload:{pageId:s,userId:n}}).then(()=>{a()})})}getOnlineUsers(){var s;return Object.keys(((s=this.channel)==null?void 0:s.presenceState())||{})}}if(typeof window>"u")throw new Error("@chaibuilder/pages is not available on the server");exports.$TRACK=yn;exports.ChaiBuilderPages=gu;exports.ChaiBuilderPagesRealtime=yu;exports.Dynamic=Yo;exports.For=wo;exports.ImagePicker=Ns;exports.Index=No;exports.LanguageSwitcher=pn;exports.Match=Ao;exports.NestedPathSelector=Ye;exports.PermissionChecker=Re;exports.Portal=Qo;exports.Show=Eo;exports.SmartJsonInput=Sa;exports.Switch=Co;exports.addEventListener=Ua;exports.batch=ao;exports.className=Oa;exports.clearDelegatedEvents=Fo;exports.convertRemToPixels=Rc;exports.createComponent=bn;exports.createComputed=Ta;exports.createContext=uo;exports.createEffect=jn;exports.createMemo=Me;exports.createRenderEffect=Xe;exports.createRoot=Je;exports.createSignal=we;exports.createUniqueId=So;exports.delegateEvents=Fa;exports.deleteNestedDataByPath=Rt;exports.displayValue=Ic;exports.getMutationStatusColor=kc;exports.getPreferredColorScheme=Fc;exports.getQueryStatusColor=Pc;exports.getQueryStatusColorByLabel=Lc;exports.getQueryStatusLabel=Ac;exports.getSidedProp=Tc;exports.insert=ws;exports.mergeProps=Sn;exports.mutationSortFns=Gc;exports.on=ro;exports.onCleanup=Tt;exports.onMount=Pa;exports.registerChaiSiteSetting=zs;exports.registerLoginComponent=Ll;exports.serialize=ir;exports.setAttribute=Ss;exports.sortFns=Bc;exports.splitProps=Ba;exports.spread=qa;exports.stringify=Cc;exports.template=Ro;exports.untrack=Pe;exports.updateNestedDataByPath=Gt;exports.use=$a;exports.useActivePage=tt;exports.useBuilderPageData=an;exports.useChaiAuth=Fe;exports.useChaiFetch=pu;exports.useChaiUserInfo=ct;exports.useContext=ho;exports.useCurrentPage=ke;exports.useFallbackLang=We;exports.useFetch=ee;exports.useGotoPage=dr;exports.useLanguagePages=Ue;exports.usePageTypes=Ce;exports.useTransition=co;exports.useUpdateActivePageMetadata=xu;exports.useUserRoleAndPermissions=va;exports.useWebsitePages=ot;exports.useWebsiteSetting=He;