@chaibuilder/pages 0.9.2 → 0.9.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.
- package/dist/{B4MFY5CR-CiovF75K.js → B4MFY5CR-BKj-uOD8.js} +1 -1
- package/dist/{B4MFY5CR-KtEUBopS.cjs → B4MFY5CR-C3UGXyLD.cjs} +1 -1
- package/dist/{HO4MOOFI-CuXikmPc.js → HO4MOOFI-Cn1tqw73.js} +2 -2
- package/dist/{HO4MOOFI-DJNgUjg_.cjs → HO4MOOFI-GguExgYj.cjs} +1 -1
- package/dist/{HUY7CZI3-1KbTmr8N.cjs → HUY7CZI3-Dehg317s.cjs} +1 -1
- package/dist/{HUY7CZI3-Di-nGfZT.js → HUY7CZI3-DrtOdq5i.js} +2 -2
- package/dist/index-BnmEv5ry.cjs +6 -0
- package/dist/{index-BNA2NDaf.js → index-C_Z0LMHl.js} +3684 -3495
- package/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/package.json +3 -3
- package/dist/index-CbOxTkR_.cjs +0 -6
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
"use strict";var Nr=Object.defineProperty;var _n=e=>{throw TypeError(e)};var Er=(e,s,n)=>s in e?Nr(e,s,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[s]=n;var Fe=(e,s,n)=>Er(e,typeof s!="symbol"?s+"":s,n),Ln=(e,s,n)=>s.has(e)||_n("Cannot "+n);var ee=(e,s,n)=>(Ln(e,s,"read from private field"),n?n.call(e):s.get(e)),pe=(e,s,n)=>s.has(e)?_n("Cannot add the same private member more than once"):s instanceof WeakSet?s.add(e):s.set(e,n),ge=(e,s,n,a)=>(Ln(e,s,"write to private field"),a?a.call(e,n):s.set(e,n),n);const t=require("react/jsx-runtime"),f=require("lodash-es"),g=require("react"),je=require("jotai"),F=require("@tanstack/react-query"),W=require("sonner"),$=require("@chaibuilder/sdk"),c=require("@chaibuilder/sdk/ui"),Bt=require("date-fns"),N=require("lucide-react"),sa=require("@chaibuilder/runtime"),js=require("zod"),Cr=require("react-dropzone"),Ar=require("@chaibuilder/sdk/web-blocks");function Tr(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=Tr(g),Ee={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"},D={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"};let kr=0;function Dn(e,s){const n=`atom${++kr}`,a={toString(){return n}};return typeof e=="function"?a.read=e:(a.init=e,a.read=Pr,a.write=Ir),s&&(a.write=s),a}function Pr(e){return e(this)}function Ir(e,s,n){return s(this,typeof n=="function"?n(e(this)):n)}const _r=Symbol(""),Lr=e=>typeof(e==null?void 0:e.then)=="function";function Dr(e=()=>{try{return window.localStorage}catch{return}},s){var n;let a,r;const i={getItem:(u,d)=>{var h,m;const j=v=>{if(v=v||"",a!==v){try{r=JSON.parse(v,s==null?void 0:s.reviver)}catch{return d}a=v}return r},y=(m=(h=e())==null?void 0:h.getItem(u))!=null?m:null;return Lr(y)?y.then(j):j(y)},setItem:(u,d)=>{var h;return(h=e())==null?void 0:h.setItem(u,JSON.stringify(d,void 0))},removeItem:u=>{var d;return(d=e())==null?void 0:d.removeItem(u)}},l=u=>(d,h,m)=>u(d,j=>{let y;try{y=JSON.parse(j||"")}catch{y=m}h(y)});let o;try{o=(n=e())==null?void 0:n.subscribe}catch{}return!o&&typeof window<"u"&&typeof window.addEventListener=="function"&&window.Storage&&(o=(u,d)=>{if(!(e()instanceof window.Storage))return()=>{};const h=m=>{m.storageArea===e()&&m.key===u&&d(m.newValue)};return window.addEventListener("storage",h),()=>{window.removeEventListener("storage",h)}}),o&&(i.subscribe=l(o)),i}const Br=Dr();function na(e,s,n=Br,a){const r=Dn(s);return r.onMount=l=>{l(n.getItem(e,s));let o;return n.subscribe&&(o=n.subscribe(e,l,s)),o},Dn(l=>l(r),(l,o,u)=>{const d=typeof u=="function"?u(l(r)):u;return d===_r?(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 aa="__logged_in_user",Rr=na(aa,null),Me=()=>{const[e,s]=je.useAtom(Rr),n=g.useCallback(()=>{s(null),localStorage.removeItem(aa)},[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}},un=async(e,s,n={})=>await fetch(e,{method:"POST",headers:{"Content-Type":"application/json",...n},body:JSON.stringify(s)});let xt=null;function Mr(){const{user:e,setUser:s,logout:n}=Me(),a=Ls(),r=$e("getAccessToken",!1),i=async()=>{if(r===!1&&e&&!(!f.has(e,"expiresAt")||!f.has(e,"accessToken")||!f.has(e,"refreshToken")))try{const l=await un(a,{action:"REFRESH_TOKEN",data:{refreshToken:e.refreshToken,accessToken:e.accessToken}});if(!l.ok){n(),window.location.reload();return}const o=await l.json();if(f.has(o,"id")&&f.has(o,"email")&&f.has(o,"accessToken")&&f.has(o,"refreshToken"))return s(o),o;n(),window.location.reload()}catch{n(),window.location.reload()}};return F.useMutation({mutationFn:async()=>{if(xt)return await xt;xt=i();try{return await xt}finally{xt=null}},onSuccess:()=>{}})}function Or(){return xt}const ra=()=>{const{user:e,isSessionExpired:s}=Me(),{mutateAsync:n}=Mr(),r=$e("getAccessToken",async()=>{if(!(!f.has(e,"expiresAt")||!f.has(e,"accessToken")||!f.has(e,"refreshToken"))){if(s){const i=Or();if(i){const o=await i;return(o==null?void 0:o.accessToken)||""}const l=await n();return(l==null?void 0:l.accessToken)||""}return(e==null?void 0:e.accessToken)||""}});return{getAccessToken:g.useCallback(async()=>{try{return await r()}catch{return""}},[r])}},X=()=>{const{logout:e}=Me(),{getAccessToken:s}=ra();return g.useCallback(async(n,a,r={})=>{const i=await s();if(!i)return null;try{const l=f.get(a,"action","").toLowerCase(),o=await un(n+(l?`?action=${l}`:""),a,{...r,Authorization:`Bearer ${i}`});if(o.status===401)return console.log("401 Response",o),e(),window.location.reload(),null;if(!o.ok){const u=await o.json();throw console.error(`API Error (${o.status}):`,u),{status:o.status,statusText:o.statusText,...u,message:u.error||u.message||`Server error: ${o.status}`}}return await o.json()}catch(l){throw console.error("API request failed:",a,l),l}},[e,s])},ia=()=>{const e=le(),s=F.useQueryClient(),n=X();return F.useMutation({mutationFn:async a=>n(e,{action:D.RELEASE_LOCK,data:a}),onSuccess:()=>{s.invalidateQueries({queryKey:[D.GET_DRAFT_PAGE]})}})},la=()=>{const e=le(),s=F.useQueryClient(),n=X();return F.useMutation({mutationFn:async a=>n(e,{action:D.UPDATE_WEBSITE_SETTINGS,data:a}),onSuccess:(a,r)=>{var i;s.invalidateQueries({queryKey:[D.GET_WEBSITE_DRAFT_SETTINGS]}),(i=r==null?void 0:r.settings)!=null&&i.theme||W.toast.success("Website settings updated successfully.")},onError:a=>{W.toast.error("Failed to update website settings",{description:a.message})}})},Gr=()=>{const e=le(),s=F.useQueryClient(),n=X();return F.useMutation({mutationFn:async a=>n(e,{action:D.UPDATE_WEBSITE_DATA,data:a}),onSuccess:()=>{s.invalidateQueries({queryKey:[D.GET_WEBSITE_DATA]}),W.toast.success("Website data updated successfully.")},onError:a=>{W.toast.error("Failed to update website data",{description:a.message})}})};function Pe(){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 Ur=je.atom({}),oa=()=>je.useAtom(Ur),Fr=()=>{const[e]=Pe(),s=e.get("page"),n=g.useRef(""),{mutate:a}=ia();g.useEffect(()=>{!f.isEmpty(n.current)&&s!==n.current&&a({id:n.current}),n.current=s},[s,a,n])},$e=(e,s)=>{const[n]=oa();return g.useMemo(()=>f.get(n,e,s),[n,e,s])},le=()=>$e("apiUrl","/chai/api"),Ls=()=>$e("usersApiUrl","/chai/users"),ls=()=>$e("assetsApiUrl","/chai/assets"),qr=()=>$e("supabaseInstance",null),qe=e=>{const s=le(),[n]=Pe(),a=e??n.get("page"),r=X();return F.useQuery({queryKey:[D.GET_LANGUAGE_PAGES,a],initialData:[],queryFn:async()=>{if(!a)return null;const i=await r(s,{action:D.GET_LANGUAGE_PAGES,data:{id:a}});return f.reverse(f.sortBy(i,"primaryPage"))},enabled:!!a})},Ke=()=>{const e=le(),s=X();return F.useQuery({queryKey:[D.GET_WEBSITE_DRAFT_SETTINGS],initialData:{theme:{},fallbackLang:"en",languages:[]},queryFn:async()=>s(e,{action:D.GET_WEBSITE_DRAFT_SETTINGS,data:{draft:!0}})})},ca=e=>{const{fallbackLang:s}=$.useLanguages(),{data:n}=Ke(),{data:a,isFetching:r}=qe(),i=g.useMemo(()=>{const l={[s]:!0};return f.each(f.get(n,"languages"),o=>{const u=f.find(a,{lang:o});l[o]=!!u}),l},[s,a,n]);return r||f.isEmpty(e)||e&&i[e]},dn=()=>{const e=F.useQueryClient(),{data:s}=F.useQuery({queryKey:[D.AI_CONTEXT],initialData:"",queryFn:()=>"",staleTime:0});return{setAiContext:g.useCallback(a=>{e.setQueryData([D.AI_CONTEXT],a)},[e]),aiContext:s}},$r=je.atom(null),ua=()=>je.useAtom($r),hn=()=>{const[e]=ua();return(e==null?void 0:e.slug)||""};function zr(e,s){const[n,a]=g.useState(e);return g.useEffect(()=>{const r=setTimeout(()=>a(e),s);return()=>clearTimeout(r)},[e,s]),n}const Vr=({query:e,uuid:s})=>{const{selectedLang:n,fallbackLang:a}=$.useLanguages(),{data:r}=ke(),i=r==null?void 0:r.pageType,l=le(),o=X(),{data:u,isFetching:d}=F.useQuery({queryKey:[D.GET_DYNAMIC_PAGES,e,i,s],initialData:[],queryFn:async()=>await o(l,{action:D.GET_DYNAMIC_PAGES,data:{query:e,pageType:i,uuid:s}})||[],enabled:!!i}),h=g.useMemo(()=>n===""?u.filter(m=>m.lang===""||m.lang===a):u.filter(m=>m.lang===n),[n,a,u]);return{allLangPages:u,data:h,isFetching:d}},da=()=>{const{selectedLang:e,fallbackLang:s}=$.useLanguages(),[n,a]=ua(),[r,i]=g.useState(""),l=zr(r,500),{allLangPages:o,data:u,isFetching:d}=Vr({query:l}),h=g.useCallback(y=>a(y),[a]),m=g.useCallback(y=>i(y),[i]),j=g.useCallback(()=>{if(!n)return;const y=!(n!=null&&n.primaryPage),v=e.length===0,p=y?n==null?void 0:n.id:n==null?void 0:n.primaryPage,S=o.filter(E=>(E==null?void 0:E.primaryPage)===p||E.id===p).find(E=>v?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:m,onChangeLanguage:j}},Qe=()=>{const{data:e}=Ke();return g.useMemo(()=>(e==null?void 0:e.fallbackLang)||"en",[e])},ht=()=>{const e=X(),s=le();return F.useQuery({queryKey:[D.GET_WEBSITE_PAGES],staleTime:1e3*60*5,queryFn:async()=>e(s,{action:D.GET_WEBSITE_PAGES})||[],placeholderData:n=>n||[]})},Kr=e=>{const s=X(),n=le(),a=Qe();return F.useQuery({queryKey:[D.GET_WEBSITE_PAGES,e,a],staleTime:1e3*60*5,enabled:!!e,queryFn:async()=>{if(a===e)return{};const r=await s(n,{action:D.GET_WEBSITE_PAGES,data:{lang:e}})||[];return f.keyBy(f.map(r,i=>({...i,lang:e})),"primaryPage")},placeholderData:r=>r||{}})},Hr=je.atom({lastSaved:void 0}),Ds=()=>je.useAtom(Hr),ke=()=>{const[e]=Pe(),s=e.get("page"),[n]=ha(),{data:a,isFetching:r}=ht();return{data:g.useMemo(()=>({...f.find(a,{id:s})||{},metadata:n}),[a,s,n]),isFetching:r}},We=()=>{const[e]=Pe(),s=e.get("lang")??"",{data:n,isFetching:a}=qe();return{data:g.useMemo(()=>f.find(n,{lang:s})||{},[n,s]),isFetching:a}},Qr=je.atom({}),ha=()=>je.useAtom(Qr),ma=()=>{const{data:e}=We(),s=hn(),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};class fa{constructor(s,n,a,r){Fe(this,"channelId");Fe(this,"supabase");Fe(this,"channel",null);Fe(this,"userId",null);Fe(this,"clientId",null);Fe(this,"pageId",null);Fe(this,"callback");var i,l,o,u,d,h;this.userId=a,this.supabase=s,this.clientId=this.getClientId(),this.channelId=`WEBSITE:${n}`,this.callback=r,this.channel=this.supabase.channel(this.channelId,{config:{presence:{key:this.clientId}}}),(h=(d=(u=(o=(l=(i=this.channel)==null?void 0:i.on("presence",{event:"sync"},m=>{console.log("## ONLINE USERS",this.getOnlineUsers({})),this.callback("UPDATE_ONLINE_USERS",{pageToUser:this.getPageUserMapping()}),this.onReceiveEvent("SYNC",m)}))==null?void 0:l.on("presence",{event:"leave"},m=>{console.log("## ONLINE USERS",this.getOnlineUsers({})),this.callback("UPDATE_ONLINE_USERS",{pageToUser:this.getPageUserMapping()}),this.onReceiveEvent("SYNC",m)}))==null?void 0:o.on("presence",{event:"join"},m=>{console.log("## ONLINE USERS",this.getOnlineUsers({})),this.callback("UPDATE_ONLINE_USERS",{pageToUser:this.getPageUserMapping()}),this.onReceiveEvent("SYNC",m)}))==null?void 0:u.on("broadcast",{event:"TAKE_OVER_REQUESTED"},({payload:m})=>this.onReceiveEvent("TAKE_OVER_REQUESTED",m)))==null?void 0:d.on("broadcast",{event:"TAKE_OVER_REQUEST_ACCEPTED"},({payload:m})=>this.onReceiveEvent("TAKE_OVER_REQUEST_ACCEPTED",m)))==null||h.on("broadcast",{event:"TAKE_OVER_REQUEST_REJECTED"},({payload:m})=>this.onReceiveEvent("TAKE_OVER_REQUEST_REJECTED",m)).subscribe()}getClientId(){return crypto.randomUUID()}getOnlineUsers({pageId:s,userId:n}){var i;const a=(i=this.channel)==null?void 0:i.presenceState();let r=Object.values(a||{}).map(l=>l[0]).filter(Boolean);return s?r=r.filter(l=>l.pageId===s):n&&(r=r.filter(l=>l.userId===n)),r.sort((l,o)=>l.onlineAt-o.onlineAt)}getPageOwner(){const s=this.getOnlineUsers({pageId:this.pageId});return s.length>0?s[0]:null}getPageUserMapping(){const s=this.getOnlineUsers({}),n=f.groupBy(s,"pageId"),a={};return Object.keys(n).forEach(r=>{var l;const i=(l=f.minBy(n[r],"onlineAt"))==null?void 0:l.userId;i!==this.userId&&(a[r]=i)}),a}onReceiveEvent(s,n){if(!this.pageId)return;const a=this.getPageOwner();if(!a||a.clientId===this.clientId?this.callback("USER_JOINED",{isActiveInOtherTab:!1}):this.callback("PAGE_LOCKED",{isActiveInOtherTab:(a==null?void 0:a.userId)===this.userId&&(a==null?void 0:a.clientId)!==this.clientId}),n.targetClientId===this.clientId)switch(s){case"TAKE_OVER_REQUESTED":this.callback("TAKE_OVER_REQUESTED",{requestedBy:n==null?void 0:n.userId,requestingClientId:n==null?void 0:n.senderClientId,isRequestedFromAnotherTab:(n==null?void 0:n.senderClientId)!==this.clientId&&(n==null?void 0:n.userId)===this.userId});break;case"TAKE_OVER_REQUEST_ACCEPTED":this.channel.track({pageId:this.pageId,userId:this.userId,clientId:this.clientId,onlineAt:a?a.onlineAt-10:+new Date}),this.callback("TAKE_OVER_REQUEST_ACCEPTED",{isTakingOverFromAnotherTab:(n==null?void 0:n.senderClientId)!==this.clientId&&(n==null?void 0:n.userId)===this.userId});break;case"TAKE_OVER_REQUEST_REJECTED":this.callback("TAKE_OVER_REQUEST_REJECTED");break}}async joinPage(s){var n;this.pageId=s,(n=this.channel)==null||n.track({pageId:this.pageId,userId:this.userId,clientId:this.clientId,onlineAt:+new Date})}async leavePage(){var s;this.channel&&((s=this.channel)==null||s.untrack())}async sendEvent(s,n){var a,r;if(this.channel){const i={pageId:this.pageId,userId:this.userId,senderClientId:this.clientId};s==="TAKE_OVER_REQUESTED"?i.targetClientId=(a=this.getPageOwner())==null?void 0:a.clientId:(s==="TAKE_OVER_REQUEST_ACCEPTED"||s==="TAKE_OVER_REQUEST_REJECTED")&&(i.targetClientId=n==null?void 0:n.requestingClientId),await((r=this.channel)==null?void 0:r.send({event:s,payload:i,type:"broadcast"}))}}}const Ye=e=>{const s=Ls(),n=X();return F.useQuery({queryKey:["chaiUserInfo",e],queryFn:async()=>{const r=await n(s,{action:D.GET_CHAI_USER,data:{userId:e}});return{...r,name:r.name||r.email}},enabled:!f.isEmpty(e)})},Wr=je.atom(void 0),Yr=je.atom({status:"checking",requestedBy:"",isTakeOverRequested:!1,requestingClientId:"",isActiveInOtherTab:!1}),Jr=je.atom(""),Xr=je.atom(null),mn=je.atom({}),ga=()=>je.useAtom(mn),Je=()=>{const[e]=Pe(),s=e.get("page"),{user:n}=Me(),[a,r]=je.useAtom(Wr),[i,l]=je.useAtom(Yr),[o,u]=je.useAtom(Xr),[d,h]=je.useAtom(Jr),[m]=je.useAtom(mn);return g.useMemo(()=>({pageLock:i,pageToUser:m,lockingStatus:d,realtimeInstance:o,setPageLock:l,setCurrentEditor:r,setLockingStatus:h,setRealtimeInstance:u,realtimePageLockEnabled:!!o,currentEditor:o?m[s||""]:a,isLocked:o?s&&i.status==="locked":s&&(n==null?void 0:n.id)!==a}),[s,n==null?void 0:n.id,i,d,a,o,l,r,h,u,m])},Zr=()=>{const e=qr(),{data:s}=ke(),{user:n}=Me(),a=s==null?void 0:s.id,{data:r}=Ke(),{pageLock:i,setPageLock:l,setLockingStatus:o,realtimeInstance:u,setRealtimeInstance:d}=Je(),[,h]=je.useAtom(mn),m=g.useRef(!1),j=g.useRef(i),y=g.useRef(!1);return g.useEffect(()=>{if(n!=null&&n.id&&e&&!u&&(r!=null&&r.appKey)&&!y.current){y.current=!0;const v=async(b,S)=>{var E,L;switch(b){case"UPDATE_ONLINE_USERS":h((S==null?void 0:S.pageToUser)||{});break;case"PAGE_LOCKED":l({...j==null?void 0:j.current,requestedBy:"",status:"locked",isActiveInOtherTab:S==null?void 0:S.isActiveInOtherTab});break;case"USER_JOINED":if(((E=j==null?void 0:j.current)==null?void 0:E.status)==="editing")return;((L=j==null?void 0:j.current)==null?void 0:L.status)==="locked"&&o("can_edit_now"),l({...j==null?void 0:j.current,requestedBy:"",status:"editing",isActiveInOtherTab:S==null?void 0:S.isActiveInOtherTab});break;case"TAKE_OVER_REQUESTED":l({...j==null?void 0:j.current,requestingClientId:S==null?void 0:S.requestingClientId,requestedBy:S!=null&&S.isRequestedFromAnotherTab?"ANOTHER_TAB":S==null?void 0:S.requestedBy});break;case"TAKE_OVER_REQUEST_ACCEPTED":S!=null&&S.isTakingOverFromAnotherTab||(o("take_over_request_accepted"),W.toast.success("Your Page Take Over Request Accepted",{position:"top-center"})),l({...j==null?void 0:j.current,status:"checking",requestedBy:"",requestingClientId:"",isTakeOverRequested:!1});break;case"TAKE_OVER_REQUEST_REJECTED":o("take_over_request_rejected"),l({...j==null?void 0:j.current,requestedBy:"",requestingClientId:"",isTakeOverRequested:!1});break}},p=new fa(e,r==null?void 0:r.appKey,n==null?void 0:n.id,v);d(p)}},[d,e,r==null?void 0:r.appKey]),g.useEffect(()=>{j.current=i},[i]),g.useEffect(()=>{if(!(!u||!a||!(n!=null&&n.id)||m.current))return m.current=!0,u==null||u.joinPage(a),()=>{u&&m.current&&(m.current=!1,j.current={requestedBy:"",status:"checking",requestingClientId:"",isActiveInOtherTab:!1,isTakeOverRequested:!1},o(""),l(j.current),u==null||u.leavePage())}},[a,u]),i==null?void 0:i.status},xa=()=>{const{data:e}=ke(),{user:s}=Me(),n=e==null?void 0:e.id,{pageLock:a,setPageLock:r,realtimeInstance:i}=Je(),{savePageAsync:l}=$.useSavePage(),o=g.useCallback(()=>{!i||!n||!(s!=null&&s.id)||(r({...a,isTakeOverRequested:!0}),i==null||i.sendEvent("TAKE_OVER_REQUESTED"))},[i,n,s==null?void 0:s.id,r,a]),u=g.useCallback(async()=>{!i||!n||!(s!=null&&s.id)||(await l(),i==null||i.sendEvent("TAKE_OVER_REQUEST_ACCEPTED",{requestingClientId:a==null?void 0:a.requestingClientId}),r({requestedBy:"",status:"locked",requestingClientId:"",isActiveInOtherTab:!1,isTakeOverRequested:!1}))},[n,i,s==null?void 0:s.id,r,l,a]),d=g.useCallback(()=>{!i||!n||!(s!=null&&s.id)||(i==null||i.sendEvent("TAKE_OVER_REQUEST_REJECTED",{requestingClientId:a==null?void 0:a.requestingClientId}),r({...a,requestedBy:"",status:"editing",requestingClientId:"",isActiveInOtherTab:!1,isTakeOverRequested:!1}))},[n,i,s==null?void 0:s.id,r,a]);return{pageLock:a,acceptTakeOver:u,rejectTakeOver:d,requestTakeOver:o}},pa=()=>{const[e]=Pe(),s=e.get("page"),n=le(),{setAiContext:a}=dn(),{setCurrentEditor:r}=Je(),[,i]=Ds(),[,l]=ha(),o=X();return F.useQuery({queryKey:[D.GET_DRAFT_PAGE,s],staleTime:1/0,gcTime:1/0,queryFn:async()=>{r("");const u=await o(n,{action:D.GET_DRAFT_PAGE,data:{id:s,draft:!0}});r(u.currentEditor);const d=u.blocks??[],h=f.find(d,{_type:"@chai/ai-context"});return a(f.get(h,"_value","")||""),i(m=>({...m,lastSaved:u.lastSaved})),l(f.get(u,"metadata",{})),d},enabled:!!s})},fn=()=>{const{data:e}=ke(),{data:s}=We(),n=le(),a=X(),r=Qe(),i=hn();return F.useQuery({queryKey:[D.GET_BUILDER_PAGE_DATA,s==null?void 0:s.id,i],initialData:{},queryFn:async()=>a(n,{action:D.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)})},ei=({currentEditor:e})=>{const{user:s}=Me(),{data:n}=Ye(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"]})})]})})},ti=({userId:e})=>{const{data:s}=Ye(e);return(s==null?void 0:s.name)||"Unknown"};function si({avatar:e,name:s,email:n,lastSaved:a,onTakeOver:r,realtimePageLockEnabled:i,isRequestRejected:l,isFetchingUserInfo:o}){const[u,d]=g.useState(!1),[h,m]=g.useState(!1),j=()=>{d(!0),setTimeout(()=>{d(!1)},15e3),m(!1),r()};return t.jsx("div",{className:"fixed bottom-0 left-0 right-0 top-[50px] z-[20] flex w-screen items-center justify-center bg-black/30 backdrop-blur-sm",children:t.jsxs(c.Card,{className:"mx-auto w-full max-w-md",children:[t.jsx(c.CardHeader,{className:"space-y-1",children:t.jsxs(c.CardTitle,{className:"flex items-center gap-2 text-xl",children:[t.jsx(N.LockKeyhole,{className:"h-8 w-8 rounded-md bg-sky-500/20 p-1.5 text-sky-500"}),"Page is locked for editing"]})}),t.jsx(c.CardContent,{className:"w-md grid w-full pt-2",children:t.jsxs("div",{children:[t.jsxs("div",{className:"relative mx-auto flex w-96 items-center space-x-4 rounded-md border border-green-500 px-2 pb-2 pt-4",children:[t.jsx("div",{className:"absolute -top-2.5 left-3 w-max rounded-full bg-green-500 px-3 py-1 text-xs font-medium leading-3 text-white",children:"Locked By"}),e&&!o?t.jsx("img",{src:e,alt:s,className:"h-14 w-14 rounded-full border border-gray-300"}):t.jsx(N.UserIcon,{className:"h-14 w-14 flex-shrink-0 rounded-full bg-gradient-to-br from-purple-400 to-pink-500 p-2 text-white"}),t.jsxs("div",{className:o?"space-y-1.5":"space-y-0",children:[o?t.jsx(c.Skeleton,{className:"h-4 w-40 rounded"}):t.jsx("span",{className:"truncate font-medium text-black",children:s}),n&&!o?t.jsx("p",{className:"truncate text-sm text-muted-foreground",children:n}):t.jsx(c.Skeleton,{className:"h-4 w-60 rounded"}),a&&!o?t.jsxs("p",{className:"text-sm text-muted-foreground",children:["Last saved:"," ",Bt.formatDistanceToNow(new Date(a),{addSuffix:!0})]}):t.jsx(c.Skeleton,{className:"h-4 w-40 rounded"})]})]}),t.jsx("div",{className:"mt-4 text-sm",children:t.jsxs("p",{className:"py-4 text-center text-gray-600",children:["This page is currently being edited by ",t.jsx("span",{className:"font-bold",children:s}),".",t.jsx("br",{}),i&&t.jsxs(t.Fragment,{children:[" ",t.jsx("br",{})," You can either wait until they finish editing or"," ",i?"request to":""," take over the page."]})]})}),l&&t.jsxs("div",{className:"mt-4 flex w-full items-center justify-center gap-x-2 rounded border border-red-500 bg-red-50 p-2 text-center font-medium text-red-500",children:[t.jsx(N.Info,{className:"h-5 w-5"})," Page take over request is rejected"]})]})}),t.jsx(c.CardFooter,{children:i?t.jsxs(c.Button,{disabled:u,onClick:j,className:"w-full",variant:"destructive",children:[t.jsx(N.KeyIcon,{className:"h-5 w-5"}),u?"Page take is requested.":l?"Request take over again":"Request take over"]}):t.jsxs(c.AlertDialog,{open:h,onOpenChange:m,children:[t.jsx(c.AlertDialogTrigger,{asChild:!0,children:t.jsxs("span",{className:"flex flex-col items-center",children:[t.jsx(c.Button,{className:"w-full",variant:"destructive",children:"Take over"}),t.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:"If you need to edit, you can take over the lock, but be aware that the other user might lose unsaved changes."})]})}),t.jsxs(c.AlertDialogContent,{className:"z-[99]",children:[t.jsxs(c.AlertDialogHeader,{children:[t.jsx(c.AlertDialogTitle,{children:"Are you sure you want to take over?"}),t.jsxs(c.AlertDialogDescription,{children:[t.jsxs("span",{className:"flex items-center space-x-2 text-yellow-500",children:[t.jsx(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:j,children:"Yes, Take Over"})]})]})]})})]})})}const gs=({isChecking:e,lockingStatus:s,onContinue:n})=>{const[a,r]=g.useState(!1),i=s==="page_is_active_in_other_tab",l=(s==null?void 0:s.length)>0,{pageLock:o,acceptTakeOver:u,rejectTakeOver:d}=xa(),h=()=>{r(!0),l||i?n():u(),setTimeout(()=>{r(!1)},3e3)};return g.useEffect(()=>{(o==null?void 0:o.requestedBy)==="ANOTHER_TAB"&&u()},[o,u]),(o==null?void 0:o.requestedBy)==="ANOTHER_TAB"?null:e?t.jsxs("div",{className:"fixed bottom-0 left-0 right-0 top-[50px] z-[20] flex w-screen flex-col items-center justify-center bg-black/20 backdrop-blur-sm",children:[t.jsxs("div",{className:"relative flex h-12 w-12 items-center justify-center",children:[t.jsx("div",{className:"absolute inset-0 animate-pulse rounded-full bg-white blur-xl"}),t.jsxs("div",{className:"relative flex h-full w-full items-center justify-center",children:[t.jsx("div",{className:"absolute inset-0 animate-spin rounded-full bg-gradient-to-l from-[#38bdf8] via-[#fb7185] to-[#84cc16] blur"}),t.jsx("div",{className:"absolute h-8 w-8 animate-bounce rounded-full bg-white p-0.5",children:t.jsx("img",{className:"rounded-full",src:"https://ucarecdn.com/fbfc3b05-cb73-4e99-92a2-3a367b7c36cd/&w=96&q=75"})})]})]}),t.jsx("span",{className:"inline-block bg-gradient-to-r from-pink-800 to-purple-800 bg-clip-text pt-2 text-xs font-black text-transparent",children:"GEARING UP YOUR PAGE"})]}):t.jsx("div",{className:"fixed bottom-0 left-0 right-0 top-[50px] z-[20] flex w-screen items-center justify-center bg-black/30 backdrop-blur-sm",children:t.jsxs(c.Card,{className:"mx-auto w-full max-w-md",children:[t.jsx(c.CardHeader,{className:"space-y-1",children:t.jsxs(c.CardTitle,{className:"flex items-center gap-2 text-xl font-medium",children:[a?t.jsx(N.Loader,{className:"h-6 w-6 animate-spin text-gray-500"}):i?t.jsx(N.TableIcon,{className:"h-6 w-6 text-green-500"}):l?t.jsx(N.CheckCircle,{className:"h-6 w-6 text-green-500"}):t.jsx(N.Target,{className:"h-6 w-6 text-green-500"}),i?"Page is active in other tab":l?"You can edit the page now.":"Page take over request"]})}),t.jsx(c.CardContent,{className:"grid gap-4",children:t.jsx("div",{children:i?t.jsx("p",{children:'You are already editing this page in another tab. To continue editing here, click on "Continue editing here".'}):l?t.jsx("p",{children:"This page is released by other user you can continue editing now."}):t.jsxs("p",{children:[t.jsxs("b",{children:[" ",t.jsx(ti,{userId:o==null?void 0:o.requestedBy})]})," ","has requested to take over this page.",t.jsx("br",{})," If you accept, your unsaved changes will be saved."]})})}),t.jsxs(c.CardFooter,{className:"flex items-center justify-end gap-2",children:[t.jsx(c.Button,{disabled:a,onClick:h,className:l?"":"bg-green-500 hover:bg-green-600",children:i?t.jsxs(t.Fragment,{children:[t.jsx(N.Edit,{className:"h-5 w-5"})," Continue editing here"]}):l?t.jsxs(t.Fragment,{children:[t.jsx(N.Edit,{className:"h-5 w-5"})," Continue to edit"]}):t.jsxs(t.Fragment,{children:[t.jsx(N.Check,{className:"h-5 w-5"})," Accept"]})}),!l&&t.jsxs(c.Button,{variant:"outline",onClick:d,children:[t.jsx(N.X,{className:"h-5 w-5"})," Reject"]})]})]})})},ni=()=>{const{pageLock:e,requestTakeOver:s}=xa(),{isLocked:n,currentEditor:a,lockingStatus:r,setLockingStatus:i,realtimePageLockEnabled:l}=Je(),{data:o,isFetching:u}=Ye(a),[d]=Pe(),h=d.get("page"),{mutate:m}=ia(),{isFetching:j}=pa(),[y]=Ds(),v=F.useQueryClient(),p=g.useCallback(()=>{l?s():m({id:h})},[h,m,s,l]);return h?l&&(e==null?void 0:e.status)==="checking"?t.jsx(gs,{isChecking:!0,lockingStatus:"",onContinue:()=>{}}):l&&(e!=null&&e.requestedBy)?t.jsx(gs,{lockingStatus:"",onContinue:()=>{}}):(l?e.status!=="locked":!n||j)?r==="take_over_request_accepted"||r==="can_edit_now"?t.jsx(gs,{lockingStatus:r,onContinue:()=>{v.invalidateQueries({queryKey:[D.GET_DRAFT_PAGE]}),i("")}}):null:l&&(e!=null&&e.isActiveInOtherTab)?t.jsx(gs,{lockingStatus:"page_is_active_in_other_tab",onContinue:s}):t.jsx(si,{...o,isFetchingUserInfo:u,name:(o==null?void 0:o.name)||"Unknown User",email:(o==null?void 0:o.email)||"",lastSaved:(y==null?void 0:y.lastSaved)||"",onTakeOver:p,realtimePageLockEnabled:l,isRequestRejected:r==="take_over_request_rejected"}):null},ai=()=>{const[e,s]=Pe(),n=e.get("lang"),a=ca(n),{setSelectedLang:r}=$.useLanguages(),i=()=>{const o=new URLSearchParams(window.location.search);o.delete("lang");const u=o.toString(),d=`${window.location.pathname}${u?`?${u}`:""}`;window.history.pushState({},"",d),s(o),r(""),window.dispatchEvent(new PopStateEvent("popstate"))};if(a)return null;const l=f.get(Ee,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"})})]})})},ri=e=>{const s=le(),n=X();return F.useMutation({mutationFn:async a=>n(s,{action:D.UPSERT_LIBRARY_ITEM,data:a}),onSuccess:a=>{e(a)},onError:a=>{console.error("Error saving block:",a),W.toast.error("Failed to save block",{description:a instanceof Error?a.message:"Unknown error"})}})},ii=e=>{const s=le(),n=X();return F.useQuery({queryKey:["uiBlockDetails",e],enabled:!!e,queryFn:async()=>{if(!e)return null;try{return await n(s,{action:D.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})},li=e=>{const s=le(),n=X();return F.useMutation({mutationFn:async a=>n(s,{action:D.DELETE_LIBRARY_ITEM,data:{id:a}}),onSuccess:()=>{e()},onError:a=>{console.error("Error deleting block:",a),W.toast.error("Failed to delete block",{description:a instanceof Error?a.message:"Unknown error"})}})},oi=({blockId:e,libBlockId:s,isOpen:n,onClose:a,blockName:r,trigger:i})=>{const[l,o]=g.useState(!1),u=$.useUpdateBlocksPropsRealtime(),d=li(()=>{u([e],{_libBlockId:void 0}),W.toast.success("Block deleted successfully"),o(!1),a()}),h=()=>{o(!0),d.mutate(s)},m=t.jsxs(c.Button,{type:"button",variant:"destructive",size:"sm",onClick:j=>j.preventDefault(),disabled:l,children:[t.jsx(N.Trash2,{className:"h-4 w-4 mr-2"}),"Delete"]});return t.jsxs(c.Popover,{open:n,onOpenChange:j=>!j&&a(),children:[t.jsx(c.PopoverTrigger,{asChild:!0,children:i||m}),t.jsx(c.PopoverContent,{className:"w-72 p-4 z-[9999]",sideOffset:5,align:"center",children:t.jsxs("div",{className:"space-y-3",children:[t.jsx("h4",{className:"font-medium",children:"Delete Block"}),t.jsxs("p",{className:"text-sm",children:["Are you sure you want to delete the block",t.jsxs("span",{className:"font-medium",children:[' "',r,'"']}),"?"]}),t.jsx("p",{className:"text-xs text-muted-foreground",children:"This block will be permanently removed from the library. This action cannot be undone."}),t.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[t.jsx(c.Button,{type:"button",variant:"outline",size:"sm",onClick:a,disabled:l,children:"Cancel"}),t.jsx(c.Button,{type:"button",variant:"destructive",size:"sm",onClick:h,disabled:l,children:l?"Deleting...":"Delete"})]})]})})]})},ci=({blockId:e,libBlockId:s,blockName:n,size:a="sm",className:r="",close:i})=>{const[l,o]=g.useState(!1);return t.jsx(oi,{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"]})})},ui=()=>{const e=le(),s=X(),n=F.useQueryClient(),{data:a=[],isLoading:r,error:i}=F.useQuery({queryKey:["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}=F.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:["library-groups"]}),W.toast.success("Group created successfully")},onError:u=>{console.error("Error creating group:",u),W.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}},di=({value:e,onChange:s})=>{const[n,a]=g.useState(!1),[r,i]=g.useState(""),l=g.useRef(null),{groups:o}=ui(),[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(y=>!o.some(v=>v.id===y.id))],[o,u]),m=()=>{const y=r.trim();if(!y)return;const v={id:y,name:y};d(p=>[...p,v]),s(v.id),i(""),a(!1)};g.useEffect(()=>{n&&l.current&&l.current.focus()},[n]);const j=y=>{y.key==="Enter"&&(y.preventDefault(),m())};return g.useEffect(()=>{e&&!h.some(y=>y.id===e)&&s("")},[e,h,s]),n?t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Input,{ref:l,placeholder:"Enter new group name",value:r,onChange:y=>i(y.target.value),onKeyDown:j}),t.jsxs("div",{className:"flex justify-end gap-2",children:[t.jsx(c.Button,{variant:"outline",size:"sm",onClick:()=>a(!1),children:"Cancel"}),t.jsx(c.Button,{size:"sm",onClick:m,children:"Create"})]})]}):t.jsxs("div",{className:"flex gap-2",children:[t.jsxs("select",{className:"w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",value:e,onChange:y=>s(y.target.value),children:[t.jsx("option",{value:"",children:"Select a group"}),o.length>0&&t.jsx("optgroup",{label:"Library Groups",children:o.map(y=>t.jsx("option",{value:y.id,children:y.name},`lib-${y.id}`))}),u.length>0&&t.jsx("optgroup",{label:"Predefined Groups",children:u.filter(y=>!o.some(v=>v.id===y.id)).map(y=>t.jsx("option",{value:y.id,children:y.name},`local-${y.id}`))})]}),t.jsx(c.Button,{type:"button",size:"icon",variant:"outline",onClick:()=>a(!0),children:t.jsx(N.Plus,{className:"h-4 w-4"})})]})},hi=10*1024*1024,mi=({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>hi){W.toast.error("File too large",{description:`Maximum file size is 10mb. Selected file is ${(d.size/1024/1024).toFixed(2)}MB.`}),r.current&&(r.current.value="");return}try{a(!0);const m=new FileReader;m.onloadend=()=>{s(m.result),a(!1)},m.readAsDataURL(d)}catch(m){console.error("Error reading file:",m),a(!1),W.toast.error("Failed to process image",{description:m instanceof Error?m.message:"Unknown error"})}}},[s]),l=()=>{s(""),r.current&&(r.current.value="")},o=()=>{var u;(u=r.current)==null||u.click()};return t.jsxs("div",{className:"space-y-2",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(c.Input,{type:"file",ref:r,onChange:i,accept:"image/*",className:"hidden"}),t.jsx(c.Button,{type:"button",variant:"outline",onClick:o,disabled:n,className:"w-full",children:n?t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsx("div",{className:"animate-spin h-4 w-4 border-2 border-current border-t-transparent rounded-full"}),"Uploading..."]}):t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsx(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"})})]})},we={...$.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"},fi=e=>{const{blocks:s,close:n,blockId:a}=e,{getPartailBlocks:r}=$.usePartailBlocksStore(),i=s.find(P=>P._id===a),l=i==null?void 0:i._libBlockId,o=!!l,u=g.useMemo(()=>s.some(P=>P._type==="PartialBlock"||P._type==="GlobalBlock"),[s]),d=g.useMemo(()=>{let P=[];for(const U of s)if(U._type==="PartialBlock"||U._type==="GlobalBlock"){let C=r(U.partialBlockId);U._parent&&(C==null?void 0:C.length)>0&&(C=C.map(B=>(f.isEmpty(B._parent)&&f.set(B,"_parent",U._parent),B))),P=[...P,...C]}else P.push(U);return P},[s,r]),[h,m]=g.useState(""),[j,y]=g.useState(""),[v,p]=g.useState(""),[b,S]=g.useState(""),[E,L]=g.useState({}),[I,k]=g.useState(!1),[T,V]=g.useState(o),[ne,Y]=g.useState(!1),{hasPermission:_}=$.usePermissions(),M=_(we.DELETE_LIBRARY_BLOCK),Q=$.useUpdateBlocksPropsRealtime(),R=()=>{Q([a],{_libBlockId:void 0}),W.toast.success("Block delinked from library"),n()},{data:Z,isLoading:K,isError:te}=ii(l);g.useEffect(()=>{te&&o&&(Y(!0),V(!1))},[te,o]),g.useEffect(()=>{Z&&!K&&(m(Z.name||""),y(Z.group||""),p(Z.description||""),S(Z.preview||""),V(!1))},[Z,K]),g.useEffect(()=>{const P=h.trim().length>=2,U=j.trim()!=="";k(P&&U)},[h,j]);const ue=()=>{const P={};return h.trim()?h.length<2&&(P.name="Name must be at least 2 characters"):P.name="Name is required",j||(P.group="Group is required"),L(P),Object.keys(P).length===0},{resetLibrary:he}=$.useLibraryBlocks({id:""}),oe=ri(P=>{o||Q([a],{_libBlockId:P.id}),W.toast.success(`Block ${o?"updated":"saved"} successfully`),he(P.library),n()}),w=async P=>{if(P.preventDefault(),!ue())return;const U=d.map(C=>(f.has(C,"_libBlockId")&&delete C._libBlockId,C));oe.mutate({name:h.trim(),group:j,blocks:U,description:v.trim(),...b&&b.startsWith("data:")?{previewImage:b}:{},...o?{id:l}:{}})},x=oe.isPending;return T||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"})}):ne?t.jsxs("div",{className:"p-6 space-y-4",children:[t.jsx("div",{className:"text-destructive font-medium",children:"Block Not Found"}),t.jsx("p",{className:"text-sm text-muted-foreground",children:"This block could not be found on the server. It may have been deleted."}),t.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[t.jsx(c.Button,{type:"button",variant:"outline",onClick:n,children:"Cancel"}),t.jsx(c.Button,{onClick:R,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:P=>m(P.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(di,{value:j,onChange:y}),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:v,onChange:P=>p(P.target.value)})]}),t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Label,{htmlFor:"previewImage",children:"Preview Image (optional)"}),t.jsx(mi,{value:b,onChange:S})]}),t.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[o&&M&&t.jsx(ci,{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"})]})]})]})},re={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."},gi={SLUG_ALREADY_USED:"This slug is already in use. Please choose a different one."},Ae=()=>{const e=le(),s=X();return F.useQuery({queryKey:[D.GET_PAGE_TYPES],initialData:[],queryFn:async()=>s(e,{action:D.GET_PAGE_TYPES})})},ya=e=>{const{data:s}=Ae();return g.useMemo(()=>s==null?void 0:s.find(n=>n.key===e),[s,e])},xi=()=>{const e=le(),s=X();return F.useMutation({mutationFn:async({pageType:n,query:a})=>{try{return s(e,{action:D.SEARCH_PAGES,data:{pageType:n,query:Array.isArray(a)&&a.length>0?a[0]:a}})||[]}catch(r){return console.error(r),[]}}})},ja=()=>{const e=le(),s=F.useQueryClient(),n=X(),{data:a}=Ae();return F.useMutation({mutationFn:async r=>await n(e,{action:D.CREATE_PAGE,data:r}),onSuccess:(r,i)=>{var o;i&&(i!=null&&i.primaryPage)?(s.invalidateQueries({queryKey:[D.GET_LANGUAGE_PAGES,i==null?void 0:i.primaryPage]}),s.invalidateQueries({queryKey:[D.GET_WEBSITE_PAGES,i==null?void 0:i.lang]})):s.invalidateQueries({queryKey:[D.GET_WEBSITE_PAGES]});const l=i.template?`Page created from "${i.template.name}" template`:i.hasSlug===!1?"New "+((o=f.find(a,{key:i.pageType}))==null?void 0:o.name)+" added successfully":"New page added successfully";W.toast.success(l)},onError:(r,i)=>{const l=f.find(a,{key:i.pageType});W.toast.error(`Failed to add new ${l!=null&&l.hasSlug?"page":l.name}.`,{description:f.get(gi,r.message,r.message)})}})},gn=()=>{const e=le(),s=F.useQueryClient(),n=X(),{data:a}=We(),{data:r}=Ae();return F.useMutation({mutationFn:async i=>await n(e,{action:D.UPDATE_PAGE,data:i}),onSuccess:(i,l)=>{(a==null?void 0:a.id)===(l==null?void 0:l.id)&&s.invalidateQueries({queryKey:[D.GET_LANGUAGE_PAGES]}),l&&(l!=null&&l.primaryPage||l!=null&&l.seo)?(s.invalidateQueries({queryKey:[D.GET_LANGUAGE_PAGES,l==null?void 0:l.primaryPage]}),s.invalidateQueries({queryKey:[D.GET_WEBSITE_PAGES]})):s.invalidateQueries({queryKey:[D.GET_WEBSITE_PAGES]})},onError:(i,l)=>{const o=f.find(r,{key:l.pageType});W.toast.error(`Failed to update ${o!=null&&o.hasSlug?"page":o.name}.`,{description:i.message})}})},pi=()=>{const e=le(),s=F.useQueryClient(),n=X(),{data:a}=Ae();return F.useMutation({mutationFn:async r=>n(e,{action:D.DELETE_PAGE,data:{id:r==null?void 0:r.id}}),onSuccess:(r,i)=>{if(r.code==="PAGE_LOCKED"){W.toast.error("Delete not allowed",{description:"Page is currently being edited by another user."});return}i&&(i!=null&&i.primaryPage)?(s.invalidateQueries({queryKey:[D.GET_LANGUAGE_PAGES,i==null?void 0:i.primaryPage]}),s.invalidateQueries({queryKey:[D.GET_WEBSITE_PAGES]})):s.invalidateQueries({queryKey:[D.GET_WEBSITE_PAGES]})},onError:(r,i)=>{const l=f.find(a,{key:i.pageType});W.toast.error(`Failed to delete ${l!=null&&l.hasSlug?"page":l.name}.`,{description:r.message})}})},yi=()=>{const e=le(),s=F.useQueryClient(),n=X(),{data:a}=Ae();return F.useMutation({mutationFn:async r=>n(e,{action:D.TAKE_OFFLINE,data:{id:r==null?void 0:r.id}}),onSuccess:(r,i)=>{i&&(i!=null&&i.primaryPage)?s.invalidateQueries({queryKey:[D.GET_LANGUAGE_PAGES,i==null?void 0:i.primaryPage]}):s.invalidateQueries({queryKey:[D.GET_WEBSITE_PAGES]});const l=f.find(a,{key:i.pageType});W.toast.success(l!=null&&l.hasSlug?re.PAGE_UNPUBLISH_SUCCESS:"New "+l.name+" added successfully.")},onError:(r,i)=>{const l=f.find(a,{key:i.pageType});W.toast.error(`Failed to take offline ${l!=null&&l.hasSlug?"page":l.name}.`,{description:r.message})}})},xn=()=>{const e=le(),s=X(),n=F.useQueryClient(),{data:a}=ke(),{savePageAsync:r}=$.useSavePage();return F.useMutation({mutationFn:async({ids:i})=>(await r(),s(e,{action:D.PUBLISH_CHANGES,data:{ids:i}})),onSuccess:()=>{n.invalidateQueries({queryKey:[D.GET_CHANGES]}),n.invalidateQueries({queryKey:[D.GET_WEBSITE_PAGES]}),n.invalidateQueries({queryKey:[D.GET_LANGUAGE_PAGES,a==null?void 0:a.id]})},onError:i=>{console.log("##",i),W.toast.error("Failed to publish pages.")}})},ji=()=>{const e=le(),s=X(),n=F.useQueryClient();return F.useMutation({mutationFn:async a=>{var r;return s(e,{action:D.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:[D.GET_WEBSITE_PAGES]}),W.toast.success("Page marked as template successfully.")},onError:()=>{W.toast.error("Failed to mark page as template.")}})},vi=()=>{const e=le(),s=X(),n=F.useQueryClient();return F.useMutation({mutationFn:async a=>s(e,{action:D.UNMARK_AS_TEMPLATE,data:{id:a==null?void 0:a.id}}),onSuccess:()=>{n.invalidateQueries({queryKey:[D.GET_WEBSITE_PAGES]}),W.toast.success("Page unmarked as template successfully.")},onError:()=>{W.toast.error("Failed to unmark page as template.")}})},bi=()=>{const e=le(),s=X(),n=F.useQueryClient();return F.useMutation({mutationFn:async({id:a,slug:r})=>s(e,{action:D.CHANGE_SLUG,data:{id:a,slug:r}}),onSuccess:(a,{primaryPage:r})=>{W.toast.success(re.SLUG_CHANGE_SUCCESS),r?n.invalidateQueries({queryKey:[D.GET_LANGUAGE_PAGES,r]}):n.invalidateQueries({queryKey:[D.GET_WEBSITE_PAGES]})},onError:()=>{W.toast.error("Failed to change slug")}})};var pn={};(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 P=w.transferToImageBitmap();try{x.createPattern(P,"no-repeat")}catch{return!1}return!0}();function u(){}function d(w){var x=n.exports.Promise,P=x!==void 0?x:s.Promise;return typeof P=="function"?new P(w):(w(u,u),null)}var h=function(w,x){return{transform:function(P){if(w)return P;if(x.has(P))return x.get(P);var U=new OffscreenCanvas(P.width,P.height),C=U.getContext("2d");return C.drawImage(P,0,0),x.set(P,U),U},clear:function(){x.clear()}}}(o,new Map),m=function(){var w=Math.floor(16.666666666666668),x,P,U={},C=0;return typeof requestAnimationFrame=="function"&&typeof cancelAnimationFrame=="function"?(x=function(B){var O=Math.random();return U[O]=requestAnimationFrame(function z(J){C===J||C+w-1<J?(C=J,delete U[O],B()):U[O]=requestAnimationFrame(z)}),O},P=function(B){U[B]&&cancelAnimationFrame(U[B])}):(x=function(B){return setTimeout(B,w)},P=function(B){return clearTimeout(B)}),{frame:x,cancel:P}}(),j=function(){var w,x,P={};function U(C){function B(O,z){C.postMessage({options:O||{},callback:z})}C.init=function(z){var J=z.transferControlToOffscreen();C.postMessage({canvas:J},[J])},C.fire=function(z,J,ce){if(x)return B(z,null),x;var H=Math.random().toString(36).slice(2);return x=d(function(ae){function me(xe){xe.data.callback===H&&(delete P[H],C.removeEventListener("message",me),x=null,h.clear(),ce(),ae())}C.addEventListener("message",me),B(z,H),P[H]=me.bind(null,{data:{callback:H}})}),x},C.reset=function(){C.postMessage({reset:!0});for(var z in P)P[z](),delete P[z]}}return function(){if(w)return w;if(!a&&i){var C=["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([C])))}catch(B){return typeof console!==void 0&&typeof console.warn=="function"&&console.warn("🎊 Could not load worker",B),null}U(w)}return w}}(),y={particleCount:50,angle:90,spread:45,startVelocity:45,decay:.9,gravity:1,drift:0,ticks:200,x:.5,y:.5,shapes:["square","circle"],zIndex:100,colors:["#26ccff","#a25afd","#ff5e7e","#88ff5a","#fcff42","#ffa62d","#ff36ff"],disableForReducedMotion:!1,scalar:1};function v(w,x){return x?x(w):w}function p(w){return w!=null}function b(w,x,P){return v(w&&p(w[x])?w[x]:y[x],P)}function S(w){return w<0?0:Math.floor(w)}function E(w,x){return Math.floor(Math.random()*(x-w))+w}function L(w){return parseInt(w,16)}function I(w){return w.map(k)}function k(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:L(x.substring(0,2)),g:L(x.substring(2,4)),b:L(x.substring(4,6))}}function T(w){var x=b(w,"origin",Object);return x.x=b(x,"x",Number),x.y=b(x,"y",Number),x}function V(w){w.width=document.documentElement.clientWidth,w.height=document.documentElement.clientHeight}function ne(w){var x=w.getBoundingClientRect();w.width=x.width,w.height=x.height}function Y(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 _(w,x,P,U,C,B,O,z,J){w.save(),w.translate(x,P),w.rotate(B),w.scale(U,C),w.arc(0,0,1,O,z,J),w.restore()}function M(w){var x=w.angle*(Math.PI/180),P=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*P-Math.random()*P),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 Q(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 P=x.tick++/x.totalTicks,U=x.x+x.random*x.tiltCos,C=x.y+x.random*x.tiltSin,B=x.wobbleX+x.random*x.tiltCos,O=x.wobbleY+x.random*x.tiltSin;if(w.fillStyle="rgba("+x.color.r+", "+x.color.g+", "+x.color.b+", "+(1-P)+")",w.beginPath(),l&&x.shape.type==="path"&&typeof x.shape.path=="string"&&Array.isArray(x.shape.matrix))w.fill(ue(x.shape.path,x.shape.matrix,x.x,x.y,Math.abs(B-U)*.1,Math.abs(O-C)*.1,Math.PI/10*x.wobble));else if(x.shape.type==="bitmap"){var z=Math.PI/10*x.wobble,J=Math.abs(B-U)*.1,ce=Math.abs(O-C)*.1,H=x.shape.bitmap.width*x.scalar,ae=x.shape.bitmap.height*x.scalar,me=new DOMMatrix([Math.cos(z)*J,Math.sin(z)*J,-Math.sin(z)*ce,Math.cos(z)*ce,x.x,x.y]);me.multiplySelf(new DOMMatrix(x.shape.matrix));var xe=w.createPattern(h.transform(x.shape.bitmap),"no-repeat");xe.setTransform(me),w.globalAlpha=1-P,w.fillStyle=xe,w.fillRect(x.x-H/2,x.y-ae/2,H,ae),w.globalAlpha=1}else if(x.shape==="circle")w.ellipse?w.ellipse(x.x,x.y,Math.abs(B-U)*x.ovalScalar,Math.abs(O-C)*x.ovalScalar,Math.PI/10*x.wobble,0,2*Math.PI):_(w,x.x,x.y,Math.abs(B-U)*x.ovalScalar,Math.abs(O-C)*x.ovalScalar,Math.PI/10*x.wobble,0,2*Math.PI);else if(x.shape==="star")for(var ie=Math.PI/2*3,Ce=4*x.scalar,_e=8*x.scalar,G=x.x,q=x.y,be=5,Be=Math.PI/be;be--;)G=x.x+Math.cos(ie)*_e,q=x.y+Math.sin(ie)*_e,w.lineTo(G,q),ie+=Be,G=x.x+Math.cos(ie)*Ce,q=x.y+Math.sin(ie)*Ce,w.lineTo(G,q),ie+=Be;else w.moveTo(Math.floor(x.x),Math.floor(x.y)),w.lineTo(Math.floor(x.wobbleX),Math.floor(C)),w.lineTo(Math.floor(B),Math.floor(O)),w.lineTo(Math.floor(U),Math.floor(x.wobbleY));return w.closePath(),w.fill(),x.tick<x.totalTicks}function R(w,x,P,U,C){var B=x.slice(),O=w.getContext("2d"),z,J,ce=d(function(H){function ae(){z=J=null,O.clearRect(0,0,U.width,U.height),h.clear(),C(),H()}function me(){a&&!(U.width===r.width&&U.height===r.height)&&(U.width=w.width=r.width,U.height=w.height=r.height),!U.width&&!U.height&&(P(w),U.width=w.width,U.height=w.height),O.clearRect(0,0,U.width,U.height),B=B.filter(function(xe){return Q(O,xe)}),B.length?z=m.frame(me):ae()}z=m.frame(me),J=ae});return{addFettis:function(H){return B=B.concat(H),ce},canvas:w,promise:ce,reset:function(){z&&m.cancel(z),J&&J()}}}function Z(w,x){var P=!w,U=!!b(x||{},"resize"),C=!1,B=b(x,"disableForReducedMotion",Boolean),O=i&&!!b(x||{},"useWorker"),z=O?j():null,J=P?V:ne,ce=w&&z?!!w.__confetti_initialized:!1,H=typeof matchMedia=="function"&&matchMedia("(prefers-reduced-motion)").matches,ae;function me(ie,Ce,_e){for(var G=b(ie,"particleCount",S),q=b(ie,"angle",Number),be=b(ie,"spread",Number),Be=b(ie,"startVelocity",Number),Gs=b(ie,"decay",Number),Us=b(ie,"gravity",Number),Fs=b(ie,"drift",Number),us=b(ie,"colors",I),qs=b(ie,"ticks",Number),ds=b(ie,"shapes"),$s=b(ie,"scalar"),zs=!!b(ie,"flat"),Ot=T(ie),ft=G,Ze=[],hs=w.width*Ot.x,ms=w.height*Ot.y;ft--;)Ze.push(M({x:hs,y:ms,angle:q,spread:be,startVelocity:Be,color:us[ft%us.length],shape:ds[E(0,ds.length)],ticks:qs,decay:Gs,gravity:Us,drift:Fs,scalar:$s,flat:zs}));return ae?ae.addFettis(Ze):(ae=R(w,Ze,J,Ce,_e),ae.promise)}function xe(ie){var Ce=B||b(ie,"disableForReducedMotion",Boolean),_e=b(ie,"zIndex",Number);if(Ce&&H)return d(function(Be){Be()});P&&ae?w=ae.canvas:P&&!w&&(w=Y(_e),document.body.appendChild(w)),U&&!ce&&J(w);var G={width:w.width,height:w.height};z&&!ce&&z.init(w),ce=!0,z&&(w.__confetti_initialized=!0);function q(){if(z){var Be={getBoundingClientRect:function(){if(!P)return w.getBoundingClientRect()}};J(Be),z.postMessage({resize:{width:Be.width,height:Be.height}});return}G.width=G.height=null}function be(){ae=null,U&&(C=!1,s.removeEventListener("resize",q)),P&&w&&(document.body.contains(w)&&document.body.removeChild(w),w=null,ce=!1)}return U&&!C&&(C=!0,s.addEventListener("resize",q,!1)),z?z.fire(ie,G,be):me(ie,G,be)}return xe.reset=function(){z&&z.reset(),ae&&ae.reset()},xe}var K;function te(){return K||(K=Z(null,{useWorker:!0,resize:!0})),K}function ue(w,x,P,U,C,B,O){var z=new Path2D(w),J=new Path2D;J.addPath(z,new DOMMatrix(x));var ce=new Path2D;return ce.addPath(J,new DOMMatrix([Math.cos(O)*C,Math.sin(O)*C,-Math.sin(O)*B,Math.cos(O)*B,P,U])),ce}function he(w){if(!l)throw new Error("path confetti are not supported in this browser");var x,P;typeof w=="string"?x=w:(x=w.path,P=w.matrix);var U=new Path2D(x),C=document.createElement("canvas"),B=C.getContext("2d");if(!P){for(var O=1e3,z=O,J=O,ce=0,H=0,ae,me,xe=0;xe<O;xe+=2)for(var ie=0;ie<O;ie+=2)B.isPointInPath(U,xe,ie,"nonzero")&&(z=Math.min(z,xe),J=Math.min(J,ie),ce=Math.max(ce,xe),H=Math.max(H,ie));ae=ce-z,me=H-J;var Ce=10,_e=Math.min(Ce/ae,Ce/me);P=[_e,0,0,_e,-Math.round(ae/2+z)*_e,-Math.round(me/2+J)*_e]}return{type:"path",path:x,matrix:P}}function oe(w){var x,P=1,U="#000000",C='"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,P="scalar"in w?w.scalar:P,C="fontFamily"in w?w.fontFamily:C,U="color"in w?w.color:U);var B=10*P,O=""+B+"px "+C,z=new OffscreenCanvas(B,B),J=z.getContext("2d");J.font=O;var ce=J.measureText(x),H=Math.ceil(ce.actualBoundingBoxRight+ce.actualBoundingBoxLeft),ae=Math.ceil(ce.actualBoundingBoxAscent+ce.actualBoundingBoxDescent),me=2,xe=ce.actualBoundingBoxLeft+me,ie=ce.actualBoundingBoxAscent+me;H+=me+me,ae+=me+me,z=new OffscreenCanvas(H,ae),J=z.getContext("2d"),J.font=O,J.fillStyle=U,J.fillText(x,xe,ie);var Ce=1/P;return{type:"bitmap",bitmap:z.transferToImageBitmap(),matrix:[Ce,0,0,Ce,-H*Ce/2,-ae*Ce/2]}}n.exports=function(){return te().apply(this,arguments)},n.exports.reset=function(){te().reset()},n.exports.create=Z,n.exports.shapeFromPath=he,n.exports.shapeFromText=oe})(function(){return typeof window<"u"?window:typeof self<"u"?self:this||{}}(),pn,!1);const wi=pn.exports;pn.exports.create;const Si={particleCount:350,spread:120,origin:{y:.6},angle:90},Ni={TOP_RIGHT:{angle:225,origin:{x:.9,y:0}},BOTTOM_RIGHT:{angle:100,origin:{x:.9,y:.9}}},$t=e=>{let s=Ni[e];s||(s={});const n={...Si,...s};wi(n)},Ei=()=>{const[e]=$.useTheme(),{mutate:s,isPending:n}=xn(),{mutateAsync:a,isPending:r}=la(),i=()=>{a({settings:{theme:e}})},l=async()=>{await a({settings:{theme:e}}),s({ids:["THEME"]},{onSuccess:()=>{$t("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"})]})},os=je.atom(null),Ci=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}},at=e=>{if(!e)return e;const{base:s}=Ci(e);return s};function Ai(e,s){const n=(e||"").split("/").filter(Boolean);let a="",r=!0;if(s.slug==="/"){const i=n.pop()||"";if(Ee[i])r=!0;else{a=i;const l=n.pop()||"";r=!!Ee[l]}}else if(s.parent)n.length&&(a=n.pop()||"");else if(n.length){a=n.pop()||"";const i=n.pop()||"";r=!!Ee[i]}return{initSlug:a,prefix:r}}const Ti=e=>e&&at(e),Bn=(e,s)=>{const n=at(e||"");return!n||n==="/"?`/${s}`:`${n}/${s}`};function yn({value:e,onChange:s,placeholder:n,parentSlug:a,onValidationChange:r,disabled:i=!1,fullSlug:l}){const[o,u]=g.useState(e),[d,h]=g.useState(null);g.useEffect(()=>{u(e)},[e]);const m=j=>{const v=j.target.value.replace(/\//g,"").replace(/\s+/g,"-").replace(/[^a-zA-Z0-9-_.]/g,"-").replace(/-+/g,"-").replace(/^-+/,"").toLowerCase(),p=(v.match(/\./g)||[]).length,b=p<=1;p>1?h("Invalid slug. Only one dot (.) is allowed in the slug"):h(null),r&&r(b),u(v),s(v)};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:Ti(a)})]})}),t.jsxs("div",{className:"relative",children:[t.jsx(c.Input,{disabled:i,value:o,onChange:m,placeholder:n,className:d?"border-red-500":""}),d&&t.jsx("div",{className:"mt-1 text-xs text-red-500",children:d})]}),l&&l!=="undefined"&&t.jsx("div",{className:"mt-1 flex items-center",children:t.jsxs("span",{className:"text-xs text-gray-500",children:["Complete Slug: ",t.jsx("span",{className:"font-mono text-gray-900",children:l})]})})]})}const va=({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:re.LANGUAGE}),t.jsxs("select",{value:e?"":s,disabled:e||!n.length,onChange:o=>{const u=o.target.value;r(u),!e&&(f.startsWith(a,l==null?void 0:l.name)||a.length===0)&&i(`${l==null?void 0:l.name} - ${Ee[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?Ee[s]||s:n.length?re.CHOOSE_LANGUAGE:re.ALL_AVAILABLE_LANGUAGE_PAGE}),n.map(o=>t.jsx("option",{value:o,children:Ee[o]||o},o))]})]}),ba=({lang:e,name:s,setName:n,parentHasSelectedLanguagePage:a})=>t.jsxs("div",{className:"space-y-1",children:[t.jsx(c.Label,{htmlFor:"name",children:re.PAGE_NAME}),t.jsx(c.Input,{id:"name",value:e?s:"",onChange:r=>n(r.target.value),required:!0,placeholder:e?re.ENTER_PAGE_NAME:re.CHOOSE_LANGUAGE_TO_ADD_SLUG,disabled:!a||!e})]}),ki=({dynamic:e,isNonSlugPageType:s,isRootPage:n,lang:a,useLanguagePrefix:r,setUseLanguagePrefix:i,isHomePage:l,parentSlug:o,parentHasSelectedLanguagePage:u,slug:d,setSlug:h,setIsSlugValid:m,getSlug:j})=>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:y=>i(y.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:re.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(yn,{disabled:!a||!u,value:d,onChange:h,placeholder:a?l&&r?"Leave empty for home page":re.ENTER_PAGE_SLUG:re.CHOOSE_LANGUAGE_TO_ADD_SLUG,parentSlug:o,onValidationChange:m,fullSlug:j()})]}),wa=({parentHasSelectedLanguagePage:e,name:s,lang:n,slug:a,edit:r,id:i,primaryPageObject:l,pages:o,isNonSlugPageType:u,isHomePage:d,useLanguagePrefix:h,isSlugValid:m,isPending:j})=>{const y=j||!s||!n||o.some(v=>(r?v.id!==i:!0)&&v.parent===(l==null?void 0:l.id)&&v.lang===n)||!u&&!(d&&h)&&(!m||!a);return t.jsx(c.DialogFooter,{children:e?t.jsxs(t.Fragment,{children:[t.jsx(c.Button,{type:"submit",disabled:y&&!l.dynamic,children:j?t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsx("span",{className:"loader mr-2"}),r?re.UPDATING:re.ADDING]}):r?re.UPDATE:re.ADD_NEW_LANGUAGE}),o.some(v=>(r?v.id!==i:!0)&&v.parent===(l==null?void 0:l.id)&&v.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:Ee[n]})," page in the parent to add here."]})})})},Pi=({onSubmit:e,edit:s,lang:n,languages:a,name:r,setLang:i,setName:l,primaryPageObject:o,parentHasSelectedLanguagePage:u,id:d,pages:h,isNonSlugPageType:m,isHomePage:j,useLanguagePrefix:y,slug:v,isSlugValid:p,isPending:b})=>t.jsxs("form",{onSubmit:e,children:[t.jsxs("div",{className:"grid gap-4 py-4",children:[t.jsx(va,{edit:s,lang:n,languages:a,name:r,setLang:i,setName:l,primaryPageObject:o}),t.jsx(ba,{lang:n,name:r,setName:l,parentHasSelectedLanguagePage:u})]}),t.jsx(wa,{parentHasSelectedLanguagePage:u,name:r,lang:n,slug:v,edit:s,id:d,primaryPageObject:o,pages:h,isNonSlugPageType:m,isHomePage:j,useLanguagePrefix:y,isSlugValid:p,isPending:b})]}),Ii=({loading:e,onSubmit:s,edit:n,lang:a,languages:r,name:i,setLang:l,setName:o,primaryPageObject:u,parentHasSelectedLanguagePage:d,isNonSlugPageType:h,isRootPage:m,useLanguagePrefix:j,setUseLanguagePrefix:y,isHomePage:v,parentSlug:p,slug:b,setSlug:S,isSlugValid:E,setIsSlugValid:L,getSlug:I,isPending:k,id:T,pages:V})=>e?t.jsx("div",{className:"flex h-80 items-center justify-center",children:t.jsx(N.Loader,{className:"animate-spin"})}):h?t.jsx(Pi,{onSubmit:s,edit:n,lang:a,languages:r,name:i,setLang:l,setName:o,primaryPageObject:u,parentHasSelectedLanguagePage:d,id:T,pages:V,isNonSlugPageType:h,isHomePage:v,useLanguagePrefix:j,slug:b,isSlugValid:E,isPending:k}):t.jsxs("form",{onSubmit:s,children:[t.jsxs("div",{className:"grid gap-4 py-4",children:[t.jsx(va,{edit:n,lang:a,languages:r,name:i,setLang:l,setName:o,primaryPageObject:u}),t.jsx(ba,{lang:a,name:i,setName:o,parentHasSelectedLanguagePage:d}),t.jsx(ki,{dynamic:u==null?void 0:u.dynamic,isNonSlugPageType:h,isRootPage:m,lang:a,useLanguagePrefix:j,setUseLanguagePrefix:y,isHomePage:v,parentSlug:p,parentHasSelectedLanguagePage:d,slug:b,setSlug:S,isSlugValid:E,setIsSlugValid:L,getSlug:I})]}),t.jsx(wa,{parentHasSelectedLanguagePage:d,name:i,lang:a,slug:b,edit:n,id:T,primaryPageObject:u,pages:V,isNonSlugPageType:h,isHomePage:v,useLanguagePrefix:j,isSlugValid:E,isPending:k})]}),_i=({id:e,isOpen:s,onClose:n,primaryPage:a,edit:r=!1,preselectedLang:i})=>{const{data:l=[]}=ht(),o=g.useMemo(()=>l.find(H=>H.id===a),[l,a]),[u,d]=g.useState(""),[h,m]=g.useState(""),[j,y]=g.useState(""),[v,p]=g.useState(!0),[b,S]=g.useState(!0),{mutate:E,isPending:L}=ja(),{mutate:I,isPending:k}=gn(),T=L||k,{data:V,isFetching:ne}=Ke(),Y=Qe(),{data:_,isFetching:M}=qe(a),{data:Q=[],isFetching:R}=qe(o==null?void 0:o.parent),{data:Z=[],isFetching:K}=Ae(),{setSelectedLang:te}=$.useLanguages(),[,ue]=Pe(),[,he]=$.useSidebarActivePanel(),oe=ne||M||R||K,w=g.useMemo(()=>f.filter(V==null?void 0:V.languages,H=>!f.find(_,{lang:H})),[V,_]),x=g.useMemo(()=>Z.find(H=>H.key===(o==null?void 0:o.pageType)),[Z,o==null?void 0:o.pageType]),P=!(x!=null&&x.hasSlug),U=(o==null?void 0:o.slug)==="/";g.useEffect(()=>{if(!r&&o&&i&&(m(i),d(`${o.name} - ${Ee[i]}`)),!r||!o)return;const H=_==null?void 0:_.find(ie=>ie.id===e);if(!H)return;d(H.name),m(H.lang);const ae=H.slug||"",{initSlug:me,prefix:xe}=Ai(ae,o);y(me),S(xe)},[r,e,_,o,i]),g.useEffect(()=>{i&&m(i)},[i]);const{parentSlug:C,isRootPage:B}=g.useMemo(()=>{if(U||!h)return{parentSlug:void 0,isRootPage:!(o!=null&&o.parent)};if(!(o!=null&&o.parent))return{parentSlug:b?`/${h}`:void 0,isRootPage:!0};const H=Q==null?void 0:Q.find(ae=>ae.lang===h);return{parentSlug:H==null?void 0:H.slug,isRootPage:!1}},[o==null?void 0:o.parent,Q,b,h,U]),O=g.useMemo(()=>B?!0:!!(Q!=null&&Q.some(H=>(H==null?void 0:H.lang)===h)),[h,Q,B]),z=()=>{let H="";return B?H=`/${b?[h,j].filter(Boolean).join("/"):j}`:H=`${at(C)}/${j}`,H.replace(/\/{2,}/g,"/").replace(/\/$/,"")},J=H=>{const ae=new URLSearchParams(window.location.search);Y&&H===Y?ae.delete("lang"):ae.set("lang",H),ue(ae),window.dispatchEvent(new PopStateEvent("popstate"))},ce=H=>{H.preventDefault();const ae={name:u,lang:h,primaryPage:o==null?void 0:o.id,slug:P?"":z(),pageType:o==null?void 0:o.pageType,...r&&{id:e}},me=()=>{!r&&h&&(te(h),J(h)),he("outline"),n()};r?I(ae,{onSuccess:me}):E(ae,{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?re.EDIT_LANGUAGE:re.ADD_NEW_LANGUAGE}),t.jsx(c.DialogDescription,{className:"font-light",children:re.ENTER_LANGUAGE_DETAILS})]}),t.jsx(Ii,{id:e,pages:l,loading:oe,onSubmit:ce,edit:r,lang:h,languages:w,name:u,setLang:m,setName:d,primaryPageObject:o,parentHasSelectedLanguagePage:O,isNonSlugPageType:P,isRootPage:B,useLanguagePrefix:b,setUseLanguagePrefix:S,isHomePage:U,parentSlug:C,slug:j,setSlug:y,isSlugValid:v,setIsSlugValid:p,getSlug:z,isPending:T})]})})};function Li({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=y=>{const v=y.target.value;if(!v.startsWith(a)){const I=v.replace(a,""),k=a+I;d(k),s(I);return}const b=v.substring(a.length).replace(/\//g,"").replace(/\s+/g,"-").replace(/[^a-zA-Z0-9-_.]/g,"-").replace(/-+/g,"-").replace(/^-+/,"").toLowerCase(),S=(b.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 L=a+b;d(L),s(b)},m=()=>{if(o.current){const y=o.current;setTimeout(()=>{const v=a.length;y.setSelectionRange(v,v)},0)}},j=y=>{const v=y.currentTarget;(v.selectionStart||0)<=a.length&&setTimeout(()=>{const b=a.length;v.setSelectionRange(b,b)},0)};return t.jsx("div",{children:t.jsxs("div",{className:"relative",children:[t.jsxs("p",{className:"text-gray-500 text-xs mb-2",children:[`${a}`," is a dynamic segment of slug"]}),t.jsx(c.Input,{ref:o,value:u,onChange:h,onFocus:m,onClick:j,placeholder:n,className:i?"border-red-500":""}),i&&t.jsx("div",{className:"text-red-500 text-xs mt-1",children:i})]})})}const ws=({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})},Vs=(...e)=>e.filter(Boolean).join(" ");function Di({pages:e,selectedParentId:s,onChange:n,className:a,id:r="parentPage",currentPage:i}){const[l,o]=g.useState(!1),[u,d]=g.useState(""),h=$.useChaiFeatureFlag("enable-add-page-dropdown");h||(a="w-full rounded-md border border-gray-300 px-3 py-2");const m=g.useMemo(()=>!e||e.length===0?[]:e.filter(E=>!f.isEmpty(E.slug)).filter(E=>E.slug!=="/").sort((E,L)=>E.slug.localeCompare(L.slug)),[e]),j=g.useMemo(()=>{if(!u.trim())return m;const S=u.toLowerCase();return m.filter(E=>E.name.toLowerCase().includes(S)||E.slug.toLowerCase().includes(S))},[m,u]),y=S=>Math.max(0,(S.match(/\//g)||[]).length-1),v=S=>" ".repeat(S),p=S=>{if(S==="/")return"/";const E=S.split("/").filter(Boolean);if(E.length<=1){const L=E[0]||"";return`/${at(L)}`}return`/${at(E[E.length-1])}`},b=()=>{if(!s||s==="none")return"None";const S=m.find(E=>E.id===s);return S?`${S.name} (${p(S.slug)})`:"None"};return t.jsxs("div",{className:"space-y-0.5",children:[t.jsx(c.Label,{htmlFor:r,className:"text-sm",children:"Parent"}),h?t.jsxs(c.Popover,{open:l,onOpenChange:o,children:[t.jsx(c.PopoverTrigger,{asChild:!0,children:t.jsxs(c.Button,{id:r,variant:"outline",role:"combobox",className:Vs("w-full justify-between",a),"data-testid":"parent-page-selector",children:[b(),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:u,onChange:S=>d(S.target.value)})]})})}),t.jsxs(ws,{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(""),o(!1),d("")},className:"flex cursor-pointer items-center justify-between",children:[t.jsx("span",{children:"None"}),t.jsx(N.Check,{className:Vs("mr-2 h-4 w-4",s?"opacity-0":"opacity-100")})]}),j.map(S=>{const E=v(y(S.slug)),L=p(S.slug),I=t.jsxs("span",{className:"flex items-center text-sm",children:[E,S.name,t.jsxs("span",{className:"text-xs text-gray-500",children:[" (",L,")"]})]});return t.jsxs(c.CommandItem,{value:S.id,onSelect:()=>{n(S.id),o(!1),d("")},className:"flex cursor-pointer items-center justify-between whitespace-pre-wrap",children:[t.jsx("span",{children:I}),t.jsx(N.Check,{className:Vs("mr-2 h-4 w-4 shrink-0",s===S.id?"opacity-100":"opacity-0")})]},S.id)})]})]})]})})]}):t.jsxs("select",{id:r,value:s||"none",onChange:S=>n(S.target.value),className:a,"data-testid":"parent-page-selector",children:[t.jsx("option",{value:"none",children:"None"}),m.map(S=>{const E=y(S.slug),L=E>0?v(E):"",I=p(S.slug);return(i==null?void 0:i.id)===S.id||S.slug.startsWith(i==null?void 0:i.slug)?null:t.jsxs("option",{value:S.id,children:[L,S.name," (",I,")"]},S.id)})]})]})}const Bi=(...e)=>e.filter(Boolean).join(" "),Ri=({templates:e,selectedTemplateId:s,onSelectTemplate:n,isLoading:a=!1})=>{const[r,i]=g.useState(""),[l,o]=g.useState(!1),[u,d]=g.useState(""),h=$.useChaiFeatureFlag("enable-add-page-dropdown");if(g.useEffect(()=>{if(s){const p=e.find(b=>b.id===s);i((p==null?void 0:p.preview)||"")}else i("")},[s,e]),a)return t.jsx("div",{className:"flex h-fit items-center justify-center text-sm text-gray-500",children:"Loading templates..."});if(e.length===0)return null;const m={};e.forEach(p=>{const b=p.libraryName;m[b]||(m[b]=[]),m[b].push(p)});const j=Object.entries(m).reduce((p,[b,S])=>{const E=S.filter(L=>L.name.toLowerCase().includes(u.toLowerCase())||b.toLowerCase().includes(u.toLowerCase()));return E.length>0&&(p[b]=E),p},{}),y=e.find(p=>p.id===s),v=y?f.startCase(y.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:[v,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:p=>d(p.target.value)})]})}),t.jsxs(ws,{className:"max-h-[300px] overflow-y-auto",children:[t.jsx(c.CommandEmpty,{children:"No templates found."}),Object.entries(j).map(([p,b])=>t.jsx(c.CommandGroup,{heading:p,children:b.map(S=>t.jsxs(c.CommandItem,{value:S.id,onSelect:()=>{n(S.id),o(!1),d("")},className:"flex cursor-pointer items-center justify-between",children:[f.startCase(S.name),t.jsx(N.Check,{className:Bi("mr-2 h-4 w-4",s===S.id?"opacity-100":"opacity-0")})]},S.id))},p))]})]})})]}):t.jsxs("select",{className:"w-full rounded-md border border-gray-300 px-3 py-2",value:s,onChange:p=>n(p.target.value),children:[t.jsx("option",{value:"",children:"No Template"}),Object.entries(m).map(([p,b])=>t.jsx("optgroup",{label:p,children:b.map(S=>t.jsx("option",{value:S.id,children:f.startCase(S.name)},S.id))},p))]}),r&&t.jsxs("div",{className:"mt-3 overflow-hidden rounded border",children:[t.jsx("div",{className:"max-h-[200px] overflow-auto",children:t.jsx("img",{src:r,alt:"Template Preview",className:"w-full object-contain"})}),t.jsx("div",{className:"border-t bg-gray-50 p-2 text-xs text-gray-500",children:"Template preview"})]})]})},Mi=()=>{const e=le(),s=X();return F.useQuery({queryKey:[D.GET_LIBRARIES],queryFn:async()=>await s(e,{action:D.GET_LIBRARIES})||[]})},Oi=e=>{const s=le(),n=X();return F.useQuery({queryKey:[D.GET_TEMPLATES_BY_TYPE,e],enabled:!!e,queryFn:async()=>{const a=await n(s,{action:D.GET_TEMPLATES_BY_TYPE,data:{pageType:e}});return(e?f.filter(a,{pageType:e}):a)||[]}})},Gi=e=>{const{data:s=[],isLoading:n}=Oi(e),{data:a=[],isLoading:r}=Mi(),i=g.useMemo(()=>n||r?[]:s.map(o=>{const u=f.find(a,{id:o.library});return{...o,libraryName:(u==null?void 0:u.type)!=="shared"?"Site Library":(u==null?void 0:u.name)+" Library",libraryType:u==null?void 0:u.type}}),[s,a,n,r]),l=g.useMemo(()=>f.groupBy(i,"libraryName"),[i]);return{data:i,groupedData:l,isLoading:n||r}},jn=()=>{const[,e]=Pe();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])},Ss=(e,s)=>{const n={seo:{keyword:"",title:"",description:"",noIndex:!1,noFollow:!1,canonicalUrl:"",ogTitle:"",ogDescription:"",jsonLD:""},jsonLD:{}};e!=null&&e.defaultSeo&&(f.has(e.defaultSeo,s)&&f.isObject(e.defaultSeo[s])?n.seo={...n.seo,...e.defaultSeo[s]}:n.seo={...n.seo,...e.defaultSeo});let a={};return e!=null&&e.defaultJSONLD&&(f.has(e.defaultJSONLD,s)&&f.isObject(e.defaultJSONLD[s])?(a=e.defaultJSONLD[s],f.set(n,"seo.jsonLD",JSON.stringify(a))):(a=e.defaultJSONLD,f.set(n,"seo.jsonLD",JSON.stringify(a)))),{seo:n.seo,jsonLD:a}},it=(...e)=>e.filter(Boolean).join(" ");function Ui({addEditPage:e,additionalPageTypes:s=[],close:n,closePanel:a}){var hs,ms;const r=jn(),i=!!(e!=null&&e.id),{data:l}=ht(),{mutate:o,isPending:u}=ja(),{mutate:d,isPending:h}=gn(),[m,j]=g.useState(null),[y,v]=g.useState(!0),[p,b]=g.useState((e==null?void 0:e.pageType)??"page"),{hasPermission:S}=$.usePermissions(),E=S(we.CHANGE_PAGE_TYPE),[L,I]=g.useState(!1),[k,T]=g.useState(""),{selectedLang:V,fallbackLang:ne}=$.useLanguages(),Y=V||ne,[_,M]=g.useState(""),[Q,R]=g.useState(!1),Z=g.useMemo(()=>{const A=s.find(de=>de.key===p);return(A==null?void 0:A.hasSlug)===!1},[p,s]),[K,te]=g.useState((e==null?void 0:e.parent)??""),[ue,he]=g.useState((e==null?void 0:e.name)??""),[oe,w]=g.useState((e==null?void 0:e.dynamic)??!1),[x,P]=g.useState(oe?"":((e==null?void 0:e.slug)??"").split("/").pop()||""),[U,C]=g.useState((e==null?void 0:e.dynamicSlugCustom)??""),[B,O]=g.useState(!0),[z,J]=g.useState(!1),[ce,H]=g.useState(""),{data:ae,isLoading:me}=Gi(p),xe=u||h,ie=$.useChaiFeatureFlag("enable-add-page-dropdown"),Ce=g.useMemo(()=>!i||!(e!=null&&e.id)||!l?null:l.find(A=>A.id===e.id),[i,e==null?void 0:e.id,l]),_e=(Ce==null?void 0:Ce.online)||!1,G=g.useMemo(()=>!i||!(e!=null&&e.id)||!l?!1:l.some(A=>A.parent===e.id),[i,e==null?void 0:e.id,l]),q=s.find(A=>A.key===p),be=A=>{if(i&&p!==A){T(A),I(!0),M(""),R(!1);return}b(A),M(""),R(!1)},Be=()=>{b(k),I(!1),w(!1)},Gs=A=>{w(A),A?P(""):C("")},Us=A=>{if(te(A),A&&A!=="none"){const de=l==null?void 0:l.find(De=>De.id===A),Ge=(de==null?void 0:de.slug)||"";if(x.startsWith(Ge)){const De=x.slice(Ge.length).replace(/^\/+/,"");P(De)}else P(x.replace(/^\/+/,""))}else P(x?`${x}`:"")},Fs=A=>{H(A)},us=()=>ue.trim()?oe&&!f.isEmpty(x)?(j("Slug must be empty when using dynamic slug"),!1):oe&&!B?(j("Dynamic slug is invalid"),!1):!0:(W.toast.error("Name is required"),!1),qs=()=>{const A={pageType:q==null?void 0:q.key,name:ue,slug:"",hasSlug:!1};i?d({id:e==null?void 0:e.id,name:ue},{onSuccess:()=>{W.toast.success((q==null?void 0:q.name)+" updated successfully"),n()}}):o(A,{onSuccess:de=>{n(),r(de.page.id,a)}})},ds=(A,de)=>{if(!A.trim()&&!oe)return j("Child page slug is required"),!1;const Ge=at(de),De=Bn(Ge,A);return Object.keys(Ee).some(fs=>De===`/${fs}`||(De==null?void 0:De.startsWith(`/${fs}/`)))?(j("Slugs cannot start with a language code for primary page"),!1):!0},$s=(A,de)=>{const Ge=at(de),De=Bn(Ge,A),Oe={pageType:p,name:ue,slug:De.replace(/\/$/,""),parent:K,dynamic:oe,hasSlug:!0,template:ce||void 0,tracking:{},seo:{},jsonLD:{}};if(oe&&(Oe.dynamicSlugCustom=U),i){const Ue=f.pick(Oe,["pageType","parent","name","slug","dynamic","dynamicSlugCustom"]);d({id:e==null?void 0:e.id,...Ue},{onSuccess:()=>{W.toast.success("Page updated successfully"),n()}})}else{const Ue=f.find(s,{key:p});Ue!=null&&Ue.trackingDefault&&(Oe.tracking=Ue.trackingDefault);const{seo:fs,jsonLD:wr}=Ss(Ue,Y);f.set(Oe,"seo",fs),f.set(Oe,"jsonLD",wr),o(Oe,{onSuccess:Sr=>{n(),r(Sr.page.id,a)}})}},zs=()=>{const A={pageType:p,name:ue,slug:x===""?"/":`/${x.replace(/\/$/,"")}`,template:ce||void 0,parent:null,tracking:{}};if(i)d({id:e==null?void 0:e.id,...A},{onSuccess:()=>{W.toast.success("Page updated successfully"),n()}});else{const de=f.find(s,{key:p});de!=null&&de.trackingDefault&&(A.tracking=de.trackingDefault);const{seo:Ge,jsonLD:De}=Ss(de,Y);f.set(A,"seo",Ge),f.set(A,"jsonLD",De),o(A,{onSuccess:Oe=>{var Ue;(Ue=Oe==null?void 0:Oe.page)!=null&&Ue.id&&r(Oe.page.id,a),n()}})}},Ot=A=>{if(A.preventDefault(),j(null),!!us()){if(!(q!=null&&q.hasSlug)){qs();return}if(K&&K!=="none"){const de=l==null?void 0:l.find(De=>De.id===K),Ge=(de==null?void 0:de.slug)||"";if(!ds(x,Ge))return;$s(x,Ge)}else zs()}},{pagesType:ft,partialsType:Ze}=g.useMemo(()=>{const A=de=>_?de.name.toLowerCase().includes(_.toLowerCase())||de.key.toLowerCase().includes(_.toLowerCase()):!0;return{pagesType:s.filter(de=>de.hasSlug!==!1&&A(de)),partialsType:s.filter(de=>de.hasSlug===!1&&A(de))}},[s,_]);return q!=null&&q.hasSlug?t.jsxs("form",{onSubmit:Ot,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"}),ie?t.jsxs(c.Popover,{open:Q,onOpenChange:R,children:[t.jsx(c.PopoverTrigger,{asChild:!0,children:t.jsxs(c.Button,{variant:"outline",role:"combobox",disabled:i&&!E,className:it("w-full justify-between",i&&!E?"cursor-not-allowed text-gray-500":""),children:[(q==null?void 0:q.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:_,onChange:A=>M(A.target.value)})]})}),t.jsxs(ws,{className:"overflow-y-auto",children:[t.jsx(c.CommandEmpty,{children:"No page type found."}),i?Z?t.jsx(c.CommandGroup,{heading:"Partials",children:Ze.map(A=>t.jsxs(c.CommandItem,{value:A.key,onSelect:()=>be(A.key),className:"flex cursor-pointer items-center justify-between",children:[A.name,t.jsx(N.Check,{className:it("mr-2 h-4 w-4",p===A.key?"opacity-100":"opacity-0")})]},A.key))}):t.jsx(c.CommandGroup,{heading:"Pages",children:ft.map(A=>t.jsxs(c.CommandItem,{value:A.key,onSelect:()=>be(A.key),className:"flex cursor-pointer items-center justify-between",children:[A.name,t.jsx(N.Check,{className:it("mr-2 h-4 w-4",p===A.key?"opacity-100":"opacity-0")})]},A.key))}):t.jsxs(t.Fragment,{children:[ft.length>0&&t.jsx(c.CommandGroup,{heading:"Pages",children:ft.map(A=>t.jsxs(c.CommandItem,{value:A.key,onSelect:()=>be(A.key),className:"flex cursor-pointer items-center justify-between",children:[A.name,t.jsx(N.Check,{className:it("mr-2 h-4 w-4",p===A.key?"opacity-100":"opacity-0")})]},A.key))}),Ze.length>0&&t.jsx(c.CommandGroup,{heading:"Partials",children:Ze.map(A=>t.jsxs(c.CommandItem,{value:A.key,onSelect:()=>be(A.key),className:"flex cursor-pointer items-center justify-between",children:[A.name,t.jsx(N.Check,{className:it("mr-2 h-4 w-4",p===A.key?"opacity-100":"opacity-0")})]},A.key))})]})]})]})})]}):t.jsx("select",{id:"pageType",value:p,disabled:i&&!E,onChange:A=>be(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))})]})}),L&&t.jsxs("div",{className:"mt-2 rounded-md border border-yellow-200 bg-yellow-50 p-3",children:[t.jsx("p",{className:"text-sm text-yellow-800",children:"Changing the page type may impact the page data. Are you sure you want to proceed?"}),t.jsxs("div",{className:"mt-2 flex gap-2",children:[t.jsx(c.Button,{variant:"outline",size:"sm",onClick:()=>I(!1),children:"Cancel"}),t.jsx(c.Button,{variant:"default",size:"sm",onClick:Be,children:"Confirm"})]})]})]}),!i&&(q==null?void 0:q.hasSlug)&&ae.length>0&&t.jsxs("div",{className:"space-y-1",children:[t.jsx(c.Label,{className:"mb-1 block text-sm",children:"Template"}),t.jsx(Ri,{templates:ae,selectedTemplateId:ce,onSelectTemplate:Fs,isLoading:me})]}),t.jsx(Di,{pages:l,selectedParentId:K,onChange:Us,currentPage:e}),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:ue,onChange:A=>he(A.target.value),required:!0,"aria-required":"true",placeholder:"Enter page name"})]}),(q==null?void 0:q.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:oe,onChange:A=>Gs(A.target.checked),className:"rounded border-gray-300"}),t.jsx(c.Label,{htmlFor:"useDynamicSlug",className:"text-sm",children:"Use Dynamic Slug"})]}),oe&&t.jsx("div",{className:"space-y-2",children:t.jsx("div",{className:"space-y-0.5",children:t.jsx(Li,{value:U,onChange:C,dynamicPattern:(q==null?void 0:q.dynamicSlug)||"{{id}}",placeholder:"Enter custom slug part (optional)",onValidationChange:O})})})]}),(!(q!=null&&q.dynamicSegments)||!oe)&&t.jsxs("div",{className:"space-y-0.5",children:[t.jsx(c.Label,{htmlFor:"slug",className:"text-sm",children:"Slug"}),t.jsx(yn,{value:x,onChange:A=>{var de;P(A),i&&A!==(((de=e==null?void 0:e.slug)==null?void 0:de.split("/").pop())||"")?J(!!(_e||G)):J(!1)},placeholder:K&&K!=="none"?"Enter page slug":p==="page"?"Leave empty for home page":"Required - e.g. your-slug",parentSlug:K&&K!=="none"?(ms=l==null?void 0:l.find(A=>A.id===K))==null?void 0:ms.slug:void 0,onValidationChange:v}),m&&t.jsx("p",{className:"text-xs text-red-500",children:m}),z&&t.jsx("div",{className:"mt-4 rounded-md border border-amber-200 bg-amber-50 p-3",children:t.jsxs("div",{className:"flex items-start space-x-2",children:[t.jsx("div",{className:"flex-shrink-0",children:t.jsx("svg",{className:"h-5 w-5 text-amber-400",viewBox:"0 0 20 20",fill:"currentColor",children:t.jsx("path",{fillRule:"evenodd",d:"M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z",clipRule:"evenodd"})})}),t.jsxs("div",{className:"flex-1",children:[t.jsx("h3",{className:"text-sm font-medium text-amber-800",children:"Slug Change Warning"}),t.jsx("div",{className:"mt-1 text-sm text-amber-700",children:t.jsx("p",{children:"The previous URL and any child pages will become inaccessible. You may want to set up a redirect to avoid broken links."})})]})]})})]}),t.jsx(c.Button,{disabled:xe||!y&&(!(q!=null&&q.dynamicSegments)||!oe)||oe&&!B,type:"submit",className:"w-full",children:i?xe?"Updating...":"Update page":xe?"Creating...":"Create Page"})]}):t.jsxs("form",{onSubmit:Ot,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"}),ie?t.jsxs(c.Popover,{open:Q,onOpenChange:R,children:[t.jsx(c.PopoverTrigger,{asChild:!0,children:t.jsxs(c.Button,{variant:"outline",role:"combobox",disabled:i&&!E,className:it("w-full justify-between",i&&!E?"cursor-not-allowed text-gray-500":""),children:[(q==null?void 0:q.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:_,onChange:A=>M(A.target.value)})]})}),t.jsxs(ws,{className:"max-h-[200px] overflow-y-auto",children:[t.jsx(c.CommandEmpty,{children:"No page type found."}),t.jsx(c.CommandGroup,{heading:"Partials",children:Ze.map(A=>t.jsxs(c.CommandItem,{value:A.key,onSelect:()=>{be(A.key),R(!1)},className:"flex cursor-pointer items-center justify-between",children:[A.name,t.jsx(N.Check,{className:it("mr-2 h-4 w-4",p===A.key?"opacity-100":"opacity-0")})]},A.key))})]})]})})]}):t.jsx("select",{id:"pageType",value:p,disabled:i&&!E,onChange:A=>be(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))})}),L&&t.jsxs("div",{className:"mt-2 rounded-md border border-yellow-200 bg-yellow-50 p-3",children:[t.jsx("p",{className:"text-sm text-yellow-800",children:"Changing the page type may impact the page data. Are you sure you want to proceed?"}),t.jsxs("div",{className:"mt-2 flex gap-2",children:[t.jsx(c.Button,{variant:"outline",size:"sm",onClick:()=>I(!1),children:"Cancel"}),t.jsx(c.Button,{variant:"default",size:"sm",onClick:Be,children:"Confirm"})]})]}),t.jsx("p",{className:"text-xs text-gray-500",children:(hs=s.find(A=>A.key===p))==null?void 0:hs.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:ue,onChange:A=>he(A.target.value),required:!0,"aria-required":"true"})]}),t.jsx(c.Button,{disabled:xe,type:"submit",className:"w-full",children:i?xe?"Updating...":"Update "+(q==null?void 0:q.name):xe?"Creating...":"Create "+(q==null?void 0:q.name)})]})}const vn=({addEditPage:e,setAddEditPage:s,closePanel:n})=>{const{data:a}=Ae(),r=!!(e!=null&&e.id);return console.log(e),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(Ui,{closePanel:n,addEditPage:e,close:()=>s(void 0),additionalPageTypes:a??[]})]})})};function Bs({page:e,onClose:s}){const[,n]=Pe(),{mutate:a,isPending:r}=pi(),{data:i}=Ae(),{setSelectedLang:l,fallbackLang:o}=$.useLanguages(),[,u]=$.useSidebarActivePanel(),d=()=>{r||a(e,{onSuccess:()=>{e!=null&&e.primaryPage?(window.history.replaceState({},"",`/?page=${e.primaryPage}`),n(new URLSearchParams({page:e.primaryPage}))):(window.history.replaceState({},"","/"),n(new URLSearchParams)),window.dispatchEvent(new PopStateEvent("popstate")),l(o),u("outline"),s()}})},h=i==null?void 0:i.find(m=>m.key===(e==null?void 0:e.pageType));return t.jsx(c.Dialog,{open:!!e,onOpenChange:s,children:t.jsxs(c.DialogContent,{children:[t.jsxs(c.DialogHeader,{children:[t.jsx(c.DialogTitle,{children:"Confirm Deletion"}),t.jsxs(c.DialogDescription,{className:"py-4 text-slate-500",children:[t.jsxs("div",{children:["Are you sure you want to remove ",t.jsx("b",{children:(e==null?void 0:e.name)??(e==null?void 0:e.slug)})," ",h!=null&&h.hasSlug?(h==null?void 0:h.name)+"?":`page? ${e!=null&&e.primaryPage?"":"This will also delete all associated language pages."}`]}),e.lang&&t.jsxs("div",{className:"py-2 text-sm",children:["Language:"," ",t.jsx("span",{className:"font-medium text-gray-500",children:f.get(Ee,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 Fi=()=>{const e=le(),s=F.useQueryClient(),n=X();return F.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:[D.GET_WEBSITE_PAGES]}),W.toast.success("Page duplicated successfully")},onError:a=>{W.toast.error("Failed to duplicate page",{description:a.message||"An error occurred while duplicating the page"})}})},bn=({page:e,onClose:s})=>{const{mutate:n,isPending:a}=Fi(),[r,i]=g.useState(null),[l,o]=g.useState(`${e.name} (Copy)`),u=f.isEmpty(e.slug),[d,h]=g.useState(u?"":`${e.slug.split("/").pop()}-copy`),m=u?"":f.initial(e.slug.split("/")).join("/"),[j,y]=g.useState(!1),v=p=>{if(p.preventDefault(),!l.trim()){i("Name is required");return}if(!u&&!d.trim()){i("Slug is required");return}i(null),y(!0);const b={pageId:e.id,name:l};u||(b.slug=`${m}/${d}`),n(b,{onSuccess:()=>{y(!1),s()},onError:S=>{y(!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:v,className:"space-y-4",children:[t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Label,{htmlFor:"name",className:"text-sm",children:"Name"}),t.jsx(c.Input,{id:"name",value:l,onChange:p=>o(p.target.value),required:!0})]}),!u&&t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Label,{htmlFor:"slug",className:"text-sm",children:"Slug"}),t.jsx(yn,{value:d,onChange:p=>h(p),parentSlug:m,onValidationChange:p=>{i(p?null:"Invalid slug")}})]}),r&&t.jsxs(c.Alert,{variant:"destructive",className:"py-2",children:[t.jsx(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||j,children:a||j?"Duplicating...":"Duplicate"})]})]})]})})},qi=1*1024*1024,wn=({page:e,onClose:s})=>{const[n,a]=g.useState(!1),[r,i]=g.useState(""),[l,o]=g.useState(""),[u,d]=g.useState(!1),h=g.useRef(null),m=ji(),{data:j}=Ae(),y=j==null?void 0:j.find(L=>L.key===e.pageType),v=(y==null?void 0:y.name)||f.startCase(e.pageType),p=g.useCallback(L=>{var k;const I=(k=L.target.files)==null?void 0:k[0];if(I){if(I.size>qi){W.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 T=new FileReader;T.onloadend=()=>{o(T.result),d(!1)},T.readAsDataURL(I)}catch(T){console.error("Error reading file:",T),d(!1),W.toast.error("Failed to process image",{description:T instanceof Error?T.message:"Unknown error"})}}},[]),b=()=>{o(""),h.current&&(h.current.value="")},S=()=>{var L;(L=h.current)==null||L.click()},E=()=>{a(!0),m.mutate({page:e,name:e.name,description:r.trim()||void 0,pageType:e.pageType,...l?{previewImage:l}:{}},{onSuccess:()=>{a(!1),s()},onError:()=>{a(!1)}})};return t.jsx(c.Dialog,{open:!0,onOpenChange:s,children:t.jsxs(c.DialogContent,{children:[t.jsxs(c.DialogHeader,{children:[t.jsx(c.DialogTitle,{children:"Mark as template"}),t.jsxs(c.DialogDescription,{className:"py-4 text-slate-500 space-y-1 text-xs",children:["Are you sure you want to mark this page as a template?",t.jsx("br",{}),"Templates can be used to create new pages with the same content."]})]}),t.jsxs("div",{className:"space-y-4 mb-4 text-xs",children:[t.jsxs("div",{className:"p-4 border rounded bg-slate-50 space-y-3",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(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:f.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:v})]})]}),t.jsxs("div",{children:[t.jsx(c.Label,{htmlFor:"description",className:"text-xs font-medium",children:"Description (Optional)"}),t.jsx(c.Textarea,{id:"description",placeholder:"Describe this template's purpose",className:"text-xs resize-none h-24 mt-1",value:r,onChange:L=>i(L.target.value)})]}),t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Label,{htmlFor:"previewImage",className:"text-xs font-medium",children:"Preview Image (Optional)"}),t.jsxs("div",{className:"space-y-2",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(c.Input,{type:"file",id:"previewImage",ref:h,onChange:p,accept:"image/*",className:"hidden"}),t.jsx(c.Button,{type:"button",variant:"outline",onClick:S,disabled:u,className:"w-full",children:u?t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsx("div",{className:"animate-spin h-4 w-4 border-2 border-current border-t-transparent rounded-full"}),"Uploading..."]}):t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsx(N.ImageIcon,{className:"h-4 w-4"}),"Select image"]})}),l&&t.jsx(c.Button,{type:"button",variant:"outline",size:"icon",onClick:b,children:t.jsx(N.X,{className:"h-4 w-4"})})]}),l&&t.jsx("div",{className:"rounded-md overflow-hidden border aspect-video",children:t.jsx("img",{src:l,alt:"Preview",className:"w-full h-full max-h-[200px] object-contain"})}),t.jsx("p",{className:"text-xs text-muted-foreground",children:"max 1mb"})]})]})]}),t.jsxs(c.DialogFooter,{className:n?"opacity-75 pointer-events-none":"",children:[t.jsx(c.Button,{variant:"outline",onClick:L=>{L.stopPropagation(),s()},children:"Cancel"}),t.jsx(c.Button,{variant:"default",disabled:n,onClick:E,children:"Mark as template"})]})]})})},Sn=({page:e,setDuplicatePage:s,setAddEditPage:n,setUnpublishPage:a,setDeletePage:r,setMarkAsTemplate:i,setUnmarkAsTemplate:l,children:o,isLanguagePage:u})=>{const{hasPermission:d}=$.usePermissions(),{data:h}=Ae(),m=g.useMemo(()=>f.find(h,{key:e.pageType}),[h,e.pageType]),j=g.useMemo(()=>!!e.isTemplate,[e.isTemplate]),y=g.useMemo(()=>!!(m!=null&&m.hasSlug),[m==null?void 0:m.hasSlug]);return!d(we.EDIT_PAGE)&&!d(we.DELETE_PAGE)&&!d(we.UNPUBLISH_PAGE)||!e?null:t.jsxs(c.DropdownMenu,{children:[t.jsx(c.DropdownMenuTrigger,{asChild:!0,onClick:p=>p.stopPropagation(),children:o}),t.jsxs(c.DropdownMenuContent,{align:"center",className:"text-sm",children:[d(we.ADD_PAGE)&&!u&&t.jsxs(c.DropdownMenuItem,{className:"flex cursor-pointer items-center gap-2",onClick:p=>{p.stopPropagation(),s(e)},children:[t.jsx(N.CopyPlusIcon,{className:"size-3"}),"Duplicate page"]}),d(we.EDIT_PAGE)&&t.jsxs(c.DropdownMenuItem,{className:"flex cursor-pointer items-center gap-2",onClick:p=>{p.stopPropagation(),n({...e,global:!(m!=null&&m.hasSlug)})},children:[t.jsx(N.Pencil,{className:"size-3"}),"Edit"]}),(e==null?void 0:e.online)&&d(we.UNPUBLISH_PAGE)&&t.jsxs(c.DropdownMenuItem,{className:"flex cursor-pointer items-center gap-2",onClick:p=>{p.stopPropagation(),a(e)},children:[t.jsx(N.Power,{className:"size-3"}),re.UNPUBLISH]}),d(we.DELETE_PAGE)&&t.jsxs(c.DropdownMenuItem,{className:"flex cursor-pointer items-center gap-2",onClick:p=>{p.stopPropagation(),r(e)},children:[t.jsx(N.Trash,{className:"size-3"}),re.DELETE]}),d(we.MARK_AS_TEMPLATE)&&y&&!u&&t.jsx(t.Fragment,{children:j?t.jsxs(c.DropdownMenuItem,{className:"flex cursor-pointer items-center gap-2",onClick:p=>{p.stopPropagation(),l(e)},children:[t.jsx(N.SquareLibrary,{className:"size-3"}),re.UNMARK_AS_TEMPLATE]}):t.jsxs(c.DropdownMenuItem,{className:"flex cursor-pointer items-center gap-2",onClick:p=>{p.stopPropagation(),i(e)},children:[t.jsx(N.SquareLibrary,{className:"size-3"}),re.MARK_AS_TEMPLATE]})})]})]})},Nn=({page:e,onClose:s})=>{const[n,a]=g.useState(!1),r=vi(),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"})]})]})})},cs=({page:e,onClose:s})=>{const{mutate:n,isPending:a}=yi(),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:[re.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?re.UPDATING:re.UNPUBLISH})]})]})})},$i=na("expandedPagesState",[]),En=e=>f.flatMap(e,s=>[s,...s.children?En(s.children):[]]),zi=(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)||[]},Sa=(e,s)=>{if(!s)return[];const n=En(e),a=f.find(n,r=>r.id===s);if(a){if(a.parent)return[...Sa(e,a.parent),s];const r=zi(e,s);if(!f.isEmpty(r))return r}return[s]},Vi=e=>{const s=new Set,n=(a,r=[])=>{a.forEach(i=>{const l=[...r,i.id];i.shouldExpandOnSearch&&l.forEach(o=>s.add(o)),i.children&&!f.isEmpty(i.children)&&n(i.children,l)})};return n(e),Array.from(s)},Rt=e=>{const[s,n]=je.useAtom($i),a=e?f.includes(s,e):!1,r=g.useCallback(()=>{n(d=>a?f.filter(d,h=>h!==e):[...d,e])},[n,a,e]),i=g.useCallback((d,h)=>{if(!h||f.isEmpty(d))return;const m=En(d),j=Sa(m,h);if(!Array.isArray(j)||f.isEmpty(j))return;const y=j.slice(0,-1);f.isEmpty(y)||n(v=>f.uniq([...v,...y]))},[n]),l=g.useCallback(d=>{if(f.isEmpty(d))return;const h=Vi(d);f.isEmpty(h)||n(m=>f.union(m,h))},[n]),o=g.useCallback(d=>{if(f.isEmpty(d))return;const h=f.flatMap(d,m=>{const j=y=>[y.id,...y.children?f.flatMap(y.children,j):[]];return j(m)});n(h)},[n]),u=g.useCallback(()=>{n([])},[n]);return{isExpanded:a,toggleExpanded:r,updateForSelectedPage:i,expandedPages:s,expandPagesOnSearch:l,setExpandedPages:n,expandAll:o,collapseAll:u}},Rn=(e,s)=>!e||!Array.isArray(e)?[]:f.isEmpty(s)?e:f.compact(f.filter(e,n=>{const a=f.toLower(s);return f.includes(f.toLower((n==null?void 0:n.name)||""),a)||f.includes(f.toLower((n==null?void 0:n.slug)||""),a)})),Ki=(e,s)=>{const n=new Set,a=f.keyBy(e,"id");return s.forEach(r=>{let i=r;for(;i.parent&&a[i.parent];)n.add(i.parent),i=a[i.parent]}),Array.from(n).map(r=>a[r])},Ys=(e,s,n)=>f.isEmpty(s)?e:e.map(a=>{if(!n(a.pageType))return{...a,shouldExpandOnSearch:!0,children:a.children?Ys(a.children,s,n):[]};const r=a.children&&a.children.some(i=>f.includes(f.toLower(i.name||""),f.toLower(s))||f.includes(f.toLower(i.slug||""),f.toLower(s)));return{...a,shouldExpandOnSearch:r,children:a.children?Ys(a.children,s,n):[]}}),Hi=e=>{if(!e||!e.length)return[];const s={};e.forEach(a=>{s[a.id]={...a,children:[]}});const n=[];return Object.values(s).forEach(a=>{a.parent&&s[a.parent]?s[a.parent].children.push(a):n.push(a)}),n},Na=e=>!e||!e.length?[]:[...e].sort((n,a)=>(n.name||"").localeCompare(a.name||"")).map(n=>({...n,children:n.children?Na(n.children):[]})),Ea=(e,s,n,a)=>{if(!e||!e.length)return[];let r=e;if(n!=="all"&&(r=f.compact(f.filter(e,{pageType:n}))),f.isEmpty(s))r=Rn(r,s);else{const h=Rn(r,s),m=Ki(e,h);r=f.uniqBy([...h,...m],"id")}const i=Na(Hi(r)),l=Ys(i,s,a),o=f.filter(l,h=>a(h.pageType)).sort((h,m)=>(h.name||"").localeCompare(m.name||"")),u=f.filter(l,h=>!a(h.pageType));let d=[];if(n==="all"){const h=f.keyBy(u,"pageType");d=Object.values(f.mapValues(h,(m,j)=>({...m,id:j,name:f.startCase(j),isPartialGroup:!0,children:l.filter(y=>y.pageType===j)})))}else d=u.sort((h,m)=>(h.name||"").localeCompare(m.name||""));return[...o,...d]},Qi=({parentSlug:e,page:s,active:n,closePanel:a,setUnpublishPage:r,setDeletePage:i,setAddEditPage:l,setMarkAsTemplate:o,setUnmarkAsTemplate:u,setDuplicatePage:d,hasChildren:h,isExpanded:m,onToggleExpand:j})=>{const y=jn(),{data:v}=Ae(),[,p]=$.useSidebarActivePanel(),b=g.useMemo(()=>f.find(v,{key:s.pageType}),[v,s.pageType]),S=g.useMemo(()=>{const k=f.get(s,"slug",""),T=e?at(e):"",V=T?k.replace(T,""):k;return V||"/"},[s,e]),E=g.useMemo(()=>!!s.isTemplate,[s.isTemplate]),L=g.useCallback(()=>{p("outline"),y(f.get(s,"id"),a)},[y,a,s,p]),I=g.useCallback(k=>{k.stopPropagation(),j()},[j]);return t.jsxs("div",{onClick:s.isPartialGroup?I:L,className:`flex cursor-pointer items-center justify-between rounded p-1.5 px-3 py-1.5 leading-none ${n?"bg-gray-200":"hover:bg-gray-100"}`,children:[t.jsxs("div",{className:"flex items-center gap-x-2",children:[t.jsx("button",{onClick: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 ${m?"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"})}):b!=null&&b.icon?t.jsx("div",{className:"h-4 w-4 stroke-[1] text-slate-500",dangerouslySetInnerHTML:{__html:b.icon}}):b!=null&&b.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}),b!=null&&b.hasSlug?t.jsxs(c.Badge,{variant:"outline",className:`ml-2 max-w-full rounded-full border py-px text-xs font-normal leading-tight text-gray-400 ${n?"border-gray-300":"border-gray-200"}`,children:[S,s.dynamic&&t.jsxs("span",{className:"text-xs font-light leading-none text-slate-500",children:[f.endsWith(S,"/")?`${b==null?void 0:b.dynamicSlug}`:`/${b==null?void 0:b.dynamicSlug}`,s.dynamicSlugCustom]})]}):s.isPartialGroup?null:t.jsx(c.Badge,{variant:"outline",className:`ml-2 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:b==null?void 0:b.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(ei,{currentEditor:s.currentEditor}),t.jsx(Sn,{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:k=>k.stopPropagation()})})})]})]})},Wi=({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=C=>l?String(f.get(C,"name","")).toLowerCase().includes(l.toLowerCase())||String(f.get(C,"key","")).toLowerCase().includes(l.toLowerCase()):!0,[m,j]=g.useState(null),[y,v]=g.useState(null),[p,b]=g.useState(null),[S,E]=g.useState(null),{data:L,isFetching:I}=ht(),[k,T]=g.useState(""),{hasPermission:V}=$.usePermissions(),{updateForSelectedPage:ne,expandPagesOnSearch:Y,expandAll:_,collapseAll:M}=Rt(null),[Q,R]=Pe(),Z=Q.get("page"),K=g.useRef(null),{data:te}=Ae(),ue=$.useChaiFeatureFlag("enable-add-page-dropdown"),he=g.useCallback(C=>{var B;return(B=f.find(te,{key:C}))==null?void 0:B.hasSlug},[te]);g.useEffect(()=>{if(!f.isEmpty(k))return;const C=sessionStorage.getItem("pageTypeFilter")||"all";!f.isEmpty(te)&&C&&(f.find(te,{key:C})?T(C):T("all"))},[te,k]);const oe=C=>{T(C),sessionStorage.setItem("pageTypeFilter",C),o("")},w=g.useCallback(C=>{const O=new URLSearchParams(window.location.search).get("lang"),z=new URLSearchParams({page:C});O&&z.set("lang",O),window.history.pushState({},"",`?${z.toString()}`),R(z),window.dispatchEvent(new PopStateEvent("popstate")),e()},[R,e]);g.useEffect(()=>{if(Z&&!I){const C=f.find(L,{id:Z});C&&(C!=null&&C.pageType)?s(B=>[...B,C==null?void 0:C.pageType]):(window.history.replaceState(null,"","/"),R(new URLSearchParams({})),window.dispatchEvent(new PopStateEvent("popstate")))}},[L,Z,I,R]);const x=g.useMemo(()=>L?Ea(L,r,k,he):[],[L,r,k,he]);g.useEffect(()=>{Z&&!I&&!f.isEmpty(x)&&(ne(x,Z),K.current&&K.current.scrollIntoView({behavior:"smooth",block:"end"}))},[Z,I,x,ne]),g.useEffect(()=>{!f.isEmpty(r)&&!f.isEmpty(x)&&Y(x)},[r,x,Y]);const P=g.useCallback(()=>{_(x)},[_,x]),U=g.useCallback(()=>{M()},[M]);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:C=>i(C.target.value)}),!f.isEmpty(k)&&t.jsxs(c.Select,{value:k,onValueChange:oe,children:[t.jsx(c.SelectTrigger,{className:`${k==="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:[ue&&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:C=>o(C.target.value),onKeyDown:C=>C.stopPropagation()})]})}),t.jsx(c.SelectItem,{value:"all",children:"All"},"all"),!f.isEmpty(f.filter(te,C=>C.hasSlug&&h(C)))&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"mt-2 border-t px-2 py-1.5 pt-2 text-xs font-semibold text-gray-500",children:"Pages"}),f.map([...f.filter(te,C=>C.hasSlug&&h(C))].sort((C,B)=>f.get(C,"name","").localeCompare(f.get(B,"name",""))),C=>t.jsx(c.SelectItem,{value:f.get(C,"key"),children:f.get(C,"name")},f.get(C,"key")))]}),!f.isEmpty(f.filter(te,C=>!C.hasSlug&&h(C)))&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"mt-2 border-t px-2 py-1.5 pt-2 text-xs font-semibold text-gray-500",children:"Partials"}),f.map([...f.filter(te,C=>!C.hasSlug&&h(C))].sort((C,B)=>f.get(C,"name","").localeCompare(f.get(B,"name",""))),C=>t.jsx(c.SelectItem,{value:f.get(C,"key"),children:f.get(C,"name")},f.get(C,"key")))]}),f.isEmpty(f.filter(te,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:P,className:"p-1 text-gray-500",children:t.jsx(N.ChevronsUpDown,{})}),t.jsx(c.Button,{variant:"outline",size:"icon",onClick:U,className:"p-1 text-gray-500",children:t.jsx(N.ChevronsDownUp,{})})]})]}),I?t.jsx("div",{className:"space-y-2",children:f.map([...Array(5).keys()],C=>t.jsx("div",{className:"h-9 w-full animate-pulse rounded bg-gray-200"},C))}):f.isEmpty(x)?t.jsxs("div",{className:"flex h-[70vh] flex-col items-center justify-center gap-y-1 text-sm font-medium text-slate-500",children:[t.jsx(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:f.map(x,C=>{const B=C.id===Z;return t.jsx("div",{ref:B?K:null,children:t.jsx(Ca,{item:C,currentPage:Z,close:e,setUnpublishPage:j,setDeletePage:d,setAddEditPage:v,setMarkAsTemplate:b,setUnmarkAsTemplate:E,setDuplicatePage:a,level:0})},`page-item-${C.id}`)})})]}),V(we.ADD_PAGE)&&t.jsxs(c.Button,{className:"flex gap-x-2 text-sm",onClick:()=>{v({slug:"",name:"",pageType:k==="all"?"page":k})},children:[t.jsx(N.Plus,{className:"h-4 w-4"})," Add New"]}),y&&t.jsx(vn,{closePanel:e,editPage:w,addEditPage:y,setAddEditPage:v}),u&&t.jsx(Bs,{page:u,onClose:()=>d(null)}),m&&t.jsx(cs,{page:m,onClose:()=>j(null)}),p&&t.jsx(wn,{page:p,onClose:()=>b(null)}),S&&t.jsx(Nn,{page:S,onClose:()=>E(null)}),n&&t.jsx(bn,{page:n,onClose:()=>a(null)})]})},Ca=({item:e,currentPage:s,close:n,setUnpublishPage:a,setDeletePage:r,setAddEditPage:i,setMarkAsTemplate:l,setUnmarkAsTemplate:o,setDuplicatePage:u,parentSlug:d,level:h=0})=>{const m=!f.isEmpty(e==null?void 0:e.children),{isExpanded:j,toggleExpanded:y}=Rt(e==null?void 0:e.id);return t.jsxs("div",{className:"border-0",children:[t.jsx(Qi,{closePanel:n,setUnpublishPage:a,setDeletePage:r,setAddEditPage:i,setMarkAsTemplate:l,setUnmarkAsTemplate:o,setDuplicatePage:u,active:s===e.id,page:e,parentSlug:d,hasChildren:m,isExpanded:j,onToggleExpand:y}),m&&j&&t.jsx("div",{className:"bg-white pl-6 pt-2",children:f.map(f.get(e,"children",[]),v=>t.jsx(Ca,{item:v,currentPage:s,close:n,setUnpublishPage:a,setDeletePage:r,setAddEditPage:i,setMarkAsTemplate:l,setUnmarkAsTemplate:o,setDuplicatePage:u,parentSlug:e.slug,level:h+1},v.id||`child-${h}-${v.key}`))})]},e.id||`level-${h}-${e.key}`)},Yi=({selectedPageType:e,setSelectedPageType:s})=>{const[n,a]=g.useState(""),{data:r}=Ae(),i=o=>{if(!n)return!0;const u=n.toLowerCase(),d=h=>String(f.get(o,h,"")).toLowerCase().includes(u);return d("name")||d("key")},l=r.find(o=>o.key===e);return t.jsxs(c.Select,{onValueChange:s,value:e,children:[t.jsx(c.SelectTrigger,{className:`${e==="all"?"bg-gray-100/30 hover:bg-gray-100":"gap-x-1 border bg-gray-100/30 hover:bg-gray-100"} h-9 w-max min-w-[150px] overflow-hidden whitespace-nowrap rounded p-0 px-2 py-1 text-xs text-gray-600 shadow-none ring-0 focus:ring-0 [&>svg]:hidden`,children:t.jsxs("div",{className:"flex w-full items-center justify-between gap-x-1.5",children:[t.jsx("span",{className:"max-w-[150px] overflow-hidden truncate whitespace-nowrap font-medium leading-tight",children:(l==null?void 0:l.name)||"All"}),t.jsx(N.ListFilter,{className:`${e!=="all"?"fill-sky-50 text-sky-500":""} pointer-events-none h-4 w-4 text-muted-foreground hover:bg-blue-300`})]})}),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:o=>a(o.target.value),onKeyDown:o=>o.stopPropagation()})]})}),t.jsx(c.SelectItem,{value:"all",children:"All"}),!f.isEmpty(f.filter(r,o=>o.hasSlug&&i(o)))&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"mt-2 border-t px-2 py-1.5 pt-2 text-xs font-semibold text-gray-500",children:"Pages"}),f.map([...f.filter(r,o=>o.hasSlug&&i(o))].sort((o,u)=>f.get(o,"name","").localeCompare(f.get(u,"name",""))),o=>t.jsx(c.SelectItem,{value:f.get(o,"key"),children:f.get(o,"name")},f.get(o,"key")))]}),!f.isEmpty(f.filter(r,o=>!o.hasSlug&&i(o)))&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"mt-2 border-t px-2 py-1.5 pt-2 text-xs font-semibold text-gray-500",children:"Partials"}),f.map([...f.filter(r,o=>!o.hasSlug&&i(o))].sort((o,u)=>f.get(o,"name","").localeCompare(f.get(u,"name",""))),o=>t.jsx(c.SelectItem,{value:f.get(o,"key"),children:f.get(o,"name")},f.get(o,"key")))]}),f.isEmpty(f.filter(r,i))&&t.jsx("div",{className:"px-3 py-2 text-center text-sm text-gray-500",children:"No matching page types found"})]})]})},Ji=({search:e,setSearch:s})=>t.jsxs("div",{className:"relative flex h-9 flex-1 items-center gap-2 rounded-md border px-2.5",children:[t.jsx("label",{htmlFor:"page-search-input",className:"sr-only",children:"Search Pages"}),t.jsx(N.Search,{className:`${e?"fill-sky-50 text-sky-500":""} 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:n=>s(n.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"})]}),Xi=({pages:e})=>{const{expandAll:s,collapseAll:n,expandedPages:a}=Rt(null);return t.jsxs("div",{className:"flex gap-1",children:[t.jsxs(c.Tooltip,{children:[t.jsx(c.TooltipTrigger,{asChild:!0,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,{asChild:!0,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"})]})]})},Aa=({languages:e,selectedLanguage:s,setSelectedLanguage:n})=>{const a=Qe();return t.jsx("div",{className:"scrollbar-hide flex gap-1 overflow-x-auto pb-1",children:e.map(r=>t.jsxs(c.Button,{variant:s===r?"default":"outline",size:"sm",className:`h-6 flex-shrink-0 whitespace-nowrap rounded px-3 text-xs font-normal ${s===r?"bg-black text-white hover:bg-black":"text-gray-500"}`,onClick:()=>n(r.toLowerCase()),children:[r===a&&t.jsx(N.Star,{size:4,className:`p-0.5 ${s===a?"fill-white":"fill-black"}`}),Ee[r]||""]},r))})},Mn=()=>{const e=F.useQueryClient();return t.jsxs(c.Tooltip,{children:[t.jsx(c.TooltipTrigger,{asChild:!0,children:t.jsx(c.Button,{size:"sm",variant:"ghost",onClick:()=>e.invalidateQueries({queryKey:[D.GET_WEBSITE_PAGES]}),className:"mt-1 h-6 w-6",children:t.jsx(N.RefreshCw,{})})}),t.jsx(c.TooltipContent,{side:"bottom",children:"Refresh pages list"})]})},Zi=({pages:e,search:s,setSearch:n,languages:a,onAddPage:r,selectedLanguage:i,setSelectedLanguage:l,selectedPageType:o,setSelectedPageType:u,showUntranslatedPages:d,setShowUntranslatedPages:h})=>{const m=a.length>1;return t.jsxs("div",{className:"space-y-3 border-b border-b-gray-200 px-4 pb-1",children:[t.jsxs("div",{className:"flex items-center gap-x-2",children:[t.jsx(Yi,{selectedPageType:o,setSelectedPageType:u}),t.jsx(Ji,{search:s,setSearch:n}),t.jsx(Xi,{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"})]}),!m&&t.jsx(Mn,{})]}),m?t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx(Aa,{languages:a,selectedLanguage:i,setSelectedLanguage:j=>{l(j),h(d&&(a==null?void 0:a[0])!==i)}}),t.jsxs("div",{className:"flex items-center gap-x-2",children:[(a==null?void 0:a[0])!==i&&t.jsxs(c.Tooltip,{children:[t.jsx(c.TooltipTrigger,{asChild:!0,children:t.jsx(c.Button,{variant:"ghost",onClick:()=>h(!d),className:"h-6 rounded px-3 py-1 text-xs font-normal",children:d?t.jsx(N.FilterXIcon,{}):t.jsx(N.Filter,{})})}),t.jsx(c.TooltipContent,{side:"bottom",children:"Toggle Untranslated Pages"})]}),t.jsx(Mn,{})]})]}):t.jsx("div",{className:"flex items-center justify-between gap-2"})]})};function dt({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 el=({page:e})=>{var a,r;const{isExpanded:s,toggleExpanded:n}=Rt(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":""}`})})},tl=({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"})}),sl=({isOnline:e})=>t.jsx("div",{className:`h-2 w-2 rounded-full ${e?"bg-green-300":"bg-gray-300"}`}),nl=({page:e,pageTypes:s,currentPage:n,onClickAction:a,languagePages:r,selectedLanguage:i,showUntranslatedPages:l})=>{const[o]=ga(),u=Qe(),d=n===e.id,h=!!e.isTemplate,m=g.useMemo(()=>f.find(s,{key:e.pageType}),[s,e.pageType]),j=o==null?void 0:o[e.id],{data:y}=Ye(j),v=y?y==null?void 0:y.name:null;let p=f.get(r,e==null?void 0:e.id);p=f.get(p,"lang")===i?p:null;const b=i===u||!!p,S=(p==null?void 0:p.name)||(e==null?void 0:e.name)||"No name";let E=(p==null?void 0:p.slug)||(e==null?void 0:e.slug)||"";const L=E+(e!=null&&e.dynamic?`/${m.dynamicSlug}`:"")+(e!=null&&e.dynamicSlugCustom?`${e.dynamicSlugCustom}`:"");if(E.startsWith("/")&&!l){const k=E.split("/").pop();E=E.endsWith(k)&&e.dynamic?"":`/${k}`}const I=g.useMemo(()=>{const k="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]",T=`${d?"border-primary/30 bg-primary/5":"border-transparent hover:border-gray-200 hover:bg-gray-100"}`;return b?`${k} ${T} ${v?"opacity-60":""}`:`${k} bg-gray-100 opacity-50 group-hover:border-gray-200 border-transparent group-hover:bg-blue-100`},[b,d,v]);return t.jsxs("div",{className:"group relative",children:[t.jsxs("div",{onClick:()=>!e.isPartialGroup&&b&&a("select",e==null?void 0:e.id),className:I,children:[t.jsx(el,{page:e}),!e.isPartialGroup&&t.jsx(sl,{isOnline:p?p.online:e.online}),t.jsx(tl,{page:e,pageType:m}),t.jsx(dt,{content:S,side:"top",showTooltip:S.length>35,children:t.jsx("span",{className:"max-w-[40%] truncate font-medium text-black",children:S})}),(E||e.dynamic)&&t.jsx(dt,{content:L,side:"top",showTooltip:!0,children:t.jsxs("span",{className:"max-w-[40%] truncate font-mono text-xs text-muted-foreground",children:[E,e.dynamic&&(m==null?void 0:m.dynamicSlug)&&t.jsxs("span",{className:"text-xs text-gray-500",children:["/",m.dynamicSlug,e.dynamicSlugCustom]})]})}),h&&t.jsx(dt,{content:"Template",side:"top",children:t.jsx("span",{className:"text-blue-500",children:t.jsx(N.NotepadText,{size:16})})}),!e.isPartialGroup&&b&&!v?t.jsx("div",{className:"duration absolute right-0.5 top-[3px]",children:t.jsx(Sn,{isLanguagePage:!!p,page:p||e,setDuplicatePage:k=>a("duplicate",k),setAddEditPage:k=>a("edit",p||k),setUnpublishPage:k=>a("unpublish",k),setDeletePage:k=>a("delete",p||k),setMarkAsTemplate:k=>a("markAsTemplate",k),setUnmarkAsTemplate:k=>a("unmarkAsTemplate",k),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:k=>k.stopPropagation()})})})}):v?t.jsx("span",{className:"duration absolute right-1.5 top-1/2 -translate-y-1/2 text-xs text-gray-500",children:t.jsx(N.Lock,{className:"h-3.5 w-3.5 fill-red-200 text-red-500"})}):null]}),t.jsx(t.Fragment,{children:v&&t.jsxs("button",{className:"absolute right-0 top-0 flex h-full items-center gap-x-1 rounded bg-red-50 px-2 py-0.5 text-xs font-light text-red-500 opacity-0 group-hover:opacity-100",children:[t.jsx(N.Edit,{size:12,className:"stroke-[3]"})," ",t.jsx("span",{className:"font-medium",children:v})," is editing this page"]})}),t.jsx(t.Fragment,{children:!b&&!e.isPartialGroup&&!v&&t.jsxs("button",{onClick:k=>{k.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 ",f.get(Ee,i)," Page"]})]})})]})},Ta=({pages:e,tier:s,pageTypes:n,currentPage:a,onClickAction:r,languagePages:i,selectedLanguage:l,showUntranslatedPages:o})=>{const{expandedPages:u}=Rt();return t.jsx("div",{className:"space-y-0.5",style:{paddingLeft:`${s*10}px`},children:e.map(d=>t.jsxs(t.Fragment,{children:[t.jsx(nl,{page:d,pageTypes:n,currentPage:a,onClickAction:r,languagePages:i,selectedLanguage:l,showUntranslatedPages:o}),d.children&&d.children.length>0&&(u==null?void 0:u.includes(d.id))&&t.jsx(Ta,{pages:d.children,tier:s+1,pageTypes:n,currentPage:a,onClickAction:r,languagePages:i,selectedLanguage:l,showUntranslatedPages:o})]},d.id))})},al=({close:e})=>{const{languages:s,setSelectedLang:n,selectedLang:a}=$.useLanguages(),{data:r}=Ae(),{data:i,isFetching:l}=ht(),[o,u]=Pe(),{updateForSelectedPage:d,expandPagesOnSearch:h}=Rt(null),m=Qe(),j=o.get("page"),[y,v]=g.useState(""),[p,b]=g.useState(null),[S,E]=g.useState(null),[L,I]=g.useState(null),[k,T]=g.useState(null),[V,ne]=g.useState(""),[Y,_]=g.useState(null),[M,Q]=g.useState(null),[R,Z]=g.useState(a||m),[K,te]=g.useState(!1),[,ue]=je.useAtom(os),he=K&&R!==m,{data:oe,isFetching:w}=Kr(R),x=g.useCallback(B=>{var O;return(O=f.find(r,{key:B}))==null?void 0:O.hasSlug},[r]),P=g.useMemo(()=>i?he?f.filter(i,B=>!(oe!=null&&oe[B.id])):Ea(i,y,V,x):[],[i,x,y,V,oe,he]);g.useEffect(()=>{if(!f.isEmpty(V))return;const B=sessionStorage.getItem("pageTypeFilter")||"all";!f.isEmpty(r)&&B&&(f.find(r,{key:B})?ne(B):ne("all"))},[r,V]),g.useEffect(()=>{j&&!l&&(f.find(i,{id:j})||(window.history.replaceState(null,"","/"),u(new URLSearchParams({})),window.dispatchEvent(new PopStateEvent("popstate"))))},[i,j,l,u]),g.useEffect(()=>{j&&!l&&!f.isEmpty(P)&&d(P,j)},[j,l,P,d]),g.useEffect(()=>{!f.isEmpty(y)&&!f.isEmpty(P)&&h(P)},[y,P,h]);const U=g.useCallback(B=>{const O=new URLSearchParams({page:B});R!==m&&O.set("lang",R),n(R),window.history.pushState({},"",`?${O.toString()}`),u(O),window.dispatchEvent(new PopStateEvent("popstate")),e()},[e,u,R,n,m]),C=(B,O)=>{var z;if(O)switch(B){case"add":E(O);break;case"select":U(O);break;case"edit":R!==m?ue({edit:!0,id:O==null?void 0:O.id,primaryPage:O==null?void 0:O.primaryPage}):E(O);break;case"delete":b(O);break;case"unpublish":I(O);break;case"markAsTemplate":T(O);break;case"unmarkAsTemplate":Q(O);break;case"duplicate":_(O);break;case"addLanguagePage":ue({edit:!1,primaryPage:((z=O==null?void 0:O.page)==null?void 0:z.id)||"",preselectedLang:(O==null?void 0:O.language)||R});break}};return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex h-full flex-col justify-between",children:[t.jsx(Zi,{pages:P,search:y,setSearch:v,languages:[m,...s],selectedLanguage:R,setSelectedLanguage:Z,selectedPageType:V,setSelectedPageType:ne,onAddPage:B=>C("add",B),showUntranslatedPages:he,setShowUntranslatedPages:te}),t.jsx("div",{className:"flex-1 overflow-y-auto px-4 pb-6 pt-2",children:l||w?t.jsx("div",{className:"space-y-2",children:f.map([...Array(15).keys()],B=>t.jsx("div",{className:"h-7 w-full animate-pulse rounded border border-gray-300 bg-gray-200"},B))}):f.isEmpty(P)?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(Ta,{tier:0,pages:P,pageTypes:r,currentPage:j||"",onClickAction:C,languagePages:oe,selectedLanguage:R,showUntranslatedPages:he})})]}),S&&t.jsx(vn,{closePanel:e,editPage:U,addEditPage:S,setAddEditPage:E}),p&&t.jsx(Bs,{page:p,onClose:()=>b(null)}),L&&t.jsx(cs,{page:L,onClose:()=>I(null)}),k&&t.jsx(wn,{page:k,onClose:()=>T(null)}),M&&t.jsx(Nn,{page:M,onClose:()=>Q(null)}),Y&&t.jsx(bn,{page:Y,onClose:()=>_(null)})]})},rl=()=>{const e=$e("logo",null);return e?t.jsx("div",{className:"max-h-9 w-full overflow-hidden pr-2",children:g.createElement(e,{})}):null},il=()=>{const[e]=Pe(),s=e.get("page"),{data:n,isFetching:a}=ke(),[r,i]=g.useState(!1),{savePage:l}=$.useSavePage(),o=!!s&&!f.isEmpty(n),u=!s||!a&&f.isEmpty(n)||r,d=$.useChaiFeatureFlag("enable-old-page-manager");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?"w-full !max-w-screen-md":"!min-w-[50vh] !max-w-[800px] p-0"} 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?t.jsx(Wi,{close:()=>i(!1)}):u&&t.jsx(al,{close:()=>i(!1)})})]})})]})},Cn=({showAdd:e=!0,variant:s="ghost"})=>{const{fallbackLang:n,languages:a,selectedLang:r,setSelectedLang:i}=$.useLanguages(),l=f.isEmpty(r)?n:r,[,o]=Pe(),{isLocked:u}=Je();g.useEffect(()=>{const b=new URLSearchParams(window.location.search),S=b.get("lang");S&&(a.includes(S)?i(S):(b.delete("lang"),o(b),i("")))},[a,o,i]);const[,d]=je.useAtom(os),{data:h}=ke(),{data:m}=Ke(),{data:j}=qe(),y=g.useMemo(()=>{const b=f.compact(f.map(f.get(m,"languages"),S=>{const E=f.find(j,{lang:S});return{key:S,value:f.get(Ee,S,S),isLangPageAdded:!!E}})).filter(Boolean);return[{key:n,value:f.get(Ee,n),isLangPageAdded:!0},...b]},[n,j,m]),v=b=>{if(document.querySelector('[data-panel-id="seo"]')){const E=new CustomEvent("seo-language-switch-check",{detail:{fromLang:l,toLang:b,switchHandler:()=>p(b)}});window.dispatchEvent(E);return}p(b)},p=b=>{i(b);const S=new URLSearchParams(window.location.search);b===n?S.delete("lang"):S.set("lang",b);const E=S.toString(),L=`${window.location.pathname}${E?`?${E}`:""}`;window.history.pushState({},"",L),o(S),window.dispatchEvent(new PopStateEvent("popstate"))};return f.isEmpty(a)?null:u?t.jsxs(c.Button,{variant:"ghost",size:"sm",className:"ml-px h-max cursor-not-allowed gap-2 py-1.5 opacity-50",children:[t.jsx(N.Languages,{className:"h-4 w-4"}),f.get(Ee,l,l),t.jsx(N.ChevronDown,{className:"h-4 w-4"})]}):t.jsx(t.Fragment,{children:t.jsxs(c.DropdownMenu,{children:[t.jsx(c.DropdownMenuTrigger,{asChild:!0,className:"focus:outline-none",children:t.jsxs(c.Button,{disabled:!!u,variant:s,size:"sm",className:"ml-px h-max gap-2 py-1.5",children:[t.jsx(N.Languages,{className:"h-4 w-4"}),f.get(Ee,l,l),t.jsx(N.ChevronDown,{className:"h-4 w-4"})]})}),t.jsxs(c.DropdownMenuContent,{className:"space-y-1 border-border",children:[f.map(y.filter(b=>b.isLangPageAdded),b=>t.jsxs(c.DropdownMenuItem,{className:$.mergeClasses("flex cursor-pointer items-center justify-between text-xs font-medium text-gray-800",b.key===l&&"!bg-gray-200 text-gray-700"),onClick:()=>v(b.key),children:[t.jsx("div",{className:"text-slate-600",children:b.value}),b.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"]})]},b.value)),e&&!f.isEmpty(y.filter(b=>!b.isLangPageAdded))&&t.jsxs(t.Fragment,{children:[t.jsx(c.Separator,{}),t.jsxs(c.Button,{size:"sm",variant:"ghost",onClick:()=>{h&&d({edit:!1,primaryPage:h.id})},className:"text-xs font-normal duration-200 hover:bg-slate-300 hover:text-slate-800",children:[t.jsx(N.Plus,{className:"mr-1 h-3 w-3"})," Add Langauge"]})]})]})]})})};function ll(){const[e,s]=je.useAtom(os);return t.jsxs("div",{className:"relative z-10 flex items-center justify-end gap-1",children:[t.jsx(rl,{}),t.jsx(il,{}),e&&t.jsx(_i,{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}=$.usePermissions();return e&&!r(e)||s&&!s.some(i=>r(i))?a:n};function ol(e){const s=le(),n=X();return F.useQuery({queryKey:["revisions",e],queryFn:async()=>await n(s,{action:D.GET_PAGE_REVISIONS,data:{pageId:e}}),enabled:!!e,gcTime:0,staleTime:0})}const cl=()=>{const e=le(),s=X(),n=F.useQueryClient();return F.useMutation({mutationFn:async a=>await s(e,{action:D.DELETE_PAGE_REVISION,data:{revisionId:a}}),onSuccess:()=>{n.invalidateQueries({queryKey:["revisions"]})}})},ul=()=>{const e=le(),s=X(),n=F.useQueryClient();return F.useMutation({mutationFn:async({revisionId:a,discardCurrent:r})=>await s(e,{action:D.RESTORE_PAGE_REVISION,data:{revisionId:a,discardCurrent:r}}),onSuccess:()=>{n.invalidateQueries({queryKey:["revisions"]})}})},ot=({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 dl({compare:e,setCompare:s,isComparisonEnabled:n}){const{data:a}=ke(),{saveState:r}=$.useSavePage(),[i]=Ds();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("div",{className:"flex items-center gap-1 text-sm font-medium leading-none",children:[t.jsx(ot,{tag:"draft"}),t.jsx("span",{className:"text-xs font-bold",children:"Currently editing"})]})}),t.jsx("div",{className:"flex items-center pl-2 text-[11px] text-muted-foreground",children:!f.isEmpty(i.lastSaved)&&t.jsxs("span",{children:["Last updated"," ",Bt.formatDistanceToNow(new Date(i.lastSaved),{addSuffix:!0})]})}),t.jsx("div",{className:"flex items-center gap-2 pt-0.5",children:u?t.jsx(ot,{tag:"unsaved"}):null})]}),n&&t.jsx(ka,{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 hl(){var R,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:m,isFetching:j,error:y,refetch:v}=ol(h==null?void 0:h.id),{mutate:p,isPending:b}=cl(),{mutate:S,isPending:E}=ul(),L=F.useQueryClient(),I=ma(),k=$.useChaiFeatureFlag("enable-page-revisions-compare"),{selectedLang:T,fallbackLang:V}=$.useLanguages(),ne=T||V;g.useEffect(()=>s([]),[h==null?void 0:h.id]);const Y=K=>{r&&S({revisionId:r.uid,discardCurrent:K},{onSuccess:()=>{o(!1),i(null),L.invalidateQueries({queryKey:[D.GET_DRAFT_PAGE]})}})},_=K=>{i(K),o(!0)},M=K=>{i(K),d(!0)},Q=()=>{r&&p(r.uid,{onSuccess:()=>{d(!1),i(null)}})};return g.useEffect(()=>{n&&v()},[n,v]),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 ",Bt.format(new Date(h.createdAt),"MMM d, yyyy 'at' h:mm a")]})]}),j?t.jsx(ml,{}):y?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:[k&&t.jsx(gl,{lang:ne,compare:e,setCompare:s}),t.jsx(dl,{compare:e,setCompare:s,isComparisonEnabled:k}),(R=m==null?void 0:m.filter(K=>K.uid==="current"))==null?void 0:R.map((K,te)=>t.jsx(On,{lang:ne,pageId:h==null?void 0:h.id,revision:K,isLatest:!0,onRestore:()=>_(K),onDelete:()=>M(K),revisionNumber:te,compare:e,setCompare:s,pageLiveFullSlug:I,isComparisonEnabled:k},K.uid)),t.jsx(c.ScrollArea,{className:"min-h-0 flex-1",children:t.jsx("div",{className:"space-y-2",children:(Z=m==null?void 0:m.filter(K=>K.uid!=="current"))==null?void 0:Z.map((K,te)=>t.jsx(On,{lang:ne,pageId:h==null?void 0:h.id,revision:K,isLatest:K.uid==="current",onRestore:()=>_(K),onDelete:()=>M(K),revisionNumber:te+1,compare:e,setCompare:s,pageLiveFullSlug:I,isComparisonEnabled:k},K.uid))})})]})]})]}),t.jsx(c.TooltipContent,{side:"bottom",children:t.jsx("p",{children:"Revision history"})})]})}),t.jsx(pl,{open:l,onOpenChange:o,revision:r,onRestore:Y,isRestoring:E}),t.jsx(yl,{open:u,onOpenChange:d,revision:r,onDelete:Q,isDeleting:b})]})}function ml(){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 On({revision:e,isLatest:s,onRestore:n,onDelete:a,revisionNumber:r,compare:i,setCompare:l,pageId:o,pageLiveFullSlug:u,isComparisonEnabled:d,lang:h}){const{data:m}=Ye(e.currentEditor),j=(m==null?void 0:m.name)||"Unknown",y=!!i.find(p=>{var b;return s?(b=p==null?void 0:p.uid)==null?void 0:b.startsWith("live"):(p==null?void 0:p.uid)===e.uid}),v=i.length>=2&&!y;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(ot,{tag:s?"live":`#${r}`}),e.type==="published"?"Published":"Draft"," by ",t.jsx("span",{className:"text-xs font-bold",children:j}),!d&&s&&t.jsx(ot,{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(ot,{tag:"published"}):t.jsx(ot,{tag:"draft"})}),t.jsx("div",{className:"flex items-center text-[10px] text-muted-foreground",children:t.jsx("span",{className:"leading-tight",children:Bt.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:[we.RESTORE_REVISION,we.DELETE_REVISION],children:t.jsx(xl,{revision:e,onRestore:n,onDelete:a})})]}),d&&t.jsx(ka,{checked:y,disabled:v,onChange:()=>{l(y?i.filter(p=>s?p.uid!==`live:${o}`:p.uid!==e.uid):[...i,{uid:s?`live:${o}`:e.uid,label:s?"live":`#${r}`}])}})]})}function fl(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 gl({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(ot,{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:"mt-0.5 h-5 gap-1 rounded px-1 pr-2 text-xs leading-none text-gray-500",variant:"outline",onClick:()=>s([]),children:[t.jsx(N.X,{className:"h-2.5 w-2.5"}),t.jsx("span",{className:"pt-px",children:" Clear"})]}),e.length===2?t.jsx("a",{target:"_blank",href:fl(e,n),children:t.jsxs(c.Button,{size:"sm",className:"h-5 gap-1 rounded px-2 text-xs leading-none",children:[t.jsx("span",{className:"pt-px",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-none",disabled:!0,children:[t.jsx("span",{className:"pt-px",children:"Compare"})," ",t.jsx(N.ExternalLink,{className:"ml-1 h-2.5 w-2.5"})]})]})]})}function ka({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 xl({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:we.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:we.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 pl({open:e,onOpenChange:s,revision:n,onRestore:a,isRestoring:r}){const{data:i}=Ye((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"," ",Bt.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 yl({open:e,onOpenChange:s,revision:n,onDelete:a,isDeleting:r}){const{data:i}=Ye((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"," ",Bt.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 jl=()=>{const e=le(),s=X();return F.useQuery({queryKey:[D.GET_CHANGES],queryFn:async()=>s(e,{action:D.GET_CHANGES})})},vl=({page:e,selectedPages:s,handleCheckboxChange:n,getPageType:a,hasSlug:r,currentOwnerId:i})=>{const{data:l}=Ye(i),o=l==null?void 0:l.name;return t.jsxs("tr",{className:"group relative 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 ${o?"opacity-50":""}`,children:[o?t.jsx(N.Lock,{className:"h-4 w-4 fill-red-200 text-red-500"}):t.jsx("input",{checked:f.includes(s,e==null?void 0:e.id),onClick:u=>{u.stopPropagation(),n(e==null?void 0:e.id)},type:"checkbox",className:"cursor-pointer rounded focus:outline-none focus:ring-0"})," ",r(e.pageType)?t.jsx(N.File,{className:"h-4 w-4"}):t.jsx(N.GlobeIcon,{className:"h-4 w-4"}),t.jsx(dt,{content:e.name,side:"top",showTooltip:e.name.length>25,children:t.jsx("span",{className:"max-w-[200px] truncate font-medium text-black",children:e.name})}),e.slug&&t.jsx(dt,{content:e.slug,side:"top",showTooltip:e.slug.length>25,children:t.jsx("span",{className:"max-w-[200px] truncate font-mono text-xs text-muted-foreground",children:e.slug})})]}),t.jsx("td",{className:"px-2",children:a(e==null?void 0:e.pageType)}),t.jsx("td",{className:"px-4 text-right",children:f.first(e.changes)||""}),t.jsx(t.Fragment,{children:o&&t.jsxs("button",{className:"absolute right-0 top-0 flex h-full items-center gap-x-1 rounded bg-red-50 px-2 py-0.5 text-xs font-light text-red-500 opacity-0 group-hover:opacity-100",children:[t.jsx(N.Edit,{size:12,className:"stroke-[3]"})," ",t.jsx("span",{className:"font-medium",children:o})," is editing this page"]})})]},e==null?void 0:e.id)};function bl({showModal:e=!1,onClose:s=()=>console.log("Cancelled")}){const[n]=ga(),[a,r]=g.useState([]),i=Qe(),[l,o]=g.useState(i),{data:u,isFetching:d}=jl(),{data:h}=Ae(),m=g.useCallback(_=>{var M;return(M=f.find(h,{key:_}))==null?void 0:M.hasSlug},[h]),j=g.useMemo(()=>f.filter(h,_=>!m(_.key)).map(_=>_.key),[m,h]),v=f.uniq(f.map(u,"lang")).filter(Boolean),p=g.useMemo(()=>f.filter(u,_=>_.pageType==="theme"?!1:l===i?_.lang===l||_.lang==="":_.lang===l),[u,l,i]),b=g.useMemo(()=>f.filter(p,_=>!j.includes(_.pageType)),[p,j]),S=g.useMemo(()=>f.filter(p,_=>j.includes(_.pageType)),[p,j]),{mutate:E,isPending:L}=xn();g.useEffect(()=>{const _=f.map(f.filter(p,{online:!0}),"id");r(_)},[p]),g.useEffect(()=>{const _=Object.keys(n);r(M=>f.filter(M,Q=>!f.includes(_,Q)))},[n]);const I=a.length===(p==null?void 0:p.length),k=_=>{r(M=>f.includes(M,_)?f.filter(M,Q=>Q!==_):f.concat(M,_))},T=()=>{r(I?[]:f.map(p,"id"))},V=()=>{E({ids:f.uniq(a)},{onSuccess:()=>{s(),$t("CENTER_CENTER"),o(i)}})},ne=_=>{if(_==="theme")return"Theme";const M=f.find(h,{key:_});return M?M==null?void 0:M.name:_},Y=g.useMemo(()=>{const _=[{label:"Updated",top:"pt-2"},...f.orderBy(f.filter(b,{online:!0}),"pageType"),...f.orderBy(f.filter(S,{online:!0}),"pageType")].filter(Q=>Q.pageType!=="theme"),M=[{label:"Offline",top:"pt-6"},...f.orderBy(f.filter(b,{online:!1}),"pageType"),...f.orderBy(f.filter(S,{online:!1}),"pageType")];return[..._,...M]},[b,S]);return t.jsx(c.Dialog,{open:e,onOpenChange:L?()=>{}: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."})]}),v.length>0&&t.jsx("div",{className:"my-[2px] mt-0",children:t.jsx(Aa,{languages:[i,...v],selectedLanguage:l,setSelectedLanguage:o})}),t.jsx("div",{className:"no-scrollbar relative -mx-4 -mt-4 h-full max-h-full overflow-y-auto",children:d?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:I,onClick:_=>{_.stopPropagation(),T()},type:"checkbox",className:"mt-1 cursor-pointer rounded focus:outline-none focus:ring-0"}),"Name"]}),t.jsx("th",{scope:"col",className:"w-[150px] px-2 py-3",children:"Type"}),t.jsx("th",{scope:"col",className:"w-[150px] px-4 py-3 text-right",children:"Status"})]})}),t.jsx("tbody",{children:f.map(Y,_=>_.label?t.jsx("tr",{children:t.jsxs("td",{colSpan:3,className:`relative px-6 py-2 text-xs font-medium text-gray-800 ${_.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:_.label})})]})},"separator"):t.jsx(vl,{page:_,selectedPages:a,handleCheckboxChange:k,getPageType:ne,hasSlug:m,currentOwnerId:n[(_==null?void 0:_.primaryPage)||(_==null?void 0:_.id)]}))})]})}),t.jsxs(c.DialogFooter,{className:"mt-10 flex items-center justify-center",children:[a.length>0&&t.jsxs("span",{className:"text-center text-sm text-muted-foreground",children:[a.length," Page",a.length!==1?"s":""," Selected"]}),t.jsx(c.Button,{disabled:L,variant:"outline",onClick:s,children:"Cancel"}),t.jsx(c.Button,{disabled:L||d||f.isEmpty(a),onClick:V,children:L?"Publishing...":"Publish Selected"})]})]})})}const wl=({isOpen:e,onClose:s,onContinue:n,isPending:a=!1,title:r="Translation Warning",description:i="Some blocks need translations before publishing. Do you want to continue anyway?"})=>{const l=()=>{s()},o=()=>{n()};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:r}),t.jsx(c.DialogDescription,{children:i})]}),t.jsxs(c.DialogFooter,{className:"flex gap-2",children:[t.jsx(c.Button,{variant:"outline",onClick:l,disabled:a,children:"Cancel"}),t.jsx(c.Button,{onClick:o,disabled:a,children:a?"Publishing...":"Continue Anyway"})]})]})})},Sl=()=>{const e=X(),s=le();return F.useQuery({queryKey:[D.GET_WEBSITE_DATA],staleTime:1e3*60*5,queryFn:async()=>e(s,{action:D.GET_WEBSITE_DATA,data:{draft:!0}})})};function Nl({onClose:e}){const{data:s,isFetching:n}=Sl(),{mutateAsync:a,isPending:r}=Gr(),i=$e("settingComponent",null),l=f.debounce(async o=>(await a({data:o}),!0),300);return i?t.jsx(c.Dialog,{open:!0,onOpenChange:e,children:t.jsxs(c.DialogContent,{className:"w-full",children:[t.jsx(c.DialogHeader,{children:t.jsx(c.DialogTitle,{children:"Website Settings"})}),n?t.jsxs("div",{className:"w-full space-y-3 py-4",children:[t.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"}),t.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"}),t.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"}),t.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"}),t.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"}),t.jsx("div",{className:"w-full h-8 rounded bg-gray-300 animate-pulse"})]}):t.jsx("div",{children:g.createElement(i,{data:s||{},onSave:r?()=>{}:l,cancel:r?()=>{}:e})})]})}):null}const El=()=>{const{selectedLang:e,fallbackLang:s}=$.useLanguages(),n=$e("getPreviewUrl",async m=>m),[a,r]=g.useState(""),{data:i}=ke(),{data:l}=qe(),{data:o}=Ae(),u=g.useMemo(()=>{var m;return(m=l==null?void 0:l.find(j=>(j==null?void 0:j.lang)===e))==null?void 0:m.slug},[e,l]),d=g.useCallback(m=>{var j;return(j=f.find(o,{key:m}))==null?void 0:j.hasSlug},[o]),h=e===s?"":e;return g.useEffect(()=>{(async()=>{if(typeof n=="function"){const m=!d(i==null?void 0:i.pageType),j=await n(m?`${h!==""?h+"/":""}${i==null?void 0:i.id}`:u||"");r(j)}else r("")})()},[n,u,i==null?void 0:i.pageType,d,i==null?void 0:i.id,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"})," ",re.PREVIEW]})})})},Cl=()=>{const[e,s]=$.useRightPanel();return t.jsxs(t.Fragment,{children:[t.jsx(dt,{content:re.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"})]})},Al=()=>{const[e,s]=g.useState(!1),{isLocked:n}=Je(),{savePageAsync:a,saveState:r}=$.useSavePage();g.useEffect(()=>{const d=h=>{r==="UNSAVED"&&(h.preventDefault(),h.returnValue=!1)};return r==="UNSAVED"&&window.addEventListener("beforeunload",d),()=>{window.removeEventListener("beforeunload",d)}},[r]);const i=g.useCallback(async()=>{e||(s(!0),await a(),s(!1))},[a,e]),{buttonIcon:l,buttonClass:o,tooltipContent:u}=g.useMemo(()=>{switch(r){case"UNSAVED":return{tooltipContent:re.SAVEDRAFT,buttonIcon:t.jsx(N.Save,{className:"h-4 w-4"}),buttonClass:"gap-x-1"};case"SAVING":return{tooltipContent:re.SAVING,buttonIcon:t.jsx(N.Loader,{className:"h-4 w-4 animate-spin text-sky-700"}),buttonClass:"gap-x-1"};case"SAVED":return{tooltipContent:re.SAVED,buttonIcon:t.jsx(N.CheckCircle,{className:"h-4 w-4"}),buttonClass:"text-green-500 gap-x-1"}}},[r]);return n?null:t.jsxs(c.Button,{size:"sm",variant:"ghost",onClick:i,className:o,children:[l," ",u]})},Tl=()=>{const{selectedLang:e}=$.useLanguages(),{data:s}=We(),{data:n}=qe(),[a,r]=g.useState(!1),[i,l]=g.useState(!1),[o,u]=g.useState(null),{savePageAsync:d}=$.useSavePage(),[h,m]=g.useState(!1),{data:j}=ke(),{mutate:y,isPending:v}=xn(),{needTranslations:p}=$.useSavePage(),b=p(),{buttonText:S,buttonClassName:E,isPublished:L}=g.useMemo(()=>{const Y=j&&(j==null?void 0:j.online);return{buttonClassName:Y?"hover:bg-green-600 bg-green-500":"",isPublished:Y,buttonText:Y?re.PUBLISHED:re.PUBLISH}},[j]),I=async()=>{if(b){m(!0);return}k()},k=()=>{const Y=[s==null?void 0:s.id,s==null?void 0:s.primaryPage];y({ids:f.compact(Y)},{onSuccess:()=>$t("TOP_RIGHT")})},T=()=>{m(!1),k()},V=async()=>{m(!1),await d()},ne=g.useMemo(()=>f.map(n??[],"id"),[n]);return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex",children:[t.jsxs(c.Button,{size:"sm",onClick:I,disabled:v||!(j!=null&&j.id),className:`relative flex items-center gap-1 overflow-hidden rounded-r-none text-white transition-all duration-300 ease-in-out ${E}`,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:L?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:L?t.jsx(N.Rocket,{className:"h-4 w-4"}):t.jsx(N.Send,{className:"h-4 w-4"})}),t.jsx("span",{children:S}),e?`(${f.upperCase(e)})`:""]}),t.jsxs(c.DropdownMenu,{children:[t.jsx(c.DropdownMenuTrigger,{asChild:!0,children:t.jsx(c.Button,{size:"sm",disabled:v||!(j!=null&&j.id),className:`rounded-l-none border-l border-white/50 px-2 text-white ${E}`,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:v,className:"cursor-pointer text-xs",onClick:()=>y({ids:ne},{onSuccess:()=>$t("TOP_RIGHT")}),children:[re.PUBLISH," with translation pages"]}),!L&&t.jsxs(c.DropdownMenuItem,{disabled:v,className:"cursor-pointer text-xs",onClick:()=>y({ids:[j==null?void 0:j.id]},{onSuccess:()=>$t("TOP_RIGHT")}),children:[re.PUBLISH," page"]}),t.jsxs(c.DropdownMenuItem,{onClick:()=>r(!0),className:"cursor-pointer text-xs",children:[re.OPEN," publish menu"]}),L&&t.jsxs(c.DropdownMenuItem,{onClick:()=>u(s),className:"cursor-pointer text-xs",children:[re.UNPUBLISH," page ",e?`(${f.upperCase(e)})`:""]})]})]})]}),t.jsx(bl,{showModal:a,onClose:()=>r(!1)}),o&&t.jsx(cs,{page:o,onClose:()=>u(null)}),t.jsx(wl,{isOpen:h,onClose:V,onContinue:T,isPending:v})]})},kl=()=>{const e=$e("settingComponent",null),[s,n]=g.useState(!1);return e?t.jsxs(t.Fragment,{children:[t.jsx(dt,{content:re.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(Nl,{onClose:()=>n(!1)}),t.jsx("div",{className:"h-4 w-px bg-gray-200 dark:bg-gray-700"})]}):null};function Pl(){const{isLocked:e}=Je(),[s]=Pe(),n=s.get("lang"),a=ca(n);return e||!a?t.jsx("div",{}):t.jsxs("div",{className:"flex items-center justify-end gap-1",children:[t.jsx(hl,{}),t.jsx(Re,{permission:we.EDIT_THEME,children:t.jsx(Cl,{})}),t.jsx(Re,{permission:we.EDIT_SETTINGS,children:t.jsx(kl,{})}),t.jsx(El,{}),t.jsx(Re,{permission:we.SAVE_PAGE,children:t.jsx(Al,{})}),t.jsx(Re,{permission:we.PUBLISH_PAGE,children:t.jsx(Tl,{})})]})}const Il=({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()}),_l=({dynamicPage:e,setDynamicPage:s,searchQuery:n,setSearchQuery:a,dynamicPages:r})=>{const{selectedLang:i,fallbackLang:l}=$.useLanguages(),o=(i==null?void 0:i.length)===0;return t.jsxs(c.DropdownMenu,{children:[t.jsx(c.DropdownMenuTrigger,{asChild:!0,children:t.jsxs(c.Button,{variant:"ghost",className:"w-max focus:outline-none focus:ring-0 border-[0px] rounded-md py-1 text-sm h-max border border-gray-200 hover:bg-gray-100 pl-4",children:[e?f.get(e,"name"):"Select Page",t.jsx(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(Il,{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))]})]})},Ll=()=>{const{dynamicPage:e,dynamicPages:s,allLangPages:n,selectedLang:a,searchQuery:r,updateDynamicPage:i,updateSearchQuery:l,onChangeLanguage:o}=da(),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(_l,{dynamicPage:e,setDynamicPage:i,searchQuery:r,setSearchQuery:l,dynamicPages:n})})},Dl=()=>{const[e,s]=g.useState(null),[n,a]=g.useState(null),[r,i]=g.useState(null),[l,o]=g.useState(null),[u,d]=g.useState(null),[h,m]=g.useState(null),{data:j,isFetching:y}=We(),{selectedLang:v,fallbackLang:p}=$.useLanguages(),{data:b}=qe(),S=b==null?void 0:b.find(T=>T.lang===v),{isLocked:E}=Je(),L=!(j!=null&&j.slug),[,I]=je.useAtom(os);if(!j)return null;const k=T=>{v.length>0&&v!==p?I({edit:!0,id:T==null?void 0:T.id,primaryPage:T==null?void 0:T.primaryPage}):m(T)};return 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",children:y?t.jsx(N.Loader,{className:"h-4 w-4 animate-spin text-slate-400"}):t.jsxs(t.Fragment,{children:[L?t.jsx(N.Globe,{className:"mr-1 h-4 w-4"}):t.jsx(N.File,{className:"mr-1 h-4 w-4"}),f.get(S||j,"name")??""]})}),E?t.jsx(c.Button,{variant:"ghost",size:"icon",className:"h-7 w-7 cursor-not-allowed rounded opacity-50 hover:bg-transparent",children:t.jsx(N.MoreHorizontal,{className:"h-4 w-4"})}):t.jsx(Sn,{page:j,setDuplicatePage:T=>d(T),setAddEditPage:T=>k(T),setUnpublishPage:T=>a(T),setDeletePage:T=>s(T),setMarkAsTemplate:T=>i(T),setUnmarkAsTemplate:T=>o(T),isLanguagePage:v.length>0&&v!==p,children:t.jsx(c.Button,{variant:"ghost",size:"icon",className:"h-7 w-7 rounded hover:bg-gray-200",children:t.jsx(N.MoreHorizontal,{className:"h-4 w-4"})})})]}),h&&t.jsx(vn,{closePanel:()=>m(null),editPage:()=>{},addEditPage:h,setAddEditPage:m}),e&&t.jsx(Bs,{page:e,onClose:()=>s(null)}),n&&t.jsx(cs,{page:n,onClose:()=>a(null)}),r&&t.jsx(wn,{page:r,onClose:()=>i(null)}),l&&t.jsx(Nn,{page:l,onClose:()=>o(null)}),u&&t.jsx(bn,{page:u,onClose:()=>d(null)})]})},Bl=({hasDynamicPage:e,className:s=""})=>t.jsx("div",{className:`fixed bottom-0 left-0 right-0 top-[50px] z-[20] z-[9999] flex w-screen items-center justify-center bg-black/10 backdrop-blur ${s}`,children:t.jsxs("div",{className:"flex min-w-[300px] max-w-[400px] flex-col items-center justify-center rounded-md bg-white p-4 shadow-xl",children:[t.jsx("h1",{className:"text-lg font-medium",children:e?"Select a page":"No pages found"}),t.jsx("p",{className:"pt-4 text-center text-sm text-gray-600",children:e?"Please select a page from the list in the top header. This will enable you to edit the page.":"Please add a new page"})]})}),Rl=()=>{const{data:e}=We(),s=hn(),{data:n,isFetching:a}=ke(),r=f.get(n,"dynamic",!1),i=$.useChaiFeatureFlag("dynamic-page-selector"),{dynamicPage:l,allLangPages:o}=da(),u=o.length>0,d=e==null?void 0:e.slug,h=!d,m=ma(),y=(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:$.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(Dl,{})}),t.jsxs("div",{className:$.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(Cn,{}),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:y==="/"?t.jsxs("span",{className:"text-gray-900",children:["/",t.jsx("span",{className:"text-[11px] font-light italic text-gray-400",children:"(Homepage)"})]}):y}),!h&&t.jsx("a",{href:m,target:"_blank",rel:"noopener noreferrer",children:t.jsx("div",{className:"ml-2 mr-px flex-shrink-0 rounded-sm p-1.5 text-gray-500 hover:bg-gray-100 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-300",children:t.jsx(N.ExternalLink,{className:"h-4 w-4",strokeWidth:1})})})]})]}),r&&!a&&i&&t.jsxs("div",{className:"relative",children:[!l&&t.jsx(Bl,{hasDynamicPage:u}),t.jsx(Ll,{})]})]})},Ml=()=>t.jsxs("div",{className:"flex h-full w-full items-center justify-between px-2",children:[t.jsx(ll,{}),t.jsx(Rl,{}),t.jsx(Pl,{})]}),Ol=()=>{const e=le(),{aiContext:s}=dn(),n=X();return g.useCallback(async(a,r,i,l)=>n(e,{action:D.ASK_AI,data:{type:a,prompt:r,blocks:i,context:s,lang:l}}),[e,s,n])},Gl=(e,s)=>s.map(n=>{if(f.has(e,n._type)){const a=sa.getDefaultBlockProps(n._type);return{...a,...f.pick(n,[...f.keys(a),"_type","_id","_name","_parent","_bindings"]),...f.pickBy(n,(r,i)=>f.endsWith(i,"_attrs")),...n}}return n}),Ul=e=>{const s=sa.useRegisteredChaiBlocks();return g.useMemo(()=>{if(!e||f.isEmpty(e))return{blocks:[]};const n=f.filter(e,a=>!f.includes(a==null?void 0:a._type,"@chai/"));return{blocks:Gl(s,n)}},[e,s])},Gn={async getUILibraryBlock(e,s,n){const a=await s(n,{action:"GET_LIBRARY_ITEM",data:{id:e.id}}),r=f.get(a,"html",""),i=f.get(a,"blocks",[]);return f.isArray(i)?i:$.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),[]}}},Fl=()=>{const e=le(),s=X();return F.useQuery({queryKey:["uiLibraries"],initialData:[],queryFn:async()=>{const a=(await s(e,{action:"GET_LIBRARIES"})).map(r=>({...r}));return a.forEach(r=>{$.registerChaiLibrary(r.id,{name:r.name,description:r.description,getBlocksList:i=>Gn.getUILibraryBlocks(i,s,e),getBlock:({block:i})=>Gn.getUILibraryBlock(i,s,e)})}),a}})},Pa=()=>{const e=Ls(),s=X(),{user:n}=Me(),a=n==null?void 0:n.id;return F.useQuery({queryKey:["permissions",a],queryFn:()=>s(e,{action:D.GET_ROLE_AND_PERMISSIONS,data:{userId:a}}),enabled:!!a})},ql=()=>{const e=le(),s=X(),{setCurrentEditor:n}=Je(),[,a]=Ds();return{onSave:async({page:i,blocks:l,needTranslations:o})=>{try{const u=await s(e,{action:"UPDATE_PAGE",data:{id:i,blocks:l,needTranslations:o}});return u.code==="PAGE_LOCKED"?(n(u.editor),!0):(a(d=>({...d,lastSaved:new Date().toISOString()})),u)}catch(u){return console.error(u),new Error("Failed to save blocks")}}}},$l=()=>{const{data:e}=ht(),s=le(),n=X();return{getPartialBlocks:g.useCallback(async()=>{const a={};for(const r of e??[])f.isEmpty(r==null?void 0:r.slug)&&(a[r.id]={type:r.pageType,name:f.startCase(r.name??r.slug),description:""});return a},[e]),getPartialBlockBlocks:g.useCallback(async a=>{if(!a)return[];try{const r=await n(s,{action:"GET_DRAFT_PAGE",data:{id:a,draft:!0,editor:!1}});return f.filter(r.blocks,i=>f.has(i,"_id"))}catch(r){return console.error(r),[]}},[n,s])}},Un=js.z.object({email:js.z.string().email({message:"Please enter a valid email address"}),password:js.z.string().min(6,{message:"Password must be at least 6 characters"})}),zl=()=>{const{setUser:e,logout:s}=Me(),n=Ls(),[a,r]=g.useState(""),[i,l]=g.useState(""),[o,u]=g.useState({}),[d,h]=g.useState(!1),[m,j]=g.useState(""),y=F.useMutation({mutationFn:async b=>{j("");const S=await un(n,{action:"LOGIN",data:b});if(!S.ok){const L=await S.json();throw new Error(L.error||"Login failed")}const E=await S.json();if(f.has(E,"id")&&f.has(E,"email")&&f.has(E,"accessToken")&&f.has(E,"refreshToken"))e(E);else throw s(),new Error("Something went wrong. Please try again.");return E},onSuccess:()=>{u({}),j("")},onError:b=>{u({email:" ",password:" "}),j(b.message?"Invalid email or password":"Something went wrong")}}),v=async b=>{b.preventDefault(),u({});const S={email:a,password:i};try{const E=Un.parse(S);y.mutate(E)}catch(E){if(E instanceof js.z.ZodError){const L=E.errors.reduce((I,k)=>{const T=k.path[0];return I[T]=k.message,I},{});u(L)}}},p=Un.safeParse({email:a,password:i}).success;return t.jsx("div",{className:"flex min-h-screen items-center justify-center 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:v,className:"space-y-4",children:[t.jsxs("div",{className:"space-y-1",children:[t.jsx(c.Label,{htmlFor:"email",children:"Email"}),t.jsx(c.Input,{id:"email",placeholder:"you@example.com",type:"email",value:a,onChange:b=>r(b.target.value),className:o.email?"border-destructive":""}),o.email&&t.jsx("p",{className:"text-sm text-destructive",children:o.email})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsx(c.Label,{htmlFor:"password",children:"Password"}),t.jsxs("div",{className:"relative",children:[t.jsx(c.Input,{id:"password",placeholder:"Enter your password",type:d?"text":"password",value:i,onChange:b=>l(b.target.value),className:o.password?"border-destructive":""}),t.jsx("button",{type:"button",className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground",onClick:()=>h(!d),children:d?t.jsx(N.EyeOff,{className:"h-4 w-4"}):t.jsx(N.Eye,{className:"h-4 w-4"})})]}),o.password&&t.jsx("p",{className:"text-sm text-destructive",children:o.password})]}),t.jsx("div",{children:t.jsx("p",{className:"text-sm text-destructive",children:m})}),t.jsx(c.Button,{type:"submit",className:"w-full",disabled:!p||y.isPending,children:y.isPending?t.jsxs(t.Fragment,{children:[t.jsx(N.Loader2,{className:"mr-2 h-4 w-4 animate-spin"}),"Logging in..."]}):"Login"})]})}),t.jsxs(c.CardFooter,{className:"flex flex-col justify-center",children:[t.jsxs("p",{className:"text-sm text-muted-foreground",children:["Forgot your password?"," ",t.jsx("a",{target:"_blank",href:"https://chaibuilder.com/forgot-password",className:"text-primary hover:underline",children:"Reset password"})]}),t.jsx("br",{}),t.jsx("br",{}),t.jsxs("div",{className:"flex items-center gap-2 border-t px-10 pt-2",children:["Powered by"," ",t.jsxs("a",{target:"_blank",href:"https://chaibuilder.com",className:"flex items-center gap-1 text-primary hover:underline",children:[t.jsx("img",{src:"https://ucarecdn.com/a82e256c-1cf2-4755-b65c-5d85e7652daa/-/preview/400x400",alt:"Chai Builder",className:"h-4 w-4 rounded font-bold uppercase"}),"Chai Builder"]})]})]})]})})};let Js=zl;const Vl=()=>g.useMemo(()=>Js,[Js]),Kl=e=>{Js=e},Hl=()=>{const e=Vl();return t.jsx(g.Suspense,{fallback:t.jsx("div",{children:"Loading..."}),children:t.jsx(e,{})})},Ql=({page:e,onClose:s})=>{const[n,a]=g.useState(e.slug||""),{mutate:r,isPending:i}=bi(),{data:l}=Ae(),o=f.find(l,{key:e==null?void 0:e.pageType}),u=h=>{if(h.preventDefault(),!(e!=null&&e.primaryPage)&&Object.keys(Ee).some(y=>n===`/${y}`||f.startsWith(n,`/${y}/`))){W.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 m=h.target.value;f.startsWith(m,`/${d}`)&&a(m)},className:"col-span-3",required:!0,pattern:"^/.*",title:"Slug must start with /",placeholder:"Enter page slug"})]})]}),t.jsx(c.DialogFooter,{children:t.jsx(c.Button,{type:"submit",disabled:i||!f.startsWith(n,`/${d}`)||f.isEqual(e==null?void 0:e.slug,n),children:i?"Changing...":"Change Slug"})})]})]})})},Wl=()=>{const[,e]=je.useAtom(os),{selectedLang:s,fallbackLang:n,setSelectedLang:a}=$.useLanguages(),{data:r,isFetching:i}=qe(),{data:l}=ke(),{data:o}=Ae(),u=g.useMemo(()=>{const S=o==null?void 0:o.find(E=>E.key===(l==null?void 0:l.pageType));return l!=null&&l.dynamic?S==null?void 0:S.dynamicSlug:""},[o,l==null?void 0:l.pageType,l==null?void 0:l.dynamic]),[d,h]=g.useState(null),[m,j]=g.useState(null),[y,v]=g.useState(null),{data:p}=Ke(),b=f.filter(f.get(p,"languages")||["en"],S=>!f.find(r,{lang:S})&&S!==f.get(p,"fallbackLang"));return t.jsxs("div",{className:"space-y-4",children:[t.jsx("ul",{className:"space-y-2",children:i?t.jsxs("div",{className:"w-full space-y-3 py-4",children:[t.jsx("div",{className:"h-8 w-full animate-pulse rounded bg-gray-300"}),t.jsx("div",{className:"h-8 w-full animate-pulse rounded bg-gray-300"}),t.jsx("div",{className:"h-8 w-full animate-pulse rounded bg-gray-300"})]}):f.map(r,S=>{const E=S.lang,L=S.slug,I=!S.primaryPage,k=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 ${k?"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"}`}),f.get(Ee,I?n:E,E)]}),t.jsxs("div",{children:[L&&t.jsxs("div",{className:"text-[11px] font-light text-slate-600",children:["Slug: ",t.jsx("b",{className:"font-mono font-medium",children:u?`${L}/${u}`:L})]}),t.jsxs("div",{className:"text-[11px] font-light text-slate-600",children:["Name:",t.jsxs("b",{className:"font-medium",children:[" ",S.name," "]})]})]})]}),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:[we.EDIT_PAGE,we.DELETE_PAGE,we.UNPUBLISH_PAGE],children:t.jsxs(c.DropdownMenu,{children:[t.jsx(c.DropdownMenuTrigger,{asChild:!0,onClick:T=>T.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:[we.EDIT_PAGE],children:t.jsxs(c.DropdownMenuItem,{className:"flex cursor-pointer items-center gap-2",onClick:T=>{T.stopPropagation(),e({edit:!0,id:S.id,primaryPage:S.primaryPage})},children:[t.jsx(N.PencilIcon,{className:"size-3"}),re.EDIT]})}),t.jsx(Re,{permissions:[we.UNPUBLISH_PAGE],children:(S==null?void 0:S.online)&&t.jsxs(c.DropdownMenuItem,{className:"flex cursor-pointer items-center gap-2",onClick:T=>{T.stopPropagation(),j(S)},children:[t.jsx(N.Power,{className:"size-3"}),re.UNPUBLISH]})}),t.jsx(Re,{permissions:[we.DELETE_PAGE],children:t.jsxs(c.DropdownMenuItem,{className:"flex cursor-pointer items-center gap-2",onClick:T=>{T.stopPropagation(),h(S)},children:[t.jsx(N.TrashIcon,{className:"size-3"}),re.DELETE]})})]})]})})})]},S.id),t.jsx("div",{className:"h-1 w-full border-b"})]})})}),t.jsx(Re,{permissions:[we.ADD_PAGE],children:t.jsx("div",{className:"flex w-full justify-center",children:t.jsx(c.Button,{variant:"default",size:"sm",disabled:f.isEmpty(b),onClick:()=>{e({primaryPage:l==null?void 0:l.id,edit:!1})},children:re.ADD_NEW_LANGUAGE})})}),d&&t.jsx(Bs,{page:d,onClose:()=>h(null)}),m&&t.jsx(cs,{page:m,onClose:()=>j(null)}),y&&t.jsx(Ql,{page:y,onClose:()=>v(null)})]})},Yl=({isActive:e,show:s})=>{const{data:n}=Ke();return!f.has(n,"languages")||!f.get(n,"languages",[]).length?null:t.jsx(c.Button,{size:"sm",onClick:s,variant:e?"default":"ghost",children:t.jsx(N.LanguagesIcon,{className:"w-4 h-4"})})},Ia="lang",Jl={id:Ia,label:"Languages",position:"top",panel:Wl,button:Yl,view:"modal",width:400};function tt({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=v=>Array.isArray(v)?"array":typeof v=="object"&&v!==null?"object":"value",m=Se.useCallback(v=>{const p=b=>n==="value"?b==="value"||b==="object":n==="array"?b==="array":b===n;v.type==="object"?(o(b=>[...b,v.key]),d(v.value)):p(v.type)&&(s([...l,v.key].join(".")),i(!1))},[l,s,n]),j=Se.useCallback(()=>{if(l.length>0){const v=l.slice(0,-1);o(v),d(v.reduce((p,b)=>p[b],e))}},[l,e]),y=Se.useMemo(()=>Object.entries(u).map(([v,p])=>({key:v,value:p,type:h(p)})).filter(v=>n==="value"?v.type==="value"||v.type==="object":n==="array"?v.type==="array"||v.type==="object":n==="object"?v.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:v=>{try{v.preventDefault();const p=v.currentTarget;p.scrollTop+=v.deltaY}catch{v.preventDefault()}},children:[t.jsx(c.CommandEmpty,{children:"No option found."}),t.jsxs(c.CommandGroup,{children:[l.length>0&&t.jsxs(c.CommandItem,{onSelect:j,className:"flex items-center text-sm",children:[t.jsx(N.ChevronLeft,{className:"w-4 h-4 mr-2"}),"Back"]}),y.map(v=>t.jsxs(c.CommandItem,{onSelect:()=>m(v),className:"flex items-center justify-between",children:[t.jsx("span",{children:v.key}),t.jsxs("div",{className:"flex items-center gap-2",children:[n==="object"&&v.type==="object"&&t.jsx(c.Button,{size:"sm",variant:"ghost",className:"h-6 px-2 hover:bg-primary hover:text-primary-foreground",onClick:p=>{p.stopPropagation(),s([...l,v.key].join(".")),i(!1)},children:"Select"}),(v.type==="object"||v.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"})})]})]},v.key))]})]})]})})]})}const Xl=()=>{const{selectedLang:e}=$.useLanguages(),{data:s,isFetching:n}=qe();return{data:g.useMemo(()=>f.find(s,{lang:e||""})||{},[s,e]),isFetching:n}},Zl=()=>{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>/,"")},Gt=({keyword:e,onComplete:s,field:n})=>{const a=X(),r=le(),{selectedLang:i,fallbackLang:l}=$.useLanguages(),o=$.useBuilderProp("aiContext",""),{mutate:u,isPending:d}=F.useMutation({mutationFn:async()=>{const h=Zl();return await a(r,{action:D.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"})})},eo=({isOpen:e,onClose:s,onSave:n,onDiscard:a,isSaving:r=!1,fromLanguage:i,toLanguage:l})=>{const o=Ee[i]||i,u=Ee[l]||l;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:"Unsaved SEO Changes"}),t.jsxs(c.DialogDescription,{children:['You have unsaved changes in the SEO form for "',o,'". Do you want to save these changes before switching to "',u,'"?']})]}),t.jsxs("div",{className:"flex justify-end gap-3 pt-4",children:[t.jsx(c.Button,{variant:"outline",onClick:a,disabled:r,children:"Discard Changes"}),t.jsx(c.Button,{onClick:n,disabled:r,children:r?"Saving...":"Save & Switch"})]})]})})},to=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Fn=e=>{if(!e.trim())return{isValid:!1,parsed:null,placeholders:[],error:{message:"JSON is empty"}};try{return{isValid:!0,parsed:JSON.parse(e),error:null,placeholders:[]}}catch{}const s=/{{([^{}]+)}}/g,n=[];let a=e,r;for(;(r=s.exec(e))!==null;){const i=r[0],l=r.index,o=`"__placeholder_${n.length}__"`;n.push({original:i,replaced:o,position:l}),a=a.replace(i,o)}try{return{isValid:!0,parsed:JSON.parse(a),error:null,placeholders:n}}catch(i){const l=i,o=l.message.match(/position (\d+)/),u=o?parseInt(o[1]):void 0;let d,h;if(u!==void 0){const m=a.substring(0,u).split(`
|
|
3
|
+
`);d=m.length,h=m[m.length-1].length+1}return{isValid:!1,parsed:null,placeholders:n,error:{message:l.message,line:d,column:h,position:u}}}},so=(e,s)=>{let a=JSON.stringify(e,null,2);return s.forEach(({original:r},i)=>{const l=`"__placeholder_${i}__"`,o=new RegExp(to(l),"g");a=a.replace(o,r)}),a},no=(e,s)=>{if(!e)return"";let n=JSON.stringify(e,null,2);const a=/{{([^{}]+)}}/g;let r;for(;(r=a.exec(n))!==null;){const i=r[1],l=f.get(s,i,null);n=n.replace(r[0],l)}return n},_a=({value:e,onChange:s,disabled:n=!1,readOnly:a=!1,placeholder:r="Enter JSON",rows:i=6,id:l="json-input",pageData:o={},handleFieldInsert:u})=>{const[d,h]=g.useState("edit"),[m,j]=g.useState(null),[y,v]=g.useState(""),p=g.useRef(null),b=I=>{if(a)return;const k=I.target.value;s(k)},S=I=>{if(I.key==="Tab"){I.preventDefault();const k=I.currentTarget,T=k.selectionStart,V=k.selectionEnd;if(T!==V){const Y=e.substring(T,V).split(`
|
|
4
|
+
`);if(I.shiftKey){const M=Y.map(R=>R.startsWith(" ")?R.substring(2):R).join(`
|
|
5
|
+
`),Q=e.substring(0,T)+M+e.substring(V);s(Q),setTimeout(()=>{k.selectionStart=T,k.selectionEnd=T+M.length},0)}else{const M=Y.map(R=>` ${R}`).join(`
|
|
6
|
+
`),Q=e.substring(0,T)+M+e.substring(V);s(Q),setTimeout(()=>{k.selectionStart=T,k.selectionEnd=T+M.length},0)}}else{const ne=e.substring(0,T)+" "+e.substring(V);s(ne),setTimeout(()=>{k.selectionStart=k.selectionEnd=T+2},0)}}};g.useEffect(()=>{const I=Fn(e);if(I.isValid)if(j(null),I.parsed){const k=no(I.parsed,o);v(k)}else v("");else j(I.error),v("")},[e,o]);const E=()=>{const I=Fn(e);if(I.isValid&&I.parsed){const k=so(I.parsed,I.placeholders);s(k)}},L=()=>{m!=null&&m.position&&p.current&&(p.current.focus(),p.current.setSelectionRange(m.position,m.position+1))};return t.jsx("div",{className:"space-y-2",children:t.jsxs(c.Tabs,{value:d,onValueChange:h,className:"w-full",children:[t.jsxs("div",{className:"mb-2 flex items-center justify-between",children:[t.jsxs(c.TabsList,{className:"grid w-[200px] grid-cols-2",children:[t.jsxs(c.TabsTrigger,{value:"edit",className:"flex items-center gap-1",children:[t.jsx(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()||m!==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(tt,{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||m!==null,children:"Format"})]})]}),t.jsxs(c.TabsContent,{value:"edit",className:"mt-0",children:[t.jsx(c.Textarea,{ref:p,id:l,name:l,className:`rounded-md border border-input text-xs ${m?"border-red-500":""}`,onChange:b,onKeyDown:S,value:e,placeholder:r,rows:i,disabled:n,readOnly:a}),m&&t.jsxs(c.Alert,{variant:"destructive",className:"mt-2",children:[t.jsx(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:m.message}),m.line&&m.column&&t.jsxs("span",{className:"text-sm",children:["Error at line ",m.line,", column ",m.column]}),t.jsx(c.Button,{type:"button",variant:"link",size:"sm",className:"mt-1 h-auto self-start p-0 text-sm",onClick:L,children:"Show position"})]})]})]}),t.jsxs(c.TabsContent,{value:"preview",className:"mt-0",children:[t.jsx(c.Textarea,{rows:i,value:y,readOnly:!0,className:"cursor-default bg-muted font-mono text-sm"}),t.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"This is how the JSON will look after placeholder substitution."})]})]})})},lt=class lt{constructor(){Fe(this,"state",{});Fe(this,"currentPageId",null)}static getInstance(){return lt.instance||(lt.instance=new lt),lt.instance}setInitialValues(s,n,a){this.state[s]||(this.state[s]={}),this.state[s][n]={initial:{...a},current:{...a}},this.currentPageId=s}updateCurrentValues(s,n,a){if(!this.state[s]||!this.state[s][n]){this.setInitialValues(s,n,a);return}this.state[s][n].current={...a},this.currentPageId=s}isDirty(s,n){if(!this.state[s]||!this.state[s][n])return!1;const a=this.state[s][n];return JSON.stringify(a.initial)!==JSON.stringify(a.current)}markClean(s,n){var a;(a=this.state[s])!=null&&a[n]&&(this.state[s][n].initial={...this.state[s][n].current})}getInitialValues(s,n){var a,r;return((r=(a=this.state[s])==null?void 0:a[n])==null?void 0:r.initial)||null}clearLanguage(s,n){this.state[s]&&(n?delete this.state[s][n]:delete this.state[s])}clearAll(){this.state={},this.currentPageId=null}onPageChange(s){this.currentPageId&&this.currentPageId!==s&&this.clearLanguage(this.currentPageId),this.currentPageId=s}};Fe(lt,"instance");let Xs=lt;const et=Xs.getInstance(),qn=e=>{if(!e)return!0;try{return JSON.parse(e),!0}catch{return!1}},ao=(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}},La=()=>{const{t:e}=$.useTranslation(),[,s]=$.useSidebarActivePanel(),{data:n}=ke(),{data:a}=fn(),{data:r,isFetching:i}=Xl(),l=r==null?void 0:r.seo,o=g.useRef(null),u=n==null?void 0:n.id,d=n==null?void 0:n.pageType,h=ya(d),{selectedLang:m,fallbackLang:j}=$.useLanguages(),y=m||j,[v,p]=g.useState(!1),[b,S]=g.useState(!1),[E,L]=g.useState(!1),[I,k]=g.useState(null),[T,V]=g.useState({keyword:"",title:"",description:"",cononicalUrl:"",noIndex:!1,noFollow:"",ogTitle:"",ogDescription:"",ogImage:"",ogImageId:"",searchTitle:"",searchDescription:"",jsonLD:"{}",...l}),ne=g.useRef({initial:T,updated:T}),{mutate:Y,isPending:_}=gn(),M=_||v||b,{hasPermission:Q}=$.usePermissions(),R=Q(we.EDIT_SEO);g.useEffect(()=>{if(!i&&l&&u){const w={keyword:"",title:"",description:"",cononicalUrl:"",noIndex:!1,noFollow:"",ogTitle:"",ogDescription:"",ogImage:"",ogImageId:"",searchTitle:"",searchDescription:"",jsonLD:"",...l};et.onPageChange(u);const x=et.getInitialValues(u,y);x?V(x):(V(w),et.setInitialValues(u,y,w))}},[i,l,y,u]),g.useEffect(()=>{const w=x=>{const{fromLang:P,toLang:U,switchHandler:C}=x.detail;et.isDirty(u,P)?(k({fromLang:P,toLang:U,switchHandler:C}),L(!0)):C()};return window.addEventListener("seo-language-switch-check",w),()=>{window.removeEventListener("seo-language-switch-check",w)}},[u]);const Z=async()=>{if(!(!h||!y))try{p(!0);const w=Ss(h,y),x={...T,keyword:f.get(w,"seo.keyword",""),title:f.get(w,"seo.title",""),description:f.get(w,"seo.description",""),cononicalUrl:f.get(w,"seo.canonicalUrl",""),noIndex:f.get(w,"seo.noIndex",!1),noFollow:f.get(w,"seo.noFollow",!1),ogTitle:f.get(w,"seo.ogTitle",""),ogDescription:f.get(w,"seo.ogDescription","")};V(x),ne.current.updated=x,W.toast.success(e("SEO fields reset to defaults"))}catch(w){W.toast.error(e("Failed to reset SEO fields")),console.error("Reset SEO error:",w)}finally{p(!1)}},K=async()=>{if(!(!h||!y))try{S(!0);const w=Ss(h,y),x={...T,jsonLD:f.get(w,"seo.jsonLD","")};V(x),ne.current.updated=x,W.toast.success(e("JSON-LD reset to default"))}catch(w){W.toast.error(e("Failed to reset JSON-LD")),console.error("Reset JSON-LD error:",w)}finally{S(!1)}},te=async()=>{Y({id:r==null?void 0:r.id,seo:T},{onSuccess:()=>{ne.current.initial=T,ne.current.updated=T,et.markClean(u,y),W.toast.success("SEO & JSON-LD updated successfully")}})},ue=(w,x)=>{const P=document.getElementById(x);if(P){const{value:U,newCursorPos:C}=ao(P,w);o.current={id:x,position:C},P.tagName.toLowerCase()==="input"?(P.value=U,V(z=>({...z,[P.name]:U})),P.focus(),P.setSelectionRange(C,C),[0,10,50,100,200].forEach(z=>{setTimeout(()=>{const J=document.getElementById(x);J&&(J.focus(),J.setSelectionRange(C,C))},z)})):(V(O=>({...O,[P.name]:U})),requestAnimationFrame(()=>{const O=document.getElementById(x);O&&(O.focus(),O.setSelectionRange(C,C),setTimeout(()=>{const z=document.getElementById(x);z&&(z.focus(),z.setSelectionRange(C,C))},50))}))}},he=w=>{const x={...T,[w.target.name]:w.target.name==="noIndex"||w.target.name==="noFollow"?w.target.checked:w.target.value};V(x),ne.current.updated=x,et.updateCurrentValues(u,y,x)},oe=w=>x=>{f.isEmpty(x.fieldValue)||he({target:{name:w,value:typeof x.fieldValue=="string"?x.fieldValue.replace(/^"(.*)"$/,"$1"):x.fieldValue}}),x.error&&W.toast.error(t.jsxs("div",{children:[t.jsx("h2",{children:"Failed to generate:"}),t.jsx("p",{children:x.error})]}))};return t.jsxs("div",{className:"relative flex h-full flex-col","data-panel-id":"seo",children:[!R&&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(Cn,{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:[R&&t.jsx("div",{className:"mb-4 flex justify-end",children:t.jsx(c.Button,{type:"button",variant:"outline",size:"sm",onClick:Z,disabled:M||!R||!h,children:e(v?"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")}),R&&t.jsx(tt,{dataType:"value",data:a??{},onSelect:w=>ue(w,"keyword")})]}),t.jsx(c.Input,{type:"text",id:"keyword",name:"keyword",value:T.keyword,onChange:he,disabled:M||!R,placeholder:e("Enter keyword"),readOnly:!R})]}),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(Gt,{keyword:T.keyword,onComplete:oe("title"),field:"title"}),R&&t.jsx(tt,{dataType:"value",data:a??{},onSelect:w=>ue(w,"title")})]})]}),t.jsx(c.Input,{type:"text",id:"title",name:"title",value:T.title,onChange:he,disabled:M||!R,placeholder:e("Enter SEO title"),readOnly:!R})]}),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(Gt,{keyword:T.keyword,onComplete:oe("description"),field:"description"}),R&&t.jsx(tt,{data:a??{},onSelect:w=>ue(w,"description")})]})]}),t.jsx(c.Textarea,{id:"description",name:"description",rows:5,value:T.description,onChange:he,disabled:M||!R,placeholder:e("Enter SEO description"),readOnly:!R})]}),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")}),R&&t.jsx(tt,{dataType:"value",data:a??{},onSelect:w=>ue(w,"canonicalUrl")})]}),t.jsx(c.Input,{type:"text",id:"canonicalUrl",name:"canonicalUrl",value:T.canonicalUrl,onChange:he,disabled:M||!R,placeholder:e("Enter Canonical URL"),readOnly:!R})]}),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:T.noIndex,onChange:he,disabled:M||!R,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:T.noFollow,onChange:he,disabled:M||!R,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(Gt,{keyword:T.keyword,onComplete:oe("ogTitle"),field:"ogTitle"}),R&&t.jsx(tt,{dataType:"value",data:a??{},onSelect:w=>ue(w,"ogTitle")})]})]}),t.jsx(c.Input,{type:"text",id:"ogTitle",name:"ogTitle",value:T.ogTitle,onChange:he,disabled:M||!R,placeholder:e("Enter OG title"),readOnly:!R})]}),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(Gt,{keyword:T.keyword,onComplete:oe("ogDescription"),field:"ogDescription"}),R&&t.jsx(tt,{dataType:"value",data:a??{},onSelect:w=>ue(w,"ogDescription")})]})]}),t.jsx(c.Textarea,{id:"ogDescription",name:"ogDescription",rows:5,value:T.ogDescription,onChange:he,disabled:M||!R,placeholder:e("Enter OG description"),readOnly:!R})]}),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(_s,{assetId:T.ogImageId,assetUrl:T.ogImage,onChange:w=>{V({...T,ogImage:w.url,ogImageId:w.id})},disabled:M||!R,placeholder:e("Select OG image"),className:"mb-2"})]})]})]})]})}),t.jsx(c.TabsContent,{value:"jsonld",children:t.jsxs("div",{className:"space-y-4",children:[R&&t.jsx("div",{className:"mb-4 flex justify-end",children:t.jsx(c.Button,{variant:"outline",size:"sm",type:"button",onClick:K,disabled:M||!R||!h,children:e(b?"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(Gt,{keyword:T.keyword,onComplete:oe("jsonLD"),field:"jsonLD"})})]}),t.jsx("div",{className:"hidden",children:JSON.stringify(a)}),t.jsx(_a,{id:"jsonLD",value:T.jsonLD,onChange:w=>{he({target:{name:"jsonLD",value:w}})},placeholder:e("Enter JSON-LD"),disabled:M||!R,readOnly:!R,pageData:a||{},rows:12,handleFieldInsert:ue})]})]})})]})})]}),R&&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:[qn(T.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:te,disabled:!qn(T==null?void 0:T.jsonLD)||f.isEqual(ne.current.initial,T)||M||!R,children:e(_?"Saving...":"Save")}),t.jsx(c.Button,{variant:"link",className:"text-gray-500 hover:text-gray-700",onClick:()=>s("outline"),children:e("Cancel")})]})]}),t.jsx(eo,{isOpen:E,onClose:()=>{L(!1),k(null)},onSave:async()=>{I&&(await te(),I.switchHandler(),L(!1),k(null))},onDiscard:()=>{if(I){const w=et.getInitialValues(u,y);w&&(V(w),ne.current.updated=w,et.setInitialValues(u,y,w)),I.switchHandler(),L(!1),k(null)}},isSaving:_,fromLanguage:(I==null?void 0:I.fromLang)||y,toLanguage:(I==null?void 0:I.toLang)||""})]})};La.displayName="SeoPanel";const Da="seo",ro=({isActive:e,show:s})=>{const{data:n}=ke(),a=ya(n==null?void 0:n.pageType);return!f.has(a,"hasSlug")||!a.hasSlug?null:t.jsx(c.Button,{size:"sm",className:"my-1",onClick:s,variant:e?"default":"ghost",children:t.jsxs("svg",{className:"h-4 w-4",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 21 21",fill:"currentColor",children:[t.jsx("path",{d:"M9.931 6.818c-1.238 0-2.136.925-2.136 2.2 0 1.279.898 2.207 2.136 2.207.664 0 1.257-.246 1.67-.694a.15.15 0 0 0-.009-.213l-.311-.286a.15.15 0 0 0-.213.009c-.273.297-.677.46-1.137.46-.699 0-1.233-.444-1.375-1.12h3.295a.15.15 0 0 0 .151-.151v-.211c0-1.295-.852-2.2-2.072-2.2m0 .724c.697 0 1.188.422 1.315 1.113h-2.69c.142-.673.676-1.113 1.374-1.113m4.332-.724c-1.246 0-2.15.925-2.15 2.2 0 1.279.904 2.207 2.15 2.207.596 0 1.143-.223 1.538-.628s.612-.965.612-1.579c0-1.275-.904-2.2-2.15-2.2m0 3.683c-.826 0-1.426-.624-1.426-1.483 0-.855.6-1.475 1.426-1.475s1.426.621 1.426 1.476c0 .423-.144.804-.406 1.073-.258.264-.62.41-1.019.41M6.318 8.71c-.665-.206-.902-.335-.902-.645 0-.47.564-.521.806-.521.29 0 .552.07.801.215a.15.15 0 0 0 .206-.055l.212-.366a.15.15 0 0 0-.055-.206 2.27 2.27 0 0 0-1.165-.312c-.915 0-1.53.501-1.53 1.245 0 .899.816 1.152 1.411 1.336.655.203.812.307.804.53-.016.398-.567.429-.735.429-.386 0-.722-.129-.972-.374q-.043-.042-.107-.043a.15.15 0 0 0-.106.045l-.295.302a.15.15 0 0 0 .002.213c.383.374.908.58 1.478.58.859 0 1.432-.441 1.459-1.125.031-.833-.746-1.074-1.313-1.249"}),t.jsx("path",{d:"M20.396 2.049H.604A.604.604 0 0 0 0 2.653v12.7c0 .333.27.604.604.604h6.941c-.266 1.296-.881 1.966-.886 1.971a.604.604 0 0 0 .434 1.024h6.815a.604.604 0 0 0 .434-1.024c-.007-.007-.621-.675-.886-1.971h6.941c.333 0 .604-.27.604-.604V2.652a.604.604 0 0 0-.604-.604m-.604 12.701h-.985v-.17a.604.604 0 0 0-1.208 0v.17h-.63v-.17a.604.604 0 0 0-1.208 0v.17H1.207V3.256h18.585z"})]})})},io={id:Da,label:"SEO & JSON-LD",panel:La,button:ro,position:"top",width:600,view:"modal"},Zs={},vs=(e,s)=>{f.has(Zs,e)&&console.warn(`Site setting ${e} already registered. Overriding...`),f.set(Zs,e,{id:e,...s})},lo=()=>f.values(Zs),oo=()=>{var i;const e=lo(),[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:"no-scrollbar max-w-[25%] overflow-y-auto border-r pr-2",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:"no-scrollbar flex-1 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"})})})})]})},co="site-settings",uo=({isActive:e,show:s})=>$.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,ho={id:co,label:"Site Settings",panel:oo,button:uo,position:"bottom",width:800,view:"modal"},mo="user-info",fo=()=>{const{user:e,logout:s}=Me(),n=$e("onLogout",f.noop);return e?t.jsxs(c.HoverCard,{children:[t.jsx(c.HoverCardTrigger,{asChild:!0,children:t.jsx(c.Button,{variant:"ghost",className:"text-sm font-medium",children:t.jsx(N.User,{className:"h-4 w-4"})})}),t.jsxs(c.HoverCardContent,{className:"w-auto space-y-2 p-4",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(),f.isFunction(n)&&n()},children:"Logout"})]})]})]})]})]}):null},go={id:mo,label:"User Info",button:fo,position:"bottom"},xo=()=>{$.registerChaiSidebarPanel(Da,io),$.registerChaiSidebarPanel(Ia,Jl),$.registerChaiSidebarPanel("site-settings",ho),$.registerChaiSidebarPanel("user-info",go)};var se={context:void 0,registry:void 0,effects:void 0,done:!1,getContextId(){return $n(this.context.count)},getNextContextId(){return $n(this.context.count++)}};function $n(e){const s=String(e),n=s.length-1;return se.context.id+(n?String.fromCharCode(96+n):"")+s}function Ut(e){se.context=e}var po=(e,s)=>e===s,Ns=Symbol("solid-proxy"),Ba=typeof Proxy=="function",An=Symbol("solid-track"),Es={equals:po},Ra=$a,Xe=1,Cs=2,Ma={owned:null,cleanups:null,context:null,owner:null},Ks={},fe=null,Hs=null,yo=null,ye=null,Ie=null,He=null,Rs=0;function st(e,s){const n=ye,a=fe,r=e.length===0,i=s===void 0?a:s,l=r?Ma:{owned:null,cleanups:null,context:i?i.context:null,owner:i},o=r?e:()=>e(()=>Te(()=>Kt(l)));fe=l,ye=null;try{return Ve(o,!0)}finally{ye=n,fe=a}}function Ne(e,s){s=s?Object.assign({},Es,s):Es;const n={value:e,observers:null,observerSlots:null,comparator:s.equals||void 0},a=r=>(typeof r=="function"&&(r=r(n.value)),qa(n,r));return[Fa.bind(n),a]}function Oa(e,s,n){const a=Ms(e,s,!0,Xe);Mt(a)}function nt(e,s,n){const a=Ms(e,s,!1,Xe);Mt(a)}function Tn(e,s,n){Ra=_o;const a=Ms(e,s,!1,Xe);(!n||!n.render)&&(a.user=!0),He?He.push(a):Mt(a)}function Le(e,s,n){n=n?Object.assign({},Es,n):Es;const a=Ms(e,s,!0,0);return a.observers=null,a.observerSlots=null,a.comparator=n.equals||void 0,Mt(a),Fa.bind(a)}function jo(e){return e&&typeof e=="object"&&"then"in e}function vo(e,s,n){let a,r,i;arguments.length===1?(a=!0,r=e,i={}):(a=e,r=s,i={});let l=null,o=Ks,u=null,d=!1,h="initialValue"in i,m=typeof a=="function"&&Le(a);const j=new Set,[y,v]=(i.storage||Ne)(i.initialValue),[p,b]=Ne(void 0),[S,E]=Ne(void 0,{equals:!1}),[L,I]=Ne(h?"ready":"unresolved");se.context&&(u=se.getNextContextId(),i.ssrLoadFrom==="initial"?o=i.initialValue:se.load&&se.has(u)&&(o=se.load(u)));function k(Y,_,M,Q){return l===Y&&(l=null,Q!==void 0&&(h=!0),(Y===o||_===o)&&i.onHydrated&&queueMicrotask(()=>i.onHydrated(Q,{value:_})),o=Ks,T(_,M)),_}function T(Y,_){Ve(()=>{_===void 0&&v(()=>Y),I(_!==void 0?"errored":h?"ready":"unresolved"),b(_);for(const M of j.keys())M.decrement();j.clear()},!1)}function V(){const Y=ko,_=y(),M=p();if(M!==void 0&&!l)throw M;return ye&&ye.user,_}function ne(Y=!0){if(Y!==!1&&d)return;d=!1;const _=m?m():a;if(_==null||_===!1){k(l,Te(y));return}const M=o!==Ks?o:Te(()=>r(_,{value:y(),refetching:Y}));return jo(M)?(l=M,"value"in M?(M.status==="success"?k(l,M.value,void 0,_):k(l,void 0,en(M.value),_),M):(d=!0,queueMicrotask(()=>d=!1),Ve(()=>{I(h?"refreshing":"pending"),E()},!1),M.then(Q=>k(M,Q,void 0,_),Q=>k(M,void 0,en(Q),_)))):(k(l,M,void 0,_),M)}return Object.defineProperties(V,{state:{get:()=>L()},error:{get:()=>p()},loading:{get(){const Y=L();return Y==="pending"||Y==="refreshing"}},latest:{get(){if(!h)return V();const Y=p();if(Y&&!l)throw Y;return y()}}}),m?Oa(()=>ne(!1)):ne(!1),[V,{refetch:ne,mutate:v}]}function bo(e){return Ve(e,!1)}function Te(e){if(ye===null)return e();const s=ye;ye=null;try{return e()}finally{ye=s}}function wo(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=Te(()=>s(o,r,l));return r=o,u}}function Ga(e){Tn(()=>Te(e))}function Lt(e){return fe===null||(fe.cleanups===null?fe.cleanups=[e]:fe.cleanups.push(e)),e}function zn(){return fe}function So(e,s){const n=fe,a=ye;fe=e,ye=null;try{return Ve(s,!0)}catch(r){kn(r)}finally{fe=n,ye=a}}function No(e){const s=ye,n=fe;return Promise.resolve().then(()=>{ye=s,fe=n;let a;return Ve(e,!1),ye=fe=null,a?a.done:void 0})}var[Eo,Bu]=Ne(!1);function Co(){return[Eo,No]}function Ao(e,s){const n=Symbol("context");return{id:n,Provider:Lo(n),defaultValue:e}}function To(e){let s;return fe&&fe.context&&(s=fe.context[e.id])!==void 0?s:e.defaultValue}function Ua(e){const s=Le(e),n=Le(()=>tn(s()));return n.toArray=()=>{const a=n();return Array.isArray(a)?a:a!=null?[a]:[]},n}var ko;function Fa(){if(this.sources&&this.state)if(this.state===Xe)Mt(this);else{const e=Ie;Ie=null,Ve(()=>Ts(this),!1),Ie=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 qa(e,s,n){let a=e.value;return(!e.comparator||!e.comparator(a,s))&&(e.value=s,e.observers&&e.observers.length&&Ve(()=>{for(let r=0;r<e.observers.length;r+=1){const i=e.observers[r],l=Hs&&Hs.running;l&&Hs.disposed.has(i),(l?!i.tState:!i.state)&&(i.pure?Ie.push(i):He.push(i),i.observers&&za(i)),l||(i.state=Xe)}if(Ie.length>1e6)throw Ie=[],new Error},!1)),s}function Mt(e){if(!e.fn)return;Kt(e);const s=Rs;Po(e,e.value,s)}function Po(e,s,n){let a;const r=fe,i=ye;ye=fe=e;try{a=e.fn(s)}catch(l){return e.pure&&(e.state=Xe,e.owned&&e.owned.forEach(Kt),e.owned=null),e.updatedAt=n+1,kn(l)}finally{ye=i,fe=r}(!e.updatedAt||e.updatedAt<=n)&&(e.updatedAt!=null&&"observers"in e?qa(e,a):e.value=a,e.updatedAt=n)}function Ms(e,s,n,a=Xe,r){const i={fn:e,state:a,updatedAt:null,owned:null,sources:null,sourceSlots:null,cleanups:null,value:s,owner:fe,context:fe?fe.context:null,pure:n};return fe===null||fe!==Ma&&(fe.owned?fe.owned.push(i):fe.owned=[i]),i}function As(e){if(e.state===0)return;if(e.state===Cs)return Ts(e);if(e.suspense&&Te(e.suspense.inFallback))return e.suspense.effects.push(e);const s=[e];for(;(e=e.owner)&&(!e.updatedAt||e.updatedAt<Rs);)e.state&&s.push(e);for(let n=s.length-1;n>=0;n--)if(e=s[n],e.state===Xe)Mt(e);else if(e.state===Cs){const a=Ie;Ie=null,Ve(()=>Ts(e,s[0]),!1),Ie=a}}function Ve(e,s){if(Ie)return e();let n=!1;s||(Ie=[]),He?n=!0:He=[],Rs++;try{const a=e();return Io(n),a}catch(a){n||(He=null),Ie=null,kn(a)}}function Io(e){if(Ie&&($a(Ie),Ie=null),e)return;const s=He;He=null,s.length&&Ve(()=>Ra(s),!1)}function $a(e){for(let s=0;s<e.length;s++)As(e[s])}function _o(e){let s,n=0;for(s=0;s<e.length;s++){const a=e[s];a.user?e[n++]=a:As(a)}if(se.context){if(se.count){se.effects||(se.effects=[]),se.effects.push(...e.slice(0,n));return}Ut()}for(se.effects&&(se.done||!se.count)&&(e=[...se.effects,...e],n+=se.effects.length,delete se.effects),s=0;s<n;s++)As(e[s])}function Ts(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===Xe?a!==s&&(!a.updatedAt||a.updatedAt<Rs)&&As(a):r===Cs&&Ts(a,s)}}}function za(e){for(let s=0;s<e.observers.length;s+=1){const n=e.observers[s];n.state||(n.state=Cs,n.pure?Ie.push(n):He.push(n),n.observers&&za(n))}}function Kt(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--)Kt(e.tOwned[s]);delete e.tOwned}if(e.owned){for(s=e.owned.length-1;s>=0;s--)Kt(e.owned[s]);e.owned=null}if(e.cleanups){for(s=e.cleanups.length-1;s>=0;s--)e.cleanups[s]();e.cleanups=null}e.state=0}function en(e){return e instanceof Error?e:new Error(typeof e=="string"?e:"Unknown error",{cause:e})}function kn(e,s=fe){throw en(e)}function tn(e){if(typeof e=="function"&&!e.length)return tn(e());if(Array.isArray(e)){const s=[];for(let n=0;n<e.length;n++){const a=tn(e[n]);Array.isArray(a)?s.push.apply(s,a):s.push(a)}return s}return e}function Lo(e,s){return function(a){let r;return nt(()=>r=Te(()=>(fe.context={...fe.context,[e]:a.value},Ua(()=>a.children))),void 0),r}}var sn=Symbol("fallback");function ks(e){for(let s=0;s<e.length;s++)e[s]()}function Do(e,s,n={}){let a=[],r=[],i=[],l=0,o=s.length>1?[]:null;return Lt(()=>ks(i)),()=>{let u=e()||[],d=u.length,h,m;return u[An],Te(()=>{let y,v,p,b,S,E,L,I,k;if(d===0)l!==0&&(ks(i),i=[],a=[],r=[],l=0,o&&(o=[])),n.fallback&&(a=[sn],r[0]=st(T=>(i[0]=T,n.fallback())),l=1);else if(l===0){for(r=new Array(d),m=0;m<d;m++)a[m]=u[m],r[m]=st(j);l=d}else{for(p=new Array(d),b=new Array(d),o&&(S=new Array(d)),E=0,L=Math.min(l,d);E<L&&a[E]===u[E];E++);for(L=l-1,I=d-1;L>=E&&I>=E&&a[L]===u[I];L--,I--)p[I]=r[L],b[I]=i[L],o&&(S[I]=o[L]);for(y=new Map,v=new Array(I+1),m=I;m>=E;m--)k=u[m],h=y.get(k),v[m]=h===void 0?-1:h,y.set(k,m);for(h=E;h<=L;h++)k=a[h],m=y.get(k),m!==void 0&&m!==-1?(p[m]=r[h],b[m]=i[h],o&&(S[m]=o[h]),m=v[m],y.set(k,m)):i[h]();for(m=E;m<d;m++)m in p?(r[m]=p[m],i[m]=b[m],o&&(o[m]=S[m],o[m](m))):r[m]=st(j);r=r.slice(0,l=d),a=u.slice(0)}return r});function j(y){if(i[m]=y,o){const[v,p]=Ne(m);return o[m]=p,s(u[m],v)}return s(u[m])}}}function Bo(e,s,n={}){let a=[],r=[],i=[],l=[],o=0,u;return Lt(()=>ks(i)),()=>{const d=e()||[],h=d.length;return d[An],Te(()=>{if(h===0)return o!==0&&(ks(i),i=[],a=[],r=[],o=0,l=[]),n.fallback&&(a=[sn],r[0]=st(j=>(i[0]=j,n.fallback())),o=1),r;for(a[0]===sn&&(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]=st(m));for(;u<a.length;u++)i[u]();return o=l.length=i.length=h,a=d.slice(0),r=r.slice(0,o)});function m(j){i[u]=j;const[y,v]=Ne(d[u]);return l[u]=v,s(y,u)}}}function Pn(e,s){return Te(()=>e(s||{}))}function xs(){return!0}var nn={get(e,s,n){return s===Ns?n:e.get(s)},has(e,s){return s===Ns?!0:e.has(s)},set:xs,deleteProperty:xs,getOwnPropertyDescriptor(e,s){return{configurable:!0,enumerable:!0,get(){return e.get(s)},set:xs,deleteProperty:xs}},ownKeys(e){return e.keys()}};function Qs(e){return(e=typeof e=="function"?e():e)?e:{}}function Ro(){for(let e=0,s=this.length;e<s;++e){const n=this[e]();if(n!==void 0)return n}}function In(...e){let s=!1;for(let l=0;l<e.length;l++){const o=e[l];s=s||!!o&&Ns in o,e[l]=typeof o=="function"?(s=!0,Le(o)):o}if(Ba&&s)return new Proxy({get(l){for(let o=e.length-1;o>=0;o--){const u=Qs(e[o])[l];if(u!==void 0)return u}},has(l){for(let o=e.length-1;o>=0;o--)if(l in Qs(e[o]))return!0;return!1},keys(){const l=[];for(let o=0;o<e.length;o++)l.push(...Object.keys(Qs(e[o])));return[...new Set(l)]}},nn);const n={},a=Object.create(null);for(let l=e.length-1;l>=0;l--){const o=e[l];if(!o)continue;const u=Object.getOwnPropertyNames(o);for(let d=u.length-1;d>=0;d--){const h=u[d];if(h==="__proto__"||h==="constructor")continue;const m=Object.getOwnPropertyDescriptor(o,h);if(!a[h])a[h]=m.get?{enumerable:!0,configurable:!0,get:Ro.bind(n[h]=[m.get.bind(o)])}:m.value!==void 0?m:void 0;else{const j=n[h];j&&(m.get?j.push(m.get.bind(o)):m.value!==void 0&&j.push(()=>m.value))}}}const r={},i=Object.keys(a);for(let l=i.length-1;l>=0;l--){const o=i[l],u=a[o];u&&u.get?Object.defineProperty(r,o,u):r[o]=u?u.value:void 0}return r}function Va(e,...s){if(Ba&&Ns 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)}},nn));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))}},nn)),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 Ka(e){let s,n;const a=r=>{const i=se.context;if(i){const[o,u]=Ne();se.count||(se.count=0),se.count++,(n||(n=e())).then(d=>{!se.done&&Ut(i),se.count--,u(()=>d.default),Ut()}),s=o}else if(!s){const[o]=vo(()=>(n||(n=e())).then(u=>u.default));s=o}let l;return Le(()=>(l=s())?Te(()=>{if(!i||se.done)return l(r);const o=se.context;Ut(i);const u=l(r);return Ut(o),u}):"")};return a.preload=()=>n||((n=e()).then(r=>s=()=>r.default),n),a}var Mo=0;function Oo(){return se.context?se.getNextContextId():`cl-${Mo++}`}var Ha=e=>`Stale read from <${e}>.`;function Go(e){const s="fallback"in e&&{fallback:()=>e.fallback};return Le(Do(()=>e.each,e.children,s||void 0))}function Uo(e){const s="fallback"in e&&{fallback:()=>e.fallback};return Le(Bo(()=>e.each,e.children,s||void 0))}function Fo(e){const s=e.keyed,n=Le(()=>e.when,void 0,{equals:(a,r)=>s?a===r:!a==!r});return Le(()=>{const a=n();if(a){const r=e.children;return typeof r=="function"&&r.length>0?Te(()=>r(s?a:()=>{if(!Te(n))throw Ha("Show");return e.when})):r}return e.fallback},void 0,void 0)}function qo(e){let s=!1;const n=(i,l)=>(s?i[1]===l[1]:!i[1]==!l[1])&&i[2]===l[2],a=Ua(()=>e.children),r=Le(()=>{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 Le(()=>{const[i,l,o]=r();if(i<0)return e.fallback;const u=o.children;return typeof u=="function"&&u.length>0?Te(()=>u(s?l:()=>{if(Te(r)[0]!==i)throw Ha("Match");return o.when})):u},void 0,void 0)}function $o(e){return e}var zo=["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"],Vo=new Set(["className","value","readOnly","formNoValidate","isMap","noModule","playsInline",...zo]),Ko=new Set(["innerHTML","textContent","innerText","children"]),Ho=Object.assign(Object.create(null),{className:"class",htmlFor:"for"}),Qo=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 Wo(e,s){const n=Qo[e];return typeof n=="object"?n[s]?n.$:void 0:n}var Yo=new Set(["beforeinput","click","dblclick","contextmenu","focusin","focusout","input","keydown","keyup","mousedown","mousemove","mouseout","mouseover","mouseup","pointerdown","pointermove","pointerout","pointerover","pointerup","touchend","touchmove","touchstart"]),Jo=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"]),Xo={xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace"};function Zo(e,s,n){let a=n.length,r=s.length,i=a,l=0,o=0,u=s[r-1].nextSibling,d=null;for(;l<r||o<i;){if(s[l]===n[o]){l++,o++;continue}for(;s[r-1]===n[i-1];)r--,i--;if(r===l){const h=i<a?o?n[o-1].nextSibling:n[i-o]:u;for(;o<i;)e.insertBefore(n[o++],h)}else if(i===o)for(;l<r;)(!d||!d.has(s[l]))&&s[l].remove(),l++;else if(s[l]===n[i-1]&&n[o]===s[r-1]){const h=s[--r].nextSibling;e.insertBefore(n[o++],s[l++].nextSibling),e.insertBefore(n[--i],h),s[r]=n[i]}else{if(!d){d=new Map;let m=o;for(;m<i;)d.set(n[m],m++)}const h=d.get(s[l]);if(h!=null)if(o<h&&h<i){let m=l,j=1,y;for(;++m<r&&m<i&&!((y=d.get(s[m]))==null||y!==h+j);)j++;if(j>h-o){const v=s[l];for(;o<h;)e.insertBefore(n[o++],v)}else e.replaceChild(n[o++],s[l++])}else l++;else s[l++].remove()}}}var zt="_$DX_DELEGATE";function Qa(e,s,n,a={}){let r;return st(i=>{r=i,s===document?e():Is(s,e(),s.firstChild?null:void 0,n)},a.owner),()=>{r(),s.textContent=""}}function ec(e,s,n){let a;const r=()=>{const l=document.createElement("template");return l.innerHTML=e,l.content.firstChild},i=()=>(a||(a=r())).cloneNode(!0);return i.cloneNode=i,i}function Wa(e,s=window.document){const n=s[zt]||(s[zt]=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,er))}}function tc(e=window.document){if(e[zt]){for(let s of e[zt].keys())e.removeEventListener(s,er);delete e[zt]}}function Ps(e,s,n){mt(e)||(n==null?e.removeAttribute(s):e.setAttribute(s,n))}function sc(e,s,n,a){mt(e)||(a==null?e.removeAttributeNS(s,n):e.setAttributeNS(s,n,a))}function nc(e,s,n){mt(e)||(n?e.setAttribute(s,""):e.removeAttribute(s))}function Ya(e,s){mt(e)||(s==null?e.removeAttribute("class"):e.className=s)}function Ja(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 ac(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]||(Vn(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||(Vn(e,o,!0),n[o]=u)}return n}function rc(e,s,n){if(!s)return n?Ps(e,"style"):s;const a=e.style;if(typeof s=="string")return a.cssText=s;typeof n=="string"&&(a.cssText=n=void 0),n||(n={}),s||(s={});let r,i;for(i in n)s[i]==null&&a.removeProperty(i),delete n[i];for(i in s)r=s[i],r!==n[i]&&(a.setProperty(i,r),n[i]=r);return n}function Xa(e,s={},n,a){const r={};return a||nt(()=>r.children=Ht(e,s.children,r.children)),nt(()=>typeof s.ref=="function"&&Za(s.ref,e)),nt(()=>ic(e,s,n,!0,r,!0)),r}function Za(e,s,n){return Te(()=>e(s,n))}function Is(e,s,n,a){if(n!==void 0&&!a&&(a=[]),typeof s!="function")return Ht(e,s,a,n);nt(r=>Ht(e,s(),r,n),a)}function ic(e,s,n,a,r={},i=!1){s||(s={});for(const l in r)if(!(l in s)){if(l==="children")continue;r[l]=Kn(e,l,null,r[l],n,i,s)}for(const l in s){if(l==="children")continue;const o=s[l];r[l]=Kn(e,l,o,r[l],n,i,s)}}function lc(e){let s,n;return!mt()||!(s=se.registry.get(n=cc()))?e():(se.completed&&se.completed.add(s),se.registry.delete(n),s)}function mt(e){return!!se.context&&!se.done&&(!e||e.isConnected)}function oc(e){return e.toLowerCase().replace(/-([a-z])/g,(s,n)=>n.toUpperCase())}function Vn(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 Kn(e,s,n,a,r,i,l){let o,u,d,h,m;if(s==="style")return rc(e,n,a);if(s==="classList")return ac(e,n,a);if(n===a)return a;if(s==="ref")i||n(e);else if(s.slice(0,3)==="on:"){const j=s.slice(3);a&&e.removeEventListener(j,a,typeof a!="function"&&a),n&&e.addEventListener(j,n,typeof n!="function"&&n)}else if(s.slice(0,10)==="oncapture:"){const j=s.slice(10);a&&e.removeEventListener(j,a,!0),n&&e.addEventListener(j,n,!0)}else if(s.slice(0,2)==="on"){const j=s.slice(2).toLowerCase(),y=Yo.has(j);if(!y&&a){const v=Array.isArray(a)?a[0]:a;e.removeEventListener(j,v)}(y||n)&&(Ja(e,j,n,y),y&&Wa([j]))}else if(s.slice(0,5)==="attr:")Ps(e,s.slice(5),n);else if(s.slice(0,5)==="bool:")nc(e,s.slice(5),n);else if((m=s.slice(0,5)==="prop:")||(d=Ko.has(s))||!r&&((h=Wo(s,e.tagName))||(u=Vo.has(s)))||(o=e.nodeName.includes("-")||"is"in l)){if(m)s=s.slice(5),u=!0;else if(mt(e))return n;s==="class"||s==="className"?Ya(e,n):o&&!u&&!d?e[oc(s)]=n:e[h||s]=n}else{const j=r&&s.indexOf(":")>-1&&Xo[s.split(":")[0]];j?sc(e,j,s,n):Ps(e,Ho[s]||s,n)}return n}function er(e){if(se.registry&&se.events&&se.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}}),se.registry&&!se.done&&(se.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 Ht(e,s,n,a,r){const i=mt(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=gt(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=gt(e,n,a)}else{if(l==="function")return nt(()=>{let u=s();for(;typeof u=="function";)u=u();n=Ht(e,u,n,a)}),()=>n;if(Array.isArray(s)){const u=[],d=n&&Array.isArray(n);if(an(u,s,n,r))return nt(()=>n=Ht(e,u,n,a,!0)),()=>n;if(i){if(!u.length)return n;if(a===void 0)return n=[...e.childNodes];let h=u[0];if(h.parentNode!==e)return n;const m=[h];for(;(h=h.nextSibling)!==a;)m.push(h);return n=m}if(u.length===0){if(n=gt(e,n,a),o)return n}else d?n.length===0?Hn(e,u,a):Zo(e,n,u):(n&>(e),Hn(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=gt(e,n,a,s);gt(e,n,null,s)}else n==null||n===""||!e.firstChild?e.appendChild(s):e.replaceChild(s,e.firstChild);n=s}}return n}function an(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=an(e,o,u)||r;else if(d==="function")if(a){for(;typeof o=="function";)o=o();r=an(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 Hn(e,s,n=null){for(let a=0,r=s.length;a<r;a++)e.insertBefore(s[a],n)}function gt(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 cc(){return se.getNextContextId()}var uc="http://www.w3.org/2000/svg";function tr(e,s=!1){return s?document.createElementNS(uc,e):document.createElement(e)}function dc(e){const{useShadow:s}=e,n=document.createTextNode(""),a=()=>e.mount||document.body,r=zn();let i,l=!!se.context;return Tn(()=>{l&&(zn().user=l=!1),i||(i=So(r,()=>Le(()=>e.children)));const o=a();if(o instanceof HTMLHeadElement){const[u,d]=Ne(!1),h=()=>d(!0);st(m=>Is(o,()=>u()?m():i(),null)),Lt(h)}else{const u=tr(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}),Is(d,i),o.appendChild(u),e.ref&&e.ref(u),Lt(()=>o.removeChild(u))}},void 0,{render:!l}),n}function hc(e){const[s,n]=Va(e,["component"]),a=Le(()=>s.component);return Le(()=>{const r=a();switch(typeof r){case"function":return Te(()=>r(n));case"string":const i=Jo.has(r),l=se.context?lc():tr(r,i);return Xa(l,n,i),l}})}var mc=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()}},sr=class{constructor(e){this.generateIdentifier=e,this.kv=new mc}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)}},fc=class extends sr{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 gc(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 xc(e,s){const n=gc(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 Dt(e,s){Object.entries(e).forEach(([n,a])=>s(a,n))}function bs(e,s){return e.indexOf(s)!==-1}function Qn(e,s){for(let n=0;n<e.length;n++){const a=e[n];if(s(a))return a}}var pc=class{constructor(){this.transfomers={}}register(e){this.transfomers[e.name]=e}findApplicable(e){return xc(this.transfomers,s=>s.isApplicable(e))}findByName(e){return this.transfomers[e]}},yc=e=>Object.prototype.toString.call(e).slice(8,-1),nr=e=>typeof e>"u",jc=e=>e===null,Qt=e=>typeof e!="object"||e===null||e===Object.prototype?!1:Object.getPrototypeOf(e)===null?!0:Object.getPrototypeOf(e)===Object.prototype,rn=e=>Qt(e)&&Object.keys(e).length===0,rt=e=>Array.isArray(e),vc=e=>typeof e=="string",bc=e=>typeof e=="number"&&!isNaN(e),wc=e=>typeof e=="boolean",Sc=e=>e instanceof RegExp,Wt=e=>e instanceof Map,Yt=e=>e instanceof Set,ar=e=>yc(e)==="Symbol",Nc=e=>e instanceof Date&&!isNaN(e.valueOf()),Ec=e=>e instanceof Error,Wn=e=>typeof e=="number"&&isNaN(e),Cc=e=>wc(e)||jc(e)||nr(e)||bc(e)||vc(e)||ar(e),Ac=e=>typeof e=="bigint",Tc=e=>e===1/0||e===-1/0,kc=e=>ArrayBuffer.isView(e)&&!(e instanceof DataView),Pc=e=>e instanceof URL,rr=e=>e.replace(/\./g,"\\."),Ws=e=>e.map(String).map(rr).join("."),Vt=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 ze(e,s,n,a){return{isApplicable:e,annotation:s,transform:n,untransform:a}}var ir=[ze(nr,"undefined",()=>null,()=>{}),ze(Ac,"bigint",e=>e.toString(),e=>typeof BigInt<"u"?BigInt(e):e),ze(Nc,"Date",e=>e.toISOString(),e=>new Date(e)),ze(Ec,"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}),ze(Sc,"regexp",e=>""+e,e=>{const s=e.slice(1,e.lastIndexOf("/")),n=e.slice(e.lastIndexOf("/")+1);return new RegExp(s,n)}),ze(Yt,"set",e=>[...e.values()],e=>new Set(e)),ze(Wt,"map",e=>[...e.entries()],e=>new Map(e)),ze(e=>Wn(e)||Tc(e),"number",e=>Wn(e)?"NaN":e>0?"Infinity":"-Infinity",Number),ze(e=>e===0&&1/e===-1/0,"number",()=>"-0",Number),ze(Pc,"URL",e=>e.toString(),e=>new URL(e))];function Os(e,s,n,a){return{isApplicable:e,annotation:s,transform:n,untransform:a}}var lr=Os((e,s)=>ar(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}),Ic=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,Uint8ClampedArray].reduce((e,s)=>(e[s.name]=s,e),{}),or=Os(kc,e=>["typed-array",e.constructor.name],e=>[...e],(e,s)=>{const n=Ic[s[1]];if(!n)throw new Error("Trying to deserialize unknown typed array");return new n(e)});function cr(e,s){return e!=null&&e.constructor?!!s.classRegistry.getIdentifier(e.constructor):!1}var ur=Os(cr,(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)}),dr=Os((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)}),_c=[ur,lr,dr,or],Yn=(e,s)=>{const n=Qn(_c,r=>r.isApplicable(e,s));if(n)return{value:n.transform(e,s),type:n.annotation(e,s)};const a=Qn(ir,r=>r.isApplicable(e,s));if(a)return{value:a.transform(e,s),type:a.annotation}},hr={};ir.forEach(e=>{hr[e.annotation]=e});var Lc=(e,s,n)=>{if(rt(s))switch(s[0]){case"symbol":return lr.untransform(e,s,n);case"class":return ur.untransform(e,s,n);case"custom":return dr.untransform(e,s,n);case"typed-array":return or.untransform(e,s,n);default:throw new Error("Unknown transformation: "+s)}else{const a=hr[s];if(!a)throw new Error("Unknown transformation: "+s);return a.untransform(e,n)}},pt=(e,s)=>{const n=e.keys();for(;s>0;)n.next(),s--;return n.next().value};function mr(e){if(bs(e,"__proto__"))throw new Error("__proto__ is not allowed as a property");if(bs(e,"prototype"))throw new Error("prototype is not allowed as a property");if(bs(e,"constructor"))throw new Error("constructor is not allowed as a property")}var Dc=(e,s)=>{mr(s);for(let n=0;n<s.length;n++){const a=s[n];if(Yt(e))e=pt(e,+a);else if(Wt(e)){const r=+a,i=+s[++n]==0?"key":"value",l=pt(e,r);switch(i){case"key":e=l;break;case"value":e=e.get(l);break}}else e=e[a]}return e},ln=(e,s,n)=>{if(mr(s),s.length===0)return n(e);let a=e;for(let i=0;i<s.length-1;i++){const l=s[i];if(rt(a)){const o=+l;a=a[o]}else if(Qt(a))a=a[l];else if(Yt(a)){const o=+l;a=pt(a,o)}else if(Wt(a)){if(i===s.length-2)break;const u=+l,d=+s[++i]==0?"key":"value",h=pt(a,u);switch(d){case"key":a=h;break;case"value":a=a.get(h);break}}}const r=s[s.length-1];if(rt(a)?a[+r]=n(a[+r]):Qt(a)&&(a[r]=n(a[r])),Yt(a)){const i=pt(a,+r),l=n(i);i!==l&&(a.delete(i),a.add(l))}if(Wt(a)){const i=+s[s.length-2],l=pt(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 on(e,s,n=[]){if(!e)return;if(!rt(e)){Dt(e,(i,l)=>on(i,s,[...n,...Vt(l)]));return}const[a,r]=e;r&&Dt(r,(i,l)=>{on(i,s,[...n,...Vt(l)])}),s(a,n)}function Bc(e,s,n){return on(s,(a,r)=>{e=ln(e,r,i=>Lc(i,a,n))}),e}function Rc(e,s){function n(a,r){const i=Dc(e,Vt(r));a.map(Vt).forEach(l=>{e=ln(e,l,()=>i)})}if(rt(s)){const[a,r]=s;a.forEach(i=>{e=ln(e,Vt(i),()=>e)}),r&&Dt(r,n)}else Dt(s,n);return e}var Mc=(e,s)=>Qt(e)||rt(e)||Wt(e)||Yt(e)||cr(e,s);function Oc(e,s,n){const a=n.get(e);a?a.push(s):n.set(e,[s])}function Gc(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(Ws):n[Ws(i)]=l.map(Ws)}),a?rn(n)?[a]:[a,n]:rn(n)?void 0:n}var fr=(e,s,n,a,r=[],i=[],l=new Map)=>{const o=Cc(e);if(!o){Oc(e,r,s);const y=l.get(e);if(y)return a?{transformedValue:null}:y}if(!Mc(e,n)){const y=Yn(e,n),v=y?{transformedValue:y.value,annotations:[y.type]}:{transformedValue:e};return o||l.set(e,v),v}if(bs(i,e))return{transformedValue:null};const u=Yn(e,n),d=(u==null?void 0:u.value)??e,h=rt(d)?[]:{},m={};Dt(d,(y,v)=>{if(v==="__proto__"||v==="constructor"||v==="prototype")throw new Error(`Detected property ${v}. This is a prototype pollution risk, please remove it from your object.`);const p=fr(y,s,n,a,[...r,v],[...i,e],l);h[v]=p.transformedValue,rt(p.annotations)?m[v]=p.annotations:Qt(p.annotations)&&Dt(p.annotations,(b,S)=>{m[rr(v)+"."+S]=b})});const j=rn(m)?{transformedValue:h,annotations:u?[u.type]:void 0}:{transformedValue:h,annotations:u?[u.type,m]:m};return o||l.set(e,j),j};function gr(e){return Object.prototype.toString.call(e).slice(8,-1)}function Jn(e){return gr(e)==="Array"}function Uc(e){if(gr(e)!=="Object")return!1;const s=Object.getPrototypeOf(e);return!!s&&s.constructor===Object&&s===Object.prototype}function Fc(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 cn(e,s={}){if(Jn(e))return e.map(r=>cn(r,s));if(!Uc(e))return e;const n=Object.getOwnPropertyNames(e),a=Object.getOwnPropertySymbols(e);return[...n,...a].reduce((r,i)=>{if(Jn(s.props)&&!s.props.includes(i))return r;const l=e[i],o=cn(l,s);return Fc(r,i,o,e,s.nonenumerable),r},{})}var ve=class{constructor({dedupe:e=!1}={}){this.classRegistry=new fc,this.symbolRegistry=new sr(s=>s.description??""),this.customTransformerRegistry=new pc,this.allowedErrorProps=[],this.dedupe=e}serialize(e){const s=new Map,n=fr(e,s,this,this.dedupe),a={json:n.transformedValue};n.annotations&&(a.meta={...a.meta,values:n.annotations});const r=Gc(s,this.dedupe);return r&&(a.meta={...a.meta,referentialEqualities:r}),a}deserialize(e){const{json:s,meta:n}=e;let a=cn(s);return n!=null&&n.values&&(a=Bc(a,n.values,this)),n!=null&&n.referentialEqualities&&(a=Rc(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)}};ve.defaultInstance=new ve;ve.serialize=ve.defaultInstance.serialize.bind(ve.defaultInstance);ve.deserialize=ve.defaultInstance.deserialize.bind(ve.defaultInstance);ve.stringify=ve.defaultInstance.stringify.bind(ve.defaultInstance);ve.parse=ve.defaultInstance.parse.bind(ve.defaultInstance);ve.registerClass=ve.defaultInstance.registerClass.bind(ve.defaultInstance);ve.registerSymbol=ve.defaultInstance.registerSymbol.bind(ve.defaultInstance);ve.registerCustom=ve.defaultInstance.registerCustom.bind(ve.defaultInstance);ve.allowErrorProps=ve.defaultInstance.allowErrorProps.bind(ve.defaultInstance);var xr=ve.serialize,qc=ve.stringify;function $c(e){return e.state.fetchStatus==="fetching"?"fetching":e.getObserversCount()?e.state.fetchStatus==="paused"?"paused":e.isStale()?"stale":"fresh":"inactive"}function zc(e,s){return`${e}${s.charAt(0).toUpperCase()+s.slice(1)}`}function Vc({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 Hc(e){return e==="fresh"?"green":e==="stale"?"yellow":e==="paused"?"purple":e==="inactive"?"gray":"blue"}var Qc=(e,s=!1)=>{const{json:n}=xr(e);return JSON.stringify(n,null,s?2:void 0)},ps=e=>e.state.fetchStatus!=="idle"?0:e.getObserversCount()?e.isStale()?2:1:3,Wc=(e,s)=>e.queryHash.localeCompare(s.queryHash),pr=(e,s)=>e.state.dataUpdatedAt<s.state.dataUpdatedAt?1:-1,Yc=(e,s)=>ps(e)===ps(s)?pr(e,s):ps(e)>ps(s)?1:-1,Jc={status:Yc,"query hash":Wc,"last updated":pr},ys=e=>e.state.isPaused?0:e.state.status==="error"?2:e.state.status==="pending"?1:3,yr=(e,s)=>e.state.submittedAt<s.state.submittedAt?1:-1,Xc=(e,s)=>ys(e)===ys(s)?yr(e,s):ys(e)>ys(s)?1:-1,Zc={status:Xc,"last updated":yr},eu=e=>e*parseFloat(getComputedStyle(document.documentElement).fontSize),tu=()=>{const[e,s]=Ne("dark");return Ga(()=>{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),Lt(()=>n.removeEventListener("change",a))}),e},Ft=(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,Ft(a.get(r),i,n)),a}if(e instanceof Set){const a=Ft(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]=Ft(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]=Ft(a[r],i,n),a}return e},qt=(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,qt(n.get(a),r)),n}if(e instanceof Set){const n=qt(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]=qt(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]=qt(n[a],r),n}return e},jr=(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)},yt,Jt,Xt,Zt,ct,es,jt,vt,bt,wt,St,Nt,ts,ea,su=(ea=class{constructor(e){pe(this,yt);pe(this,Jt);pe(this,Xt);pe(this,Zt);pe(this,ct,!1);pe(this,es);pe(this,jt);pe(this,vt);pe(this,bt);pe(this,wt);pe(this,St);pe(this,Nt);pe(this,ts);const{client:s,queryFlavor:n,version:a,onlineManager:r,buttonPosition:i,position:l,initialIsOpen:o,errorTypes:u,styleNonce:d,shadowDOMTarget:h}=e;ge(this,yt,Ne(s)),ge(this,Xt,n),ge(this,Zt,a),ge(this,Jt,r),ge(this,es,d),ge(this,jt,h),ge(this,vt,Ne(i)),ge(this,bt,Ne(l)),ge(this,wt,Ne(o)),ge(this,St,Ne(u))}setButtonPosition(e){ee(this,vt)[1](e)}setPosition(e){ee(this,bt)[1](e)}setInitialIsOpen(e){ee(this,wt)[1](e)}setErrorTypes(e){ee(this,St)[1](e)}setClient(e){ee(this,yt)[1](e)}mount(e){if(ee(this,ct))throw new Error("Devtools is already mounted");const s=Qa(()=>{const n=this,[a]=ee(this,vt),[r]=ee(this,bt),[i]=ee(this,wt),[l]=ee(this,St),[o]=ee(this,yt);let u;return ee(this,Nt)?u=ee(this,Nt):(u=Ka(()=>Promise.resolve().then(()=>require("./HO4MOOFI-GguExgYj.cjs"))),ge(this,Nt,u)),jr(ee(this,es),ee(this,jt)),Pn(u,In({get queryFlavor(){return ee(n,Xt)},get version(){return ee(n,Zt)},get onlineManager(){return ee(n,Jt)},get shadowDOMTarget(){return ee(n,jt)}},{get client(){return o()},get buttonPosition(){return a()},get position(){return r()},get initialIsOpen(){return i()},get errorTypes(){return l()}}))},e);ge(this,ct,!0),ge(this,ts,s)}unmount(){var e;if(!ee(this,ct))throw new Error("Devtools is not mounted");(e=ee(this,ts))==null||e.call(this),ge(this,ct,!1)}},yt=new WeakMap,Jt=new WeakMap,Xt=new WeakMap,Zt=new WeakMap,ct=new WeakMap,es=new WeakMap,jt=new WeakMap,vt=new WeakMap,bt=new WeakMap,wt=new WeakMap,St=new WeakMap,Nt=new WeakMap,ts=new WeakMap,ea),Et,ss,ns,as,ut,rs,Ct,At,Tt,kt,Pt,It,_t,is,ta,nu=(ta=class{constructor(e){pe(this,Et);pe(this,ss);pe(this,ns);pe(this,as);pe(this,ut,!1);pe(this,rs);pe(this,Ct);pe(this,At);pe(this,Tt);pe(this,kt);pe(this,Pt);pe(this,It);pe(this,_t);pe(this,is);const{client:s,queryFlavor:n,version:a,onlineManager:r,buttonPosition:i,position:l,initialIsOpen:o,errorTypes:u,styleNonce:d,shadowDOMTarget:h,onClose:m}=e;ge(this,Et,Ne(s)),ge(this,ns,n),ge(this,as,a),ge(this,ss,r),ge(this,rs,d),ge(this,Ct,h),ge(this,At,Ne(i)),ge(this,Tt,Ne(l)),ge(this,kt,Ne(o)),ge(this,Pt,Ne(u)),ge(this,It,Ne(m))}setButtonPosition(e){ee(this,At)[1](e)}setPosition(e){ee(this,Tt)[1](e)}setInitialIsOpen(e){ee(this,kt)[1](e)}setErrorTypes(e){ee(this,Pt)[1](e)}setClient(e){ee(this,Et)[1](e)}setOnClose(e){ee(this,It)[1](()=>e)}mount(e){if(ee(this,ut))throw new Error("Devtools is already mounted");const s=Qa(()=>{const n=this,[a]=ee(this,At),[r]=ee(this,Tt),[i]=ee(this,kt),[l]=ee(this,Pt),[o]=ee(this,Et),[u]=ee(this,It);let d;return ee(this,_t)?d=ee(this,_t):(d=Ka(()=>Promise.resolve().then(()=>require("./HUY7CZI3-Dehg317s.cjs"))),ge(this,_t,d)),jr(ee(this,rs),ee(this,Ct)),Pn(d,In({get queryFlavor(){return ee(n,ns)},get version(){return ee(n,as)},get onlineManager(){return ee(n,ss)},get shadowDOMTarget(){return ee(n,Ct)}},{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);ge(this,ut,!0),ge(this,is,s)}unmount(){var e;if(!ee(this,ut))throw new Error("Devtools is not mounted");(e=ee(this,is))==null||e.call(this),ge(this,ut,!1)}},Et=new WeakMap,ss=new WeakMap,ns=new WeakMap,as=new WeakMap,ut=new WeakMap,rs=new WeakMap,Ct=new WeakMap,At=new WeakMap,Tt=new WeakMap,kt=new WeakMap,Pt=new WeakMap,It=new WeakMap,_t=new WeakMap,is=new WeakMap,ta);function au(e){const s=F.useQueryClient(e.client),n=Se.useRef(null),{buttonPosition:a,position:r,initialIsOpen:i,errorTypes:l,styleNonce:o,shadowDOMTarget:u}=e,[d]=Se.useState(new su({client:s,queryFlavor:"React Query",version:"5",onlineManager:F.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 ru(e){const s=F.useQueryClient(e.client),n=Se.useRef(null),{errorTypes:a,styleNonce:r,shadowDOMTarget:i}=e,[l]=Se.useState(new nu({client:s,queryFlavor:"React Query",version:"5",onlineManager:F.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 iu=process.env.NODE_ENV!=="development"?function(){return null}:au;process.env.NODE_ENV;const lu=()=>{$.registerChaiFeatureFlag("dynamic-page-selector",{description:"Dynamic page selector"}),$.registerChaiFeatureFlag("enable-add-page-dropdown",{description:"Enable add page dropdown"}),$.registerChaiFeatureFlag("enable-page-revisions-compare",{description:"Page revisions compare"}),$.registerChaiFeatureFlag("enable-old-page-manager",{description:"Switch to older page manager"}),$.registerChaiFeatureFlag("enable-site-settings",{description:"Site settings"})},ou=()=>{const e=le(),s=X();return F.useQuery({queryKey:[D.GET_COLLECTIONS],initialData:[],queryFn:async()=>s(e,{action:D.GET_COLLECTIONS})})},cu=()=>{const{data:e}=ke(),{data:s}=We(),{data:n}=Ke(),a=le(),r=X(),i=g.useMemo(()=>(n==null?void 0:n.fallbackLang)||"en",[n==null?void 0:n.fallbackLang]);return F.useMutation({mutationFn:async({block:l})=>r(a,{action:D.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}}})})},vr=()=>{const e=jn();return g.useCallback(({pageId:s})=>{e(s)},[e])},uu=()=>{const e=ls(),s=F.useQueryClient(),n=X();return F.useMutation({mutationFn:async({file:a,folderId:r,name:i,optimize:l=!0})=>n(e,{action:D.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:[D.GET_ASSETS]}),W.toast.success("Asset uploaded successfully")},onError:()=>{W.toast.error("Failed to upload asset")}})},du=()=>{const e=ls(),s=F.useQueryClient(),n=X();return F.useMutation({mutationFn:async a=>n(e,{action:D.DELETE_ASSET,data:{id:a}}),onSuccess:a=>{if(a!=null&&a.error)throw new Error(a==null?void 0:a.error);s.invalidateQueries({queryKey:[D.GET_ASSETS]}),W.toast.success("Asset deleted successfully")},onError:()=>{W.toast.error("Failed to delete asset")}})},hu=()=>{const e=ls(),s=F.useQueryClient(),n=X();return F.useMutation({mutationFn:async a=>n(e,{action:D.UPDATE_ASSET,data:a}),onSuccess:a=>{if(a!=null&&a.error)throw new Error(a==null?void 0:a.error);s.invalidateQueries({queryKey:[D.GET_ASSETS]}),W.toast.success("Asset updated successfully")},onError:()=>{W.toast.error("Failed to update asset")}})},mu=(e={})=>{const s=ls(),n=X(),{search:a,page:r=1,limit:i=30}=e;return F.useQuery({queryKey:[D.GET_ASSETS,a,r,i],queryFn:async()=>{const l=await n(s,{action:D.GET_ASSETS,data:{search:a,page:r,limit:i}});return l.page=r,l.limit=i,l},staleTime:1e3*60*5,retry:1})},fu=e=>{const s=ls(),n=X();return F.useQuery({queryKey:[D.GET_ASSET,e],queryFn:async()=>e?await n(s,{action:D.GET_ASSET,data:{id:e}}):null,staleTime:1e3*60*5,retry:1})};function gu(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 Xn(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 xu=({assetId:e,onBack:s,onEdit:n,onSave:a,isSaving:r})=>{var m,j,y;const{data:i,isLoading:l,isError:o}=fu(e||""),[u,d]=g.useState(""),h=async(v,p)=>{try{await navigator.clipboard.writeText(v),W.toast.success(`${p} copied to clipboard`)}catch(b){W.toast.error(`Failed to copy ${p}`,{description:b==null?void 0:b.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=${((m=i.metadata)==null?void 0:m.updatedAt)||i.createdAt}`,alt:i.name,className:"w-full h-full object-contain rounded-lg max-h-max max-w-max"})}),t.jsxs("div",{className:"space-y-6",children:[t.jsxs("div",{className:"grid gap-3 border rounded-md pt-2 bg-gray-100",children:[t.jsx(c.Label,{className:"w-full text-center",children:"Details"}),t.jsx("div",{className:"grid grid-cols-1 gap-2 text-sm border rounded-md p-2 bg-white",children:[{label:"File Name",value:i.name},{label:"Type",value:i.type,capitalize:!0},{label:"Format",value:((j=i.metadata)==null?void 0:j.format)||i.type,capitalize:!0},{label:"Size",value:gu(i.size)},{label:"Dimensions",value:`${i.width||0} × ${i.height||0}`},{label:"Created",value:Xn(i.createdAt)},{label:"Updated",value:Xn(((y=i.metadata)==null?void 0:y.updatedAt)||i.createdAt)},{label:"URL",value:i.url,copyable:!0}].map(v=>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:v.label}),":",t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("div",{className:"w-max text-left font-medium text-gray-900"+(v.capitalize?" capitalize":""),children:v.value}),v.copyable&&t.jsx(c.Button,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>h(v.value,v.label),children:t.jsx(N.Link,{className:"h-3 w-3"})})]})]},v.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((v,p)=>t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("div",{className:"w-max text-left font-medium text-gray-900",children:v.name}),t.jsxs("div",{className:"text-gray-500",children:["(",v.slug,")"]})]},p))})]}),t.jsxs("div",{className:"grid gap-3 border rounded-md pt-2 bg-gray-100 relative",children:[t.jsx(c.Label,{className:"w-full text-center",children:"Description"}),t.jsx(c.Textarea,{id:"description",value:u,placeholder:"Enter a description for the asset",onChange:v=>d(v.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"})})]})]})]})]})},pu=g.lazy(()=>Promise.resolve().then(()=>require("./image-editor-BWLJT1mr.cjs")));function yu(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 ju=({isUpdatingAsset:e,allowedTypes:s,maxFileSize:n,uploadAsset:a,isUploadingAsset:r,onUploaded:i})=>{const[l,o]=g.useState(()=>{const y=localStorage.getItem("chai_optimize_images");return y!==null?y==="true":!0});g.useEffect(()=>{localStorage.setItem("chai_optimize_images",l.toString())},[l]);const u=e||r,d=g.useCallback(async y=>new Promise((v,p)=>{const b=y[0],S=new FileReader;S.readAsDataURL(b),S.onload=async()=>{a({file:S.result,folderId:void 0,name:b.name,optimize:l},{onSuccess:E=>{i&&i(E),v(E)},onError:E=>{p(E)}})},S.onerror=E=>p(E)}),[a,l,i]),{getRootProps:h,getInputProps:m,isDragActive:j}=Cr.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:$.mergeClasses("rounded-lg text-center cursor-pointer w-full h-max flex flex-col justify-center",u?"items-start":"items-center",j?"border-primary bg-primary/5":"border-muted-foreground/20"),children:[t.jsx("input",{...m()}),u?t.jsx("div",{className:"flex flex-col items-center px-6",children:t.jsxs("div",{className:"leading-tight flex items-center justify-center gap-2",children:[t.jsx("div",{className:"flex items-center justify-center rounded-full bg-indigo-100 p-2",children:t.jsx(N.Loader,{className:"h-4 w-4 text-indigo-500 animate-spin"})}),t.jsxs("div",{className:"text-left",children:[t.jsx("div",{className:"font-medium",children:e?"Updating file...":"Uploading file..."}),t.jsxs("div",{className:"text-xs text-muted-foreground font-light",children:["Please wait while we ",e?"update":"upload"," ","your file..."]})]})]})}):t.jsxs("div",{className:"flex items-center justify-between w-full px-6",children:[t.jsx("div",{className:"flex flex-col items-center",children:t.jsxs("div",{className:"leading-tight flex items-center justify-between gap-2",children:[t.jsx("div",{className:"flex items-center justify-center rounded-full bg-indigo-100 p-2 border border-indigo-500",children:t.jsx(N.Upload,{className:"h-4 w-4 text-indigo-500"})}),t.jsxs("div",{className:"text-left",children:[t.jsxs("div",{className:"font-medium",children:["Drop your file here or"," ",t.jsx("span",{className:"text-indigo-500 cursor-pointer hover:underline",children:"browse"})]}),t.jsxs("div",{className:"text-xs text-muted-foreground font-light",children:[t.jsxs("span",{className:"",children:["Accepted file types:"," ",t.jsx("span",{className:"capitalize text-indigo-400",children:s.join(", ")})," & "]}),t.jsxs("span",{children:["Max file size:"," ",t.jsxs("span",{className:"capitalize text-indigo-400",children:[n," MB"]})]})]})]})]})}),t.jsxs("div",{className:"text-xs text-muted-foreground flex items-center gap-2",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsxs("span",{className:"text-xs",children:["Optimization:"," ",t.jsx("span",{className:l?"text-indigo-600":"text-gray-400",children:l?"On":"Off"})]}),t.jsx(c.Switch,{checked:l,onCheckedChange:y=>{o(y)},onClick:y=>{y.stopPropagation()},className:"data-[state=checked]:bg-indigo-500"})]}),t.jsx(c.TooltipProvider,{children:t.jsxs(c.Tooltip,{children:[t.jsx(c.TooltipTrigger,{asChild:!0,children:t.jsx("span",{className:`text-amber-500 flex items-center cursor-help ${l?"invisible":""}`,children:t.jsx(N.AlertTriangle,{className:"h-4 w-4 mr-1"})})}),t.jsx(c.TooltipContent,{side:"top",children:t.jsxs("p",{className:"text-white text-xs",children:["Warning: Unoptimized images may affect ",t.jsx("br",{})," performance and page load times"]})})]})})]})]})]})})};function br({close:e,onSelect:s,mode:n="image",assetId:a}){const l=g.useMemo(()=>[n],[n]),[o,u]=g.useState(null),[d,h]=g.useState(null),[m,j]=g.useState(null),[y,v]=g.useState({show:!1,file:""}),[p,b]=g.useState(!1),[S,E]=g.useState(a?"details":"grid"),[L,I]=g.useState(""),[k,T]=g.useState(""),[V,ne]=g.useState(1),[Y]=g.useState(30),[_,M]=g.useState([]);g.useEffect(()=>{a&&(u(a),E("details"))},[a]),g.useEffect(()=>{const G=setTimeout(()=>{I(k),ne(1)},300);return()=>clearTimeout(G)},[k]);const{data:Q,isLoading:R}=mu({search:L.toLowerCase().trim(),page:V,limit:Y}),Z=(Q==null?void 0:Q.assets)||[],K=(Q==null?void 0:Q.total)||0,te=Math.ceil(K/Y),ue=V<te,he=V>1,oe=(Z==null?void 0:Z.length)>0,{mutate:w}=du(),{mutate:x,isPending:P}=uu(),{mutate:U,isPending:C}=hu(),B=g.useCallback(G=>{G>=1&&G<=te&&ne(G)},[te]),O=g.useCallback(()=>{ue&&B(V+1)},[V,ue,B]),z=g.useCallback(()=>{he&&B(V-1)},[V,he,B]),J=G=>{T(G.target.value)},ce=g.useCallback(G=>{M(q=>f.find(q,{id:G.id})?[]:[G])},[!1]),H=g.useCallback(()=>{M([])},[]),ae=G=>{(G==null?void 0:G.length)!==0&&(s(f.pick(f.first(G||_),["id","url","width","height","description"])),e())},me=async G=>{h(G)},xe=async()=>{d&&(j(d==null?void 0:d.id),await w(d.id,{onSuccess:()=>{j(null),h(null)},onError:()=>{j(null)}}),h(null))},ie=G=>{u(G.id),E("details")},Ce=async(G,q)=>{try{const be=localStorage.getItem("chai_optimize_images")!=="false";q?(await x({file:G,folderId:void 0,name:y.name||"",optimize:be}),v({show:!1,file:""})):(await U({id:y.id||"",file:G}),v({show:!1,file:""}))}catch(be){console.error("Error saving edited image:",be)}},_e=g.useCallback(G=>{M([G])},[]);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(ju,{maxFileSize:10,allowedTypes:l,uploadAsset:x,isUpdatingAsset:C,isUploadingAsset:P,onUploaded:_e}),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 ${k.length>0?"text-indigo-800":""}`}),t.jsx(c.Input,{placeholder:"Search assets...",onChange:J,value:k,className:"pl-8"})]}),_.length>0?t.jsx("div",{className:"flex justify-between items-center",children:t.jsxs("div",{className:"flex items-center gap-2",children:[_.length>0&&t.jsx(t.Fragment,{children:t.jsx(c.Button,{variant:"outline",size:"sm",onClick:()=>H(),title:"Clear selection",children:"Clear"})}),t.jsx(c.Button,{size:"sm",onClick:()=>ae(_),disabled:_.length===0,children:"Select Asset"})]})}):null]}),t.jsx("div",{className:"flex-1 overflow-y-auto pb-[66px]",children:R?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"})]}):!R&&!oe?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:L.length>0?"No assets found for your search: "+L:"Start uploading assets to get started"}),t.jsx("br",{})]}):t.jsx("div",{className:"flex flex-wrap gap-3 p-1",children:Z==null?void 0:Z.map(G=>t.jsxs("div",{className:$.mergeClasses("relative cursor-pointer overflow-hidden transition-all rounded-lg border-2 group max-w-[180px] max-h-[180px] flex flex-col justify-between",_.some(q=>q.id===G.id)?"border-blue-500":"hover:border-black/90",m&&(d==null?void 0:d.id)===G.id?"opacity-50 pointer-events-none":"",m===G.id?"opacity-50 pointer-events-none":""),onClick:()=>ce(G),onDoubleClick:()=>ae([G]),children:[t.jsxs("div",{className:"aspect-square relative overflow-hidden",children:[m===G.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,G.type==="image"?t.jsx("img",{src:`${G.thumbnailUrl||"/placeholder.svg"}?v=${(G==null?void 0:G.updatedAt)||G.createdAt}`,alt:G.name,className:`object-contain w-full h-full min-h-[80px] ${_.some(q=>q.id===G.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"}),G.thumbnailUrl&&t.jsx("img",{src:`${G.thumbnailUrl||"/placeholder.svg"}?v=${(G==null?void 0:G.updatedAt)||G.createdAt}`,alt:G.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:G.name,children:G.name}),t.jsx("div",{className:"text-[9px] whitespace-nowrap font-light text-muted-foreground flex items-center justify-between",children:t.jsx("span",{children:yu((G==null?void 0:G.size)||0)})})]}),!_.some(q=>q.id===G.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:q=>{q.stopPropagation(),ie(G)},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:q=>{q.stopPropagation(),navigator.clipboard.writeText(G.url),W.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:q=>{q.stopPropagation(),v({id:G.id,show:!0,file:G.url,name:G.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:q=>{q.stopPropagation(),me(G)},children:t.jsx(N.Trash2,{className:"h-4 w-4"})})}),t.jsx(c.TooltipContent,{children:t.jsx("p",{children:"Delete Asset"})})]})})]})}),_.some(q=>q.id===G.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})})]},G.id))})}),te>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:z,disabled:!he,children:"Previous"}),Array.from({length:Math.min(5,te)},(G,q)=>{const be=q+1;return t.jsx(c.Button,{variant:V===be?"default":"outline",size:"sm",onClick:()=>B(be),children:be},be)}),te>5&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"text-muted-foreground",children:"..."}),t.jsx(c.Button,{variant:V===te?"default":"outline",size:"sm",onClick:()=>B(te),children:te})]}),t.jsx(c.Button,{variant:"outline",size:"sm",onClick:O,disabled:!ue,children:"Next"})]})})]})]}):t.jsx(xu,{assetId:o||a||"",onBack:()=>{E("grid"),u(null)},onEdit:G=>{v({id:G.id,show:!0,file:G.url,name:G.name})},onSave:async G=>{if(o){b(!0);try{const q=Z.find(be=>be.id===o);q&&await U(f.merge(q,{description:G}))}finally{b(!1)}}},isSaving:p})]}),y.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(pu,{imageUrl:y.file,onSave:Ce,onClose:()=>v({show:!1,file:""}),defaultSavedImageName:y.name,isEditing:!!y.id})}),d&&t.jsx(c.Dialog,{open:!!d,onOpenChange:()=>h(null),children:t.jsxs(c.DialogContent,{children:[t.jsxs(c.DialogHeader,{children:[t.jsx(c.DialogTitle,{children:"Delete Asset"}),t.jsxs(c.DialogDescription,{children:['Are you sure you want to delete "',d.name,'"? This action cannot be undone.']})]}),t.jsxs(c.DialogFooter,{className:"gap-2 sm:gap-0",children:[t.jsx(c.Button,{variant:"outline",onClick:()=>h(null),children:"Cancel"}),t.jsx(c.Button,{variant:"destructive",onClick:xe,children:"Delete"})]})]})})]})}const vu=Object.freeze(Object.defineProperty({__proto__:null,default:br},Symbol.toStringTag,{value:"Module"})),_s=({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=j=>{const y=Array.isArray(j)?j[0]:j;y!=null&&y.url&&n(f.pick(y,["url","id"])),o(!1)},m=()=>{n({url:"",id:""})};return t.jsxs("div",{className:`w-full ${a}`,children:[s?t.jsxs("div",{className:"relative border rounded-md overflow-hidden",children:[t.jsx("img",{onClick:u,src:s,alt:"Selected image",className:"w-full h-auto bg-gray-300 object-contain max-h-[100px]"}),t.jsxs("div",{className:"absolute top-2 right-2 flex gap-2",children:[t.jsx(c.Button,{type:"button",variant:"destructive",size:"icon",className:"h-8 w-8 rounded-full bg-white/80 text-red-500 hover:bg-white/90",onClick:m,disabled:i,children:t.jsx(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(br,{close:d,onSelect:h,mode:"image",assetId:e})})]})})]})},bu=({isActive:e,onClick:s})=>t.jsx(c.Button,{variant:e?"default":"ghost",className:"w-full justify-start text-left",onClick:s,children:"Branding"}),wu=()=>{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:"rounded space-y-3",children:[t.jsxs("div",{children:[t.jsx("label",{className:"text-sm font-medium block mb-1",children:"Logo"}),t.jsx(_s,{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(_s,{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"})})]})]})},Su=({isActive:e,onClick:s})=>t.jsx(c.Button,{variant:e?"default":"ghost",className:"w-full justify-start text-left",onClick:s,children:"Contact & Social"}),Nu=()=>{const[e,s]=g.useState({contactEmail:"",contactPhone:"",contactAddress:""}),[n,a]=g.useState([]),[r,i]=g.useState({isOpen:!1,platform:"",url:"",customName:""}),[l,o]=g.useState(!1),u=[{value:"facebook",label:"Facebook"},{value:"twitter",label:"Twitter"},{value:"linkedin",label:"LinkedIn"},{value:"instagram",label:"Instagram"},{value:"youtube",label:"YouTube"},{value:"other",label:"Other"}],d=p=>s(b=>({...b,[p.target.name]:p.target.value})),h=()=>{const{platform:p,url:b,customName:S}=r;if(!b.trim()||!p)return;const E=p==="other"?S:p;E.trim()&&(a(L=>[...L,{platform:E,url:b,isCustom:p==="other"}]),i({isOpen:!1,platform:"",url:"",customName:""}))},m=p=>a(b=>b.filter((S,E)=>E!==p)),j=()=>i({isOpen:!1,platform:"",url:"",customName:""}),y=()=>{o(!0);const p={};n.forEach(S=>{p[S.platform.toLowerCase().replace(/\s+/g,"_")]=S.url});const b={...e,socialLinks:p};setTimeout(()=>{o(!1),console.log("Contact & Social settings saved:",b),s({contactEmail:"",contactPhone:"",contactAddress:""}),a([]),i({isOpen:!1,platform:"",url:"",customName:""})},1e3)},v=e.contactEmail.trim()||e.contactPhone.trim()||e.contactAddress.trim();return t.jsxs("div",{className:"space-y-4",children:[t.jsx("h2",{className:"text-lg font-medium",children:"Contact & Social Settings"}),t.jsxs("div",{className:"space-y-4 rounded",children:[t.jsxs("div",{className:"space-y-3",children:[t.jsxs("div",{children:[t.jsx("label",{className:"mb-1 block text-sm font-medium",children:"Contact Email"}),t.jsx("input",{type:"email",name:"contactEmail",value:e.contactEmail,onChange:d,className:"input-border w-full rounded px-3 py-1 text-sm",placeholder:"contact@example.com"})]}),t.jsxs("div",{children:[t.jsx("label",{className:"mb-1 block text-sm font-medium",children:"Contact Phone"}),t.jsx("input",{type:"tel",name:"contactPhone",value:e.contactPhone,onChange:d,className:"input-border w-full rounded px-3 py-1 text-sm",placeholder:"+1 (555) 123-4567"})]}),t.jsxs("div",{children:[t.jsx("label",{className:"mb-1 block text-sm font-medium",children:"Contact Address"}),t.jsx("textarea",{name:"contactAddress",value:e.contactAddress,onChange:d,className:"input-border w-full rounded px-3 py-1 text-sm",placeholder:"Enter your business address",rows:3})]})]}),t.jsxs("div",{className:"space-y-3",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx("h3",{className:"text-md font-medium text-gray-900",children:"Links"}),t.jsx(c.Button,{type:"button",variant:"outline",size:"sm",onClick:()=>i(p=>({...p,isOpen:!0})),className:"text-sm",children:"Add Link"})]}),r.isOpen&&t.jsxs("div",{className:"space-y-3 rounded border bg-gray-50 p-3",children:[t.jsxs("div",{children:[t.jsx("label",{className:"mb-1 block text-sm font-medium",children:"Platform"}),t.jsxs("select",{value:r.platform,onChange:p=>i(b=>({...b,platform:p.target.value})),className:"input-border w-full rounded px-3 py-1 text-sm",children:[t.jsx("option",{value:"",children:"Select platform"}),u.map(p=>t.jsx("option",{value:p.value,children:p.label},p.value))]})]}),r.platform==="other"&&t.jsxs("div",{children:[t.jsx("label",{className:"mb-1 block text-sm font-medium",children:"Platform Name"}),t.jsx("input",{type:"text",value:r.customName,onChange:p=>i(b=>({...b,customName:p.target.value})),className:"input-border w-full rounded px-3 py-1 text-sm",placeholder:"e.g., TikTok, Discord, Snapchat"})]}),t.jsxs("div",{children:[t.jsx("label",{className:"mb-1 block text-sm font-medium",children:"URL"}),t.jsx("input",{type:"url",value:r.url,onChange:p=>i(b=>({...b,url:p.target.value})),className:"input-border w-full rounded px-3 py-1 text-sm",placeholder:"https://platform.com/yourprofile"})]}),t.jsxs("div",{className:"flex gap-2",children:[t.jsx(c.Button,{type:"button",onClick:h,disabled:!r.platform||!r.url.trim()||r.platform==="other"&&!r.customName.trim(),className:"flex-1",children:"Save Link"}),t.jsx(c.Button,{type:"button",variant:"outline",onClick:j,className:"flex-1",children:"Cancel"})]})]}),n.length>0&&t.jsx("div",{className:"space-y-2",children:n.map((p,b)=>t.jsxs("div",{className:"flex items-center justify-between rounded border p-2",children:[t.jsxs("div",{children:[t.jsx("span",{className:"text-sm font-medium capitalize",children:p.platform}),t.jsx("p",{className:"max-w-xs truncate text-xs text-gray-500",children:p.url})]}),t.jsx(c.Button,{type:"button",variant:"outline",size:"sm",onClick:()=>m(b),className:"text-red-600 hover:bg-red-50 hover:text-red-700",children:"Remove"})]},b))})]}),t.jsx("div",{className:"pt-3",children:t.jsx(c.Button,{onClick:y,disabled:!v||l,className:"w-full",children:l?"Saving...":"Save Contact & Social Settings"})})]})]})},Eu=({isActive:e,onClick:s})=>t.jsx(c.Button,{variant:e?"default":"ghost",className:"w-full justify-start text-left",onClick:s,children:"Analytics & Tracking"}),Cu=()=>{const[e,s]=g.useState({googleAnalyticsId:"",googleTagManagerId:"",metaPixelId:""}),[n,a]=g.useState([]),[r,i]=g.useState(""),[l,o]=g.useState(!1),u=y=>{const{name:v,value:p}=y.target;s(b=>({...b,[v]:p}))},d=()=>{r.trim()&&(a(y=>[...y,{id:Date.now().toString(),content:r}]),i(""))},h=y=>{a(v=>v.filter(p=>p.id!==y))},m=()=>{o(!0);const y={...e,customTrackingScripts:n.map(v=>v.content)};setTimeout(()=>{o(!1),console.log("Analytics & Tracking settings saved:",y),s({googleAnalyticsId:"",googleTagManagerId:"",metaPixelId:""}),a([])},1e3)},j=Object.values(e).some(y=>y.trim())||n.length>0;return t.jsxs("div",{className:"space-y-4",children:[t.jsx("h2",{className:"text-lg font-medium",children:"Analytics & Tracking Settings"}),t.jsxs("div",{className:"space-y-4",children:[t.jsxs("div",{children:[t.jsx("label",{className:"mb-1 block text-sm font-medium",children:"Google Analytics ID"}),t.jsx("input",{type:"text",name:"googleAnalyticsId",value:e.googleAnalyticsId,onChange:u,placeholder:"UA-XXXXXXXXX-X",className:"input-border w-full rounded px-3 py-1 text-sm"})]}),t.jsxs("div",{children:[t.jsx("label",{className:"mb-1 block text-sm font-medium",children:"Google Tag Manager ID"}),t.jsx("input",{type:"text",name:"googleTagManagerId",value:e.googleTagManagerId,onChange:u,placeholder:"GTM-XXXXXX",className:"input-border w-full rounded px-3 py-1 text-sm"})]}),t.jsxs("div",{children:[t.jsx("label",{className:"mb-1 block text-sm font-medium",children:"Meta Pixel ID"}),t.jsx("input",{type:"text",name:"metaPixelId",value:e.metaPixelId,onChange:u,placeholder:"XXXXXXXXXX",className:"input-border w-full rounded px-3 py-1 text-sm"})]}),t.jsxs("div",{children:[t.jsx("div",{className:"mb-2 flex items-center justify-between",children:t.jsx("label",{className:"text-sm font-medium",children:"Custom Tracking Scripts"})}),t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx("textarea",{value:r,onChange:y=>i(y.target.value),placeholder:"Paste your tracking script code",className:"input-border min-h-[80px] w-full rounded px-3 py-2 font-mono text-sm",rows:4}),t.jsxs("div",{className:"flex justify-between items-center",children:[t.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"Add custom tracking scripts (e.g., Hotjar, Mixpanel, etc.)"}),t.jsx(c.Button,{variant:"outline",size:"sm",onClick:d,disabled:!r.trim(),children:"Add Script"})]})]})]}),n.length>0&&t.jsx("div",{className:"mb-3 space-y-2",children:n.map(y=>t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("div",{className:"flex-1 overflow-hidden rounded border bg-gray-50 p-2",children:t.jsx("code",{className:"block max-h-20 overflow-auto text-xs",children:y.content.length>100?`${y.content.substring(0,100)}...`:y.content})}),t.jsx(c.Button,{variant:"ghost",size:"sm",className:"text-destructive hover:text-destructive",onClick:()=>h(y.id),children:"Remove"})]},y.id))}),t.jsx("div",{className:"pt-3",children:t.jsx(c.Button,{onClick:m,disabled:!j||l,className:"w-full",children:l?"Saving...":"Save Settings"})})]})]})},Au=()=>{vs("branding",{label:"Branding",button:bu,panel:wu}),vs("contact-social",{label:"Contact & Social",button:Su,panel:Nu}),vs("analytics-tracking",{label:"Analytics & Tracking",button:Eu,panel:Cu})},Tu=g.lazy(()=>Promise.resolve().then(()=>vu));lu();Ar.loadWebBlocks();$.registerChaiTopBar(Ml);xo();Au();$.registerChaiMediaManager(Tu);$.registerChaiSaveToLibrary(fi);const ku=e=>{const s=g.useRef([]),[n]=Pe(),a=n.get("page"),{data:r}=ke(),{data:i={role:"",permissions:null}}=Pa();Fl(),Zr();const{data:l,isFetching:o}=pa(),{blocks:u}=Ul(l),{data:d}=Ae(),{mutateAsync:h}=la(),m=Ol(),{onSave:j}=ql(),{getPartialBlocks:y,getPartialBlockBlocks:v}=$l(),{aiContext:p,setAiContext:b}=dn(),{mutateAsync:S}=xi(),[E,L]=g.useState(!1),{data:I}=Ke(),k=Qe(),{data:T}=fn(),{data:V}=ou(),{mutateAsync:ne}=cu(),Y=vr();Fr(),g.useEffect(()=>{const R=()=>{document.hidden?L(!0):L(!1)};return window.addEventListener("visibilitychange",R),()=>window.removeEventListener("visibilitychange",R)},[]),s.current=u;const _=g.useMemo(()=>{const R={};return i&&(R.permissions=f.get(i,"permissions",null),R.role=f.get(i,"role","user")),R},[i]),M=g.useCallback(async(R,Z)=>await S({pageType:R,query:Z}),[S]),Q=g.useMemo(()=>f.get(I,"theme",{})||{},[I]);return t.jsxs(t.Fragment,{children:[t.jsx($.ChaiBuilderEditor,{gotoPage:Y,collections:V??[],getBlockAsyncProps:ne,pageExternalData:T,themePresets:e.themePresets??[],pageId:r==null?void 0:r.id,loading:o,fallbackLang:k,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:v,getPartialBlocks:y,blocks:o?[]:u,theme:f.cloneDeep(Q),pageTypes:d,searchPageTypeItems:M,saveAiContextCallback:async R=>{if(!a)return!0;const Z=s.current,K={_type:"@chai/ai-context",_value:f.isString(R)?R:""},te=[...Z,K];return await j({page:a,blocks:te}),b(R),!0},aiContext:p,askAiCallBack:m,onSave:async({blocks:R,theme:Z,needTranslations:K})=>{if(!a)return!0;s.current=R;const te={_type:"@chai/ai-context",_value:f.isString(p)?p:""},ue=[...R,te];return await j({page:a,blocks:ue,needTranslations:K}),s.current=ue,f.isEqual(Z,Q)||await h({settings:{theme:Z}}),!0},themePanelComponent:Ei,..._}),t.jsxs("div",{children:[t.jsx(ni,{}),t.jsx(ai,{})]})]})},Pu=new F.QueryClient({defaultOptions:{queries:{refetchOnWindowFocus:!1,refetchOnReconnect:!1}}}),Iu=e=>{const{isLoggedIn:s}=Me(),[,n]=oa(),[a,r]=g.useState(!1);return g.useEffect(()=>(n(f.pick(e,["apiUrl","usersApiUrl","assetsApiUrl","getPreviewUrl","getLiveUrl","logo","onLogout","getAccessToken","supabaseInstance"])),setTimeout(()=>{r(!0)},200),()=>{r(!1),n({})}),[e,n]),a?t.jsxs(F.QueryClientProvider,{client:Pu,children:[s?t.jsx(ku,{...e}):t.jsx(Hl,{}),t.jsx(iu,{})]}):t.jsx("div",{})},_u=()=>{const e=le(),s=X(),{data:n}=We(),a=F.useQueryClient();return F.useMutation({mutationFn:async r=>{if(!(n!=null&&n.id))throw new Error("No active page found");return await s(`${e}`,{action:D.UPDATE_PAGE_METADATA,data:{id:n.id,metadata:r}})},onSuccess:()=>{a.invalidateQueries({queryKey:[D.GET_BUILDER_PAGE_DATA]}),a.invalidateQueries({queryKey:[D.GET_LANGUAGE_PAGES]})},onError:()=>{console.error("Failed to update metadata")}})},Lu=()=>{const{logout:e}=Me(),{getAccessToken:s}=ra();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])};if(typeof window>"u")throw new Error("@chaibuilder/pages is not available on the server");exports.$TRACK=An;exports.ChaiBuilderPages=Iu;exports.ChaiBuilderPagesRealtime=fa;exports.Dynamic=hc;exports.For=Go;exports.ImagePicker=_s;exports.Index=Uo;exports.LanguageSwitcher=Cn;exports.Match=$o;exports.NestedPathSelector=tt;exports.PermissionChecker=Re;exports.Portal=dc;exports.Show=Fo;exports.SmartJsonInput=_a;exports.Switch=qo;exports.addEventListener=Ja;exports.batch=bo;exports.className=Ya;exports.clearDelegatedEvents=tc;exports.convertRemToPixels=eu;exports.createComponent=Pn;exports.createComputed=Oa;exports.createContext=Ao;exports.createEffect=Tn;exports.createMemo=Le;exports.createRenderEffect=nt;exports.createRoot=st;exports.createSignal=Ne;exports.createUniqueId=Oo;exports.delegateEvents=Wa;exports.deleteNestedDataByPath=qt;exports.displayValue=Qc;exports.getMutationStatusColor=Kc;exports.getPreferredColorScheme=tu;exports.getQueryStatusColor=Vc;exports.getQueryStatusColorByLabel=Hc;exports.getQueryStatusLabel=$c;exports.getSidedProp=zc;exports.insert=Is;exports.mergeProps=In;exports.mutationSortFns=Zc;exports.on=wo;exports.onCleanup=Lt;exports.onMount=Ga;exports.registerChaiSiteSetting=vs;exports.registerLoginComponent=Kl;exports.serialize=xr;exports.setAttribute=Ps;exports.sortFns=Jc;exports.splitProps=Va;exports.spread=Xa;exports.stringify=qc;exports.template=ec;exports.untrack=Te;exports.updateNestedDataByPath=Ft;exports.use=Za;exports.useActivePage=We;exports.useBuilderPageData=fn;exports.useChaiAuth=Me;exports.useChaiFetch=Lu;exports.useChaiUserInfo=Ye;exports.useContext=To;exports.useCurrentPage=ke;exports.useFallbackLang=Qe;exports.useFetch=X;exports.useGotoPage=vr;exports.useLanguagePages=qe;exports.usePageTypes=Ae;exports.useTransition=Co;exports.useUpdateActivePageMetadata=_u;exports.useUserRoleAndPermissions=Pa;exports.useWebsitePages=ht;exports.useWebsiteSetting=Ke;
|