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