@chaibuilder/pages 0.13.2 → 0.13.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{2AITGKQY-BEGIO0Jl.cjs → 2AITGKQY-DpAgk_u8.cjs} +1 -1
- package/dist/{2AITGKQY-qbnAQ6M2.js → 2AITGKQY-Dx_Cte-P.js} +2 -2
- package/dist/{NCMVHL6D-CQOgtexk.cjs → NCMVHL6D-B6lv7Umq.cjs} +1 -1
- package/dist/{NCMVHL6D-Dka6j7a3.js → NCMVHL6D-CT2qHOTS.js} +2 -2
- package/dist/{ZDWCUMSJ-DpI59KoJ.cjs → ZDWCUMSJ-C1vrgsti.cjs} +1 -1
- package/dist/{ZDWCUMSJ-Q3c0YYpj.js → ZDWCUMSJ-W9xywtZH.js} +1 -1
- package/dist/index-C4j31Yhz.js +11471 -0
- package/dist/index-DnjETHks.cjs +6 -0
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +6 -1
- package/dist/index.js +3 -3
- package/dist/page-revisions-content-Gx-Qf_91.cjs +8 -0
- package/dist/page-revisions-content-_-Nd4U11.js +712 -0
- package/package.json +3 -3
- package/dist/index-CWga9SJC.cjs +0 -13
- package/dist/index-DxhdyX8W.js +0 -12159
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
"use strict";var _r=Object.defineProperty;var Pn=e=>{throw TypeError(e)};var Lr=(e,s,n)=>s in e?_r(e,s,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[s]=n;var Ye=(e,s,n)=>Lr(e,typeof s!="symbol"?s+"":s,n),In=(e,s,n)=>s.has(e)||Pn("Cannot "+n);var te=(e,s,n)=>(In(e,s,"read from private field"),n?n.call(e):s.get(e)),ge=(e,s,n)=>s.has(e)?Pn("Cannot add the same private member more than once"):s instanceof WeakSet?s.add(e):s.set(e,n),he=(e,s,n,a)=>(In(e,s,"write to private field"),a?a.call(e,n):s.set(e,n),n);const t=require("react/jsx-runtime"),g=require("lodash-es"),f=require("react"),ye=require("jotai"),G=require("@tanstack/react-query"),Q=require("sonner"),V=require("@chaibuilder/sdk"),c=require("@chaibuilder/sdk/ui"),Dr=require("date-fns"),N=require("lucide-react"),Br=require("compressorjs"),sa=require("@chaibuilder/runtime"),vs=require("zod"),Or=require("react-dropzone"),Mr=require("@chaibuilder/sdk/web-blocks");function Gr(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 be=Gr(f),we={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"},_={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_REVISION_DATA:"GET_REVISION_DATA",GET_PAGE_DATA:"GET_PAGE_DATA",GET_COMPARE_DATA:"GET_COMPARE_DATA",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",GET_APP_SHARED_JSONLD:"GET_APP_SHARED_JSONLD",UPDATE_APP_SHARED_JSONLD:"UPDATE_APP_SHARED_JSONLD",UPLOAD_ASSET:"UPLOAD_ASSET",DELETE_ASSET:"DELETE_ASSET",UPDATE_ASSET:"UPDATE_ASSET",GET_ASSETS:"GET_ASSETS",GET_ASSET:"GET_ASSET"};let Rr=0;function _n(e,s){const n=`atom${++Rr}`,a={toString(){return n}};return typeof e=="function"?a.read=e:(a.init=e,a.read=Ur,a.write=Fr),s&&(a.write=s),a}function Ur(e){return e(this)}function Fr(e,s,n){return s(this,typeof n=="function"?n(e(this)):n)}const qr=Symbol(""),na=e=>typeof(e==null?void 0:e.then)=="function";function zr(e=()=>{try{return window.localStorage}catch{return}},s){var n;let a,r;const i={getItem:(u,d)=>{var h,m;const v=y=>{if(y=y||"",a!==y){try{r=JSON.parse(y,s==null?void 0:s.reviver)}catch{return d}a=y}return r},p=(m=(h=e())==null?void 0:h.getItem(u))!=null?m:null;return na(p)?p.then(v):v(p)},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)}},o=u=>(d,h,m)=>u(d,v=>{let p;try{p=JSON.parse(v||"")}catch{p=m}h(p)});let l;try{l=(n=e())==null?void 0:n.subscribe}catch{}return!l&&typeof window<"u"&&typeof window.addEventListener=="function"&&window.Storage&&(l=(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)}}),l&&(i.subscribe=o(l)),i}const Vr=zr();function aa(e,s,n=Vr,a){const r=_n(s);return r.onMount=o=>{o(n.getItem(e,s));let l;return n.subscribe&&(l=n.subscribe(e,o,s)),l},_n(o=>o(r),(o,l,u)=>{const d=typeof u=="function"?u(o(r)):u;return d===qr?(l(r,s),n.removeItem(e)):na(d)?d.then(h=>(l(r,h),n.setItem(e,h))):(l(r,d),n.setItem(e,d))})}localStorage.removeItem("_chai_user");localStorage.removeItem("__chai__user");const ra="__logged_in_user",$r=aa(ra,null),Fe=()=>{const[e,s]=ye.useAtom($r),n=f.useCallback(()=>{s(null),localStorage.removeItem(ra)},[s]);return{isLoggedIn:!!e,user:e,setUser:s,logout:n}},hn=async(e,s,n={})=>await fetch(e,{method:"POST",headers:{"Content-Type":"application/json",...n},body:JSON.stringify(s)});let ht=null;function Kr(){const{user:e,setUser:s,logout:n}=Fe(),a=Bs(),r=Me("getAccessToken",!1),i=async()=>{if(r===!1&&e&&!(!g.has(e,"expiresAt")||!g.has(e,"accessToken")||!g.has(e,"refreshToken")))try{const o=await hn(a,{action:"REFRESH_TOKEN",data:{refreshToken:e.refreshToken,accessToken:e.accessToken}});if(!o.ok){n(),window.location.reload();return}const l=await o.json();if(g.has(l,"id")&&g.has(l,"email")&&g.has(l,"accessToken")&&g.has(l,"refreshToken"))return s(l),l;n(),window.location.reload()}catch{n(),window.location.reload()}};return G.useMutation({mutationFn:async()=>{if(ht)return await ht;ht=i();try{return await ht}finally{ht=null}},onSuccess:()=>{}})}function Hr(){return ht}const ia=()=>{const{user:e,setUser:s}=Fe(),{mutateAsync:n}=Kr(),a=60,r=f.useCallback(()=>{if(!(e!=null&&e.expiresAt))return!1;if(!e||!(e!=null&&e.refreshToken))return!0;const l=Math.floor(Date.now()/1e3);return e.expiresAt-l<=a},[e]),o=Me("getAccessToken",async()=>{if(!g.has(e,"expiresAt")||!g.has(e,"accessToken")||!g.has(e,"refreshToken"))return(e==null?void 0:e.accessToken)||"";if(r()){const l=Hr();if(l){const d=await l;return d&&s(d),(d==null?void 0:d.accessToken)||""}const u=await n();return u&&s(u),(u==null?void 0:u.accessToken)||""}return(e==null?void 0:e.accessToken)||""});return{getAccessToken:f.useCallback(async()=>{try{return await o()}catch{return""}},[o])}},se=()=>{const{logout:e}=Fe(),{getAccessToken:s}=ia();return f.useCallback(async(n,a,r={})=>{const i=await s();if(!i)return console.error("No auth token found"),null;try{const o=g.get(a,"action","").toLowerCase(),l=await hn(n+(o?`?action=${o}`:""),a,{...r,Authorization:`Bearer ${i}`});if(l.status===401)return console.log("401 Response",l),e(),window.location.reload(),null;if(!l.ok){const u=await l.json();throw console.error(`API Error (${l.status}):`,u),{status:l.status,statusText:l.statusText,...u,message:u.error||u.message||`Server error: ${l.status}`}}return await l.json()}catch(o){throw console.error("API request failed:",a,o),o}},[e,s])},la=()=>{const e=oe(),s=G.useQueryClient(),n=se();return G.useMutation({mutationFn:async a=>n(e,{action:_.RELEASE_LOCK,data:a}),onSuccess:()=>{s.invalidateQueries({queryKey:[_.GET_DRAFT_PAGE]})}})},oa=()=>{const e=oe(),s=G.useQueryClient(),n=se();return G.useMutation({mutationFn:async a=>n(e,{action:_.UPDATE_WEBSITE_SETTINGS,data:a}),onSuccess:(a,r)=>{var i;s.invalidateQueries({queryKey:[_.GET_WEBSITE_DRAFT_SETTINGS]}),(i=r==null?void 0:r.settings)!=null&&i.theme||Q.toast.success("Website settings updated successfully.")},onError:a=>{Q.toast.error("Failed to update website settings",{description:a.message})}})},Qr=()=>{const e=oe(),s=G.useQueryClient(),n=se();return G.useMutation({mutationFn:async a=>n(e,{action:_.UPDATE_WEBSITE_DATA,data:a}),onSuccess:()=>{s.invalidateQueries({queryKey:[_.GET_WEBSITE_DATA]}),Q.toast.success("Website data updated successfully.")},onError:a=>{Q.toast.error("Failed to update website data",{description:a.message})}})},ca=()=>{const e=oe(),s=G.useQueryClient(),n=se();return G.useMutation({mutationFn:async a=>n(e,{action:_.UPDATE_APP_SHARED_JSONLD,data:JSON.stringify(a)}),onSuccess:()=>{s.invalidateQueries({queryKey:[_.GET_APP_SHARED_JSONLD]}),Q.toast.success("Shared JSON-LD updated successfully.")},onError:a=>{Q.toast.error("Failed to update shared JSON-LD",{description:a.message})}})};function _e(){const[e,s]=f.useState(new URLSearchParams(window.location.search));return f.useEffect(()=>{const n=()=>{s(new URLSearchParams(window.location.search))};return window.addEventListener("popstate",n),()=>{window.removeEventListener("popstate",n)}},[]),[e,s]}const Wr=ye.atom({}),Ds=()=>ye.useAtom(Wr),Jr=()=>{const[e]=_e(),s=e.get("page"),n=f.useRef(""),{mutate:a}=la();f.useEffect(()=>{!g.isEmpty(n.current)&&s!==n.current&&a({id:n.current}),n.current=s},[s,a,n])},Me=(e,s)=>{const[n]=Ds();return f.useMemo(()=>g.get(n,e,s),[n,e,s])},oe=()=>Me("apiUrl","/chai/api"),Bs=()=>Me("usersApiUrl","/chai/users"),is=()=>Me("assetsApiUrl","/chai/assets"),Yr=()=>Me("supabaseInstance",null),Oe=e=>{const s=oe(),[n]=_e(),a=e??n.get("page"),r=se();return G.useQuery({queryKey:[_.GET_LANGUAGE_PAGES,a],initialData:[],queryFn:async()=>{if(!a)return null;const i=await r(s,{action:_.GET_LANGUAGE_PAGES,data:{id:a}});return g.reverse(g.sortBy(i,"primaryPage"))},enabled:!!a})},$e=()=>{const e=oe(),s=se();return G.useQuery({queryKey:[_.GET_WEBSITE_DRAFT_SETTINGS],initialData:{theme:{},fallbackLang:"en",languages:[]},queryFn:async()=>s(e,{action:_.GET_WEBSITE_DRAFT_SETTINGS,data:{draft:!0}})})},ua=e=>{const{fallbackLang:s}=V.useLanguages(),{data:n}=$e(),{data:a,isFetching:r}=Oe(),i=f.useMemo(()=>{const o={[s]:!0};return g.each(g.get(n,"languages"),l=>{const u=g.find(a,{lang:l});o[l]=!!u}),o},[s,a,n]);return r||g.isEmpty(e)||e&&i[e]};class da{constructor(s,n,a,r){Ye(this,"channelId");Ye(this,"supabase");Ye(this,"channel",null);Ye(this,"userId",null);Ye(this,"clientId",null);Ye(this,"pageId",null);Ye(this,"callback");var i,o,l,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=(l=(o=(i=this.channel)==null?void 0:i.on("presence",{event:"sync"},m=>{this.callback("UPDATE_ONLINE_USERS",{pageToUser:this.getPageUserMapping()}),this.onReceiveEvent("SYNC",m)}))==null?void 0:o.on("presence",{event:"leave"},m=>{this.callback("UPDATE_ONLINE_USERS",{pageToUser:this.getPageUserMapping()}),this.onReceiveEvent("SYNC",m)}))==null?void 0:l.on("presence",{event:"join"},m=>{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(o=>o[0]).filter(Boolean);return s?r=r.filter(o=>o.pageId===s):n&&(r=r.filter(o=>o.userId===n)),r.sort((o,l)=>o.onlineAt-l.onlineAt)}getPageOwner(){const s=this.getOnlineUsers({pageId:this.pageId});return s.length>0?s[0]:null}getPageUserMapping(){const s=this.getOnlineUsers({}),n=g.groupBy(s,"pageId"),a={};return Object.keys(n).forEach(r=>{var o;const i=(o=g.minBy(n[r],"onlineAt"))==null?void 0:o.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 Xr=ye.atom(null),ha=()=>ye.useAtom(Xr),mn=()=>{const[e]=ha();return(e==null?void 0:e.slug)||""};function Zr(e,s){const[n,a]=f.useState(e);return f.useEffect(()=>{const r=setTimeout(()=>a(e),s);return()=>clearTimeout(r)},[e,s]),n}const ei=({query:e,uuid:s})=>{const{selectedLang:n,fallbackLang:a}=V.useLanguages(),{data:r}=ke(),i=r==null?void 0:r.pageType,o=oe(),l=se(),{data:u,isFetching:d}=G.useQuery({queryKey:[_.GET_DYNAMIC_PAGES,e,i,s],initialData:[],queryFn:async()=>await l(o,{action:_.GET_DYNAMIC_PAGES,data:{query:e,pageType:i,uuid:s}})||[],enabled:!!i}),h=f.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}},ma=()=>{const{selectedLang:e,fallbackLang:s}=V.useLanguages(),[n,a]=ha(),[r,i]=f.useState(""),o=Zr(r,500),{allLangPages:l,data:u,isFetching:d}=ei({query:o}),h=f.useCallback(p=>a(p),[a]),m=f.useCallback(p=>i(p),[i]),v=f.useCallback(()=>{if(!n)return;const p=!(n!=null&&n.primaryPage),y=e.length===0,j=p?n==null?void 0:n.id:n==null?void 0:n.primaryPage,b=l.filter(E=>(E==null?void 0:E.primaryPage)===j||E.id===j).find(E=>y?E.lang===e||E.lang===s:E.lang===e);a(b||n)},[n,e,l,a,s]);return{isFetching:d,dynamicPage:n,searchQuery:r,selectedLang:e,dynamicPages:u,allLangPages:l,updateDynamicPage:h,updateSearchQuery:m,onChangeLanguage:v}},ti=ye.atom({lastSaved:void 0}),Os=()=>ye.useAtom(ti),ke=()=>{const[e]=_e(),s=e.get("page"),{data:n,isFetching:a}=Oe();return{data:f.useMemo(()=>({...g.find(n,{id:s})||{}}),[n,s]),isFetching:a}},Qe=()=>{const[e]=_e(),s=e.get("lang")??"",{data:n,isFetching:a}=Oe();return{data:f.useMemo(()=>g.find(n,{lang:s})||{},[n,s]),isFetching:a}},si=ye.atom({}),ni=()=>ye.useAtom(si),fa=()=>{const{data:e}=Qe(),s=mn(),n=Me("getLiveUrl",g.noop),a=e==null?void 0:e.slug,r=n(a||"/");return s?r+s:r},ls=e=>{const s=Bs(),n=se();return G.useQuery({queryKey:["chaiUserInfo",e],queryFn:async()=>{const r=await n(s,{action:_.GET_CHAI_USER,data:{userId:e}});return{...r,name:r.name||r.email}},enabled:!g.isEmpty(e)})},ai=ye.atom({status:"checking",requestedBy:"",isTakeOverRequested:!1,requestingClientId:"",isActiveInOtherTab:!1}),ri=ye.atom(""),ii=ye.atom(null),fn=ye.atom({}),ga=()=>ye.useAtom(fn),st=()=>{const[e]=_e(),s=e.get("page"),[n,a]=ye.useAtom(ai),[r,i]=ye.useAtom(ii),[o,l]=ye.useAtom(ri),[u]=ye.useAtom(fn);return{pageLock:n,pageToUser:u,lockingStatus:o,realtimeInstance:r,setPageLock:a,setLockingStatus:l,setRealtimeInstance:i,realtimePageLockEnabled:!!r,currentEditor:u[s||""],isLocked:s&&n.status==="locked"}},li=()=>{const e=Yr(),{data:s}=ke(),{user:n}=Fe(),a=s==null?void 0:s.id,{data:r}=$e(),{pageLock:i,setPageLock:o,setLockingStatus:l,realtimeInstance:u,setRealtimeInstance:d}=st(),[,h]=ye.useAtom(fn),m=f.useRef(!1),v=f.useRef(i),p=f.useRef(!1);return f.useEffect(()=>{if(n!=null&&n.id&&e&&!u&&(r!=null&&r.appKey)&&!p.current){p.current=!0;const y=async(x,b)=>{var E,P;switch(x){case"UPDATE_ONLINE_USERS":h((b==null?void 0:b.pageToUser)||{});break;case"PAGE_LOCKED":o({...v==null?void 0:v.current,requestedBy:"",status:"locked",isActiveInOtherTab:b==null?void 0:b.isActiveInOtherTab});break;case"USER_JOINED":if(((E=v==null?void 0:v.current)==null?void 0:E.status)==="editing")return;((P=v==null?void 0:v.current)==null?void 0:P.status)==="locked"&&l("can_edit_now"),o({...v==null?void 0:v.current,requestedBy:"",status:"editing",isActiveInOtherTab:b==null?void 0:b.isActiveInOtherTab});break;case"TAKE_OVER_REQUESTED":o({...v==null?void 0:v.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||(l("take_over_request_accepted"),Q.toast.success("Your Page Take Over Request Accepted",{position:"top-center"})),o({...v==null?void 0:v.current,status:"checking",requestedBy:"",requestingClientId:"",isTakeOverRequested:!1});break;case"TAKE_OVER_REQUEST_REJECTED":l("take_over_request_rejected"),o({...v==null?void 0:v.current,requestedBy:"",requestingClientId:"",isTakeOverRequested:!1});break}},j=new da(e,r==null?void 0:r.appKey,n==null?void 0:n.id,y);d(j)}},[d,e,r==null?void 0:r.appKey]),f.useEffect(()=>{v.current=i},[i]),f.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,v.current={requestedBy:"",status:"checking",requestingClientId:"",isActiveInOtherTab:!1,isTakeOverRequested:!1},l(""),o(v.current),u==null||u.leavePage())}},[a,u]),i==null?void 0:i.status},xa=()=>{const{data:e}=ke(),{user:s}=Fe(),n=e==null?void 0:e.id,{pageLock:a,setPageLock:r,realtimeInstance:i}=st(),{savePageAsync:o}=V.useSavePage(),l=f.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=f.useCallback(async()=>{!i||!n||!(s!=null&&s.id)||(await o(),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,o,a]),d=f.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:l}},kt=({children:e})=>t.jsx("div",{className:"fixed bottom-0 left-0 right-0 top-[50px] z-[20] flex w-screen flex-col items-center justify-center bg-black/40",children:e}),oi=({userId:e})=>{const{data:s}=ls(e);return(s==null?void 0:s.name)||"Unknown"};function ci({avatar:e,name:s,email:n,lastSaved:a,onTakeOver:r,isRequestRejected:i,isFetchingUserInfo:o}){const[l,u]=f.useState(!1),d=()=>{u(!0),setTimeout(()=>{u(!1)},15e3),r()};return t.jsx(kt,{children:t.jsxs(c.Card,{className:"mx-auto w-full max-w-md",children:[t.jsx(c.CardHeader,{className:"space-y-1",children:t.jsxs(c.CardTitle,{className:"flex items-center gap-2 text-xl",children:[t.jsx(N.LockKeyhole,{className:"h-8 w-8 rounded-md bg-sky-500/20 p-1.5 text-sky-500"}),"Page is locked for editing"]})}),t.jsx(c.CardContent,{className:"w-md grid w-full pt-2",children:t.jsxs("div",{children:[t.jsxs("div",{className:"relative mx-auto flex w-96 items-center space-x-4 rounded-md border border-green-500 px-2 pb-2 pt-4",children:[t.jsx("div",{className:"absolute -top-2.5 left-3 w-max rounded-full bg-green-500 px-3 py-1 text-xs font-medium leading-3 text-white",children:"Locked By"}),e&&!o?t.jsx("img",{src:e,alt:s,className:"h-14 w-14 rounded-full border border-gray-300"}):t.jsx(N.UserIcon,{className:"h-14 w-14 flex-shrink-0 rounded-full bg-gradient-to-br from-purple-400 to-pink-500 p-2 text-white"}),t.jsxs("div",{className:o?"space-y-1.5":"space-y-0",children:[o?t.jsx(c.Skeleton,{className:"h-4 w-40 rounded"}):t.jsx("span",{className:"truncate font-medium text-black",children:s}),n&&!o?t.jsx("p",{className:"truncate text-sm text-muted-foreground",children:n}):t.jsx(c.Skeleton,{className:"h-4 w-60 rounded"}),a&&!o?t.jsxs("p",{className:"text-sm text-muted-foreground",children:["Last saved:"," ",Dr.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",{}),t.jsx("br",{})," You can either wait until they finish editing or request to take over the page."]})}),i&&t.jsxs("div",{className:"mt-4 flex w-full items-center justify-center gap-x-2 rounded border border-red-500 bg-red-50 p-2 text-center font-medium text-red-500",children:[t.jsx(N.Info,{className:"h-5 w-5"})," Page take over request is rejected"]})]})}),t.jsx(c.CardFooter,{children:t.jsxs(c.Button,{disabled:l,onClick:d,className:"w-full",variant:"destructive",children:[t.jsx(N.KeyIcon,{className:"h-5 w-5"}),l?"Page take is requested.":i?"Request take over again":"Request take over"]})})]})})}const gs=({isChecking:e,lockingStatus:s,onContinue:n})=>{const[a,r]=f.useState(!1),i=s==="page_is_active_in_other_tab",o=(s==null?void 0:s.length)>0,{pageLock:l,acceptTakeOver:u,rejectTakeOver:d}=xa(),h=()=>{r(!0),o||i?n():u(),setTimeout(()=>{r(!1)},3e3)};return f.useEffect(()=>{(l==null?void 0:l.requestedBy)==="ANOTHER_TAB"&&u()},[l,u]),(l==null?void 0:l.requestedBy)==="ANOTHER_TAB"?null:e?t.jsx(kt,{children:t.jsx(N.Loader,{className:"h-5 w-5 animate-spin text-primary"})}):t.jsx(kt,{children:t.jsxs(c.Card,{className:"mx-auto w-full max-w-md",children:[t.jsx(c.CardHeader,{className:"space-y-1",children:t.jsxs(c.CardTitle,{className:"flex items-center gap-2 text-xl font-medium",children:[a?t.jsx(N.Loader,{className:"h-6 w-6 animate-spin text-gray-500"}):i?t.jsx(N.TableIcon,{className:"h-6 w-6 text-green-500"}):o?t.jsx(N.CheckCircle,{className:"h-6 w-6 text-green-500"}):t.jsx(N.Target,{className:"h-6 w-6 text-green-500"}),i?"Page is active in other tab":o?"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".'}):o?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(oi,{userId:l==null?void 0:l.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:o?"":"bg-green-500 hover:bg-green-600",children:i?t.jsxs(t.Fragment,{children:[t.jsx(N.Edit,{className:"h-5 w-5"})," Continue editing here"]}):o?t.jsxs(t.Fragment,{children:[t.jsx(N.Edit,{className:"h-5 w-5"})," Continue to edit"]}):t.jsxs(t.Fragment,{children:[t.jsx(N.Check,{className:"h-5 w-5"})," Accept"]})}),!o&&t.jsxs(c.Button,{variant:"outline",onClick:d,children:[t.jsx(N.X,{className:"h-5 w-5"})," Reject"]})]})]})})},ui=({isFetchingPage:e})=>{const{pageLock:s,requestTakeOver:n}=xa(),{currentEditor:a,lockingStatus:r,setLockingStatus:i,realtimePageLockEnabled:o}=st(),{data:l,isFetching:u}=ls(a),[d]=_e(),h=d.get("page"),{mutate:m}=la(),[v]=Os(),p=G.useQueryClient(),y=f.useCallback(()=>{o?n():m({id:h})},[h,m,n,o]);return!h||e||!o?null:(s==null?void 0:s.status)==="checking"?t.jsx(gs,{isChecking:!0,lockingStatus:"",onContinue:()=>{}}):s!=null&&s.requestedBy?t.jsx(gs,{lockingStatus:"",onContinue:()=>{}}):(s==null?void 0:s.status)!=="locked"?r==="take_over_request_accepted"||r==="can_edit_now"?t.jsx(gs,{lockingStatus:r,onContinue:()=>{p.invalidateQueries({queryKey:[_.GET_DRAFT_PAGE]}),i("")}}):null:s!=null&&s.isActiveInOtherTab?t.jsx(gs,{lockingStatus:"page_is_active_in_other_tab",onContinue:n}):t.jsx(ci,{...l,isFetchingUserInfo:u,name:(l==null?void 0:l.name)||"Unknown User",email:(l==null?void 0:l.email)||"",lastSaved:(v==null?void 0:v.lastSaved)||"",onTakeOver:y,realtimePageLockEnabled:o,isRequestRejected:r==="take_over_request_rejected"})},di=()=>{const[e,s]=_e(),n=e.get("lang"),a=ua(n),{setSelectedLang:r}=V.useLanguages(),i=()=>{const l=new URLSearchParams(window.location.search);l.delete("lang");const u=l.toString(),d=`${window.location.pathname}${u?`?${u}`:""}`;window.history.pushState({},"",d),s(l),r(""),window.dispatchEvent(new PopStateEvent("popstate"))};if(a)return null;const o=g.get(we,n);return t.jsx(kt,{children:t.jsxs(c.Card,{className:"mx-auto w-full max-w-md",children:[t.jsx(c.CardHeader,{className:"space-y-1",children:t.jsxs(c.CardTitle,{className:"flex items-center gap-2 text-2xl",children:[t.jsx(N.LockIcon,{className:"h-6 w-6 text-yellow-500"}),'Page missing for "',o,'" language.']})}),t.jsx(c.CardContent,{className:"grid gap-4",children:t.jsxs("div",{children:['Page is not available in the "',o,'" language. Either create the page in the "',o,'" 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"})})]})})},hi=e=>{const s=oe(),n=se();return G.useMutation({mutationFn:async a=>n(s,{action:_.UPSERT_LIBRARY_ITEM,data:a}),onSuccess:a=>{e(a)},onError:a=>{console.error("Error saving block:",a),Q.toast.error("Failed to save block",{description:a instanceof Error?a.message:"Unknown error"})}})},mi=e=>{const s=oe(),n=se();return G.useQuery({queryKey:["uiBlockDetails",e],enabled:!!e,queryFn:async()=>{if(!e)return null;try{return await n(s,{action:_.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})},fi=e=>{const s=oe(),n=se();return G.useMutation({mutationFn:async a=>n(s,{action:_.DELETE_LIBRARY_ITEM,data:{id:a}}),onSuccess:()=>{e()},onError:a=>{console.error("Error deleting block:",a),Q.toast.error("Failed to delete block",{description:a instanceof Error?a.message:"Unknown error"})}})},gi=({blockId:e,libBlockId:s,isOpen:n,onClose:a,blockName:r,trigger:i})=>{const[o,l]=f.useState(!1),u=V.useUpdateBlocksPropsRealtime(),d=fi(()=>{u([e],{_libBlockId:void 0}),Q.toast.success("Block deleted successfully"),l(!1),a()}),h=()=>{l(!0),d.mutate(s)},m=t.jsxs(c.Button,{type:"button",variant:"destructive",size:"sm",onClick:v=>v.preventDefault(),disabled:o,children:[t.jsx(N.Trash2,{className:"h-4 w-4 mr-2"}),"Delete"]});return t.jsxs(c.Popover,{open:n,onOpenChange:v=>!v&&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:o,children:"Cancel"}),t.jsx(c.Button,{type:"button",variant:"destructive",size:"sm",onClick:h,disabled:o,children:o?"Deleting...":"Delete"})]})]})})]})},xi=({blockId:e,libBlockId:s,blockName:n,size:a="sm",className:r="",close:i})=>{const[o,l]=f.useState(!1);return t.jsx(gi,{blockId:e,libBlockId:s,isOpen:o,onClose:()=>{l(!1),i()},blockName:n,trigger:t.jsxs(c.Button,{type:"button",variant:"destructive",size:a,className:r,onClick:()=>l(!0),children:[t.jsx(N.Trash2,{className:"h-4 w-4 mr-2"}),"Delete"]})})},pi=()=>{const e=oe(),s=se(),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:o,isPending:l}=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"]}),Q.toast.success("Group created successfully")},onError:u=>{console.error("Error creating group:",u),Q.toast.error("Failed to create group",{description:u instanceof Error?u.message:"Unknown error"})}});return{groups:a,isLoading:r,error:i,createGroup:o,isCreating:l}},yi=({value:e,onChange:s})=>{const[n,a]=f.useState(!1),[r,i]=f.useState(""),o=f.useRef(null),{groups:l}=pi(),[u,d]=f.useState([{id:"hero",name:"Hero"},{id:"feature",name:"Feature"},{id:"footer",name:"Footer"},{id:"content",name:"Content"},{id:"testimonial",name:"Testimonial"},{id:"pricing",name:"Pricing"},{id:"login",name:"Login"},{id:"logos",name:"Logos"},{id:"about",name:"About"},{id:"banner",name:"Banner"},{id:"blog",name:"Blog"},{id:"careers",name:"Careers"},{id:"casestudy",name:"Casestudy"},{id:"changelog",name:"Changelog"},{id:"compare",name:"Compare"},{id:"contact",name:"Contact"},{id:"cta",name:"Cta"},{id:"faq",name:"Faq"},{id:"gallery",name:"Gallery"},{id:"integration",name:"Integration"},{id:"list",name:"List"},{id:"navbar",name:"Navbar"},{id:"product",name:"Product"},{id:"signup",name:"Signup"},{id:"stats",name:"Stats"},{id:"team",name:"Team"},{id:"timeline",name:"Timeline"}]),h=f.useMemo(()=>[...l,...u.filter(p=>!l.some(y=>y.id===p.id))],[l,u]),m=()=>{const p=r.trim();if(!p)return;const y={id:p,name:p};d(j=>[...j,y]),s(y.id),i(""),a(!1)};f.useEffect(()=>{n&&o.current&&o.current.focus()},[n]);const v=p=>{p.key==="Enter"&&(p.preventDefault(),m())};return f.useEffect(()=>{e&&!h.some(p=>p.id===e)&&s("")},[e,h,s]),n?t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Input,{ref:o,placeholder:"Enter new group name",value:r,onChange:p=>i(p.target.value),onKeyDown:v}),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:p=>s(p.target.value),children:[t.jsx("option",{value:"",children:"Select a group"}),l.length>0&&t.jsx("optgroup",{label:"Library Groups",children:l.map(p=>t.jsx("option",{value:p.id,children:p.name},`lib-${p.id}`))}),u.length>0&&t.jsx("optgroup",{label:"Predefined Groups",children:u.filter(p=>!l.some(y=>y.id===p.id)).map(p=>t.jsx("option",{value:p.id,children:p.name},`local-${p.id}`))})]}),t.jsx(c.Button,{type:"button",size:"icon",variant:"outline",onClick:()=>a(!0),children:t.jsx(N.Plus,{className:"h-4 w-4"})})]})},Ln=3*1024*1024,vi=10*1024*1024;function Zs(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 pa(e){return new Promise((s,n)=>{if(e.size<=Ln){s(e);return}new Br(e,{quality:.8,maxWidth:2048,maxHeight:2048,convertSize:Ln,success(a){s(a)},error(a){Q.toast.error(`Failed to compress image. Image size is ${Zs(e.size)}, which exceeds the maximum allowed size of ${Zs(vi)}.`),n(a)}})})}const ji=({value:e,onChange:s})=>{const[n,a]=f.useState(!1),r=f.useRef(null),i=f.useCallback(async u=>{var h;const d=(h=u.target.files)==null?void 0:h[0];if(d)try{a(!0);let m=d;d.type.startsWith("image/")&&(m=await pa(d));const v=new FileReader;v.onloadend=()=>{s(v.result),a(!1)},v.readAsDataURL(m)}catch(m){console.error("Error reading file:",m),a(!1),Q.toast.error("Failed to process image",{description:m instanceof Error?m.message:"Unknown error"})}},[s]),o=()=>{s(""),r.current&&(r.current.value="")},l=()=>{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:l,disabled:n,className:"w-full",children:n?t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsx("div",{className:"h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent"}),"Uploading..."]}):t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsx(N.ImageIcon,{className:"h-4 w-4"}),"Select image"]})}),e&&t.jsx(c.Button,{type:"button",variant:"outline",size:"icon",onClick:o,children:t.jsx(N.X,{className:"h-4 w-4"})})]}),e&&t.jsx("div",{className:"aspect-video h-[200px] max-h-[200px] overflow-hidden rounded-md border",children:t.jsx("img",{src:e,alt:"Preview",className:"h-full w-full object-contain"})})]})},Se={...V.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"},bi=e=>{const{blocks:s,close:n,blockId:a}=e,{getPartailBlocks:r}=V.usePartailBlocksStore(),i=s.find(I=>I._id===a),o=i==null?void 0:i._libBlockId,l=!!o,u=f.useMemo(()=>s.some(I=>I._type==="PartialBlock"||I._type==="GlobalBlock"),[s]),d=f.useMemo(()=>{let I=[];for(const B of s)if(B._type==="PartialBlock"||B._type==="GlobalBlock"){let R=r(B.partialBlockId);B._parent&&(R==null?void 0:R.length)>0&&(R=R.map(O=>(g.isEmpty(O._parent)&&g.set(O,"_parent",B._parent),O))),I=[...I,...R]}else I.push(B);return I},[s,r]),[h,m]=f.useState(""),[v,p]=f.useState(""),[y,j]=f.useState(""),[x,b]=f.useState(""),[E,P]=f.useState({}),[U,L]=f.useState(!1),[F,re]=f.useState(l),[$,k]=f.useState(!1),{hasPermission:D}=V.usePermissions(),K=D(Se.DELETE_LIBRARY_BLOCK),H=V.useUpdateBlocksPropsRealtime(),X=()=>{H([a],{_libBlockId:void 0}),Q.toast.success("Block delinked from library"),n()},{data:Y,isLoading:W,isError:ie}=mi(o);f.useEffect(()=>{ie&&l&&(k(!0),re(!1))},[ie,l]),f.useEffect(()=>{Y&&!W&&(m(Y.name||""),p(Y.group||""),j(Y.description||""),b(Y.preview||""),re(!1))},[Y,W]),f.useEffect(()=>{const I=h.trim().length>=2,B=v.trim()!=="";L(I&&B)},[h,v]);const je=()=>{const I={};return h.trim()?h.length<2&&(I.name="Name must be at least 2 characters"):I.name="Name is required",v||(I.group="Group is required"),P(I),Object.keys(I).length===0},{resetLibrary:fe}=V.useLibraryBlocks({id:""}),Pe=hi(I=>{l||H([a],{_libBlockId:I.id}),Q.toast.success(`Block ${l?"updated":"saved"} successfully`),fe(I.library),n()}),w=async I=>{if(I.preventDefault(),!je())return;const B=d.map(R=>(g.has(R,"_libBlockId")&&delete R._libBlockId,R));Pe.mutate({name:h.trim(),group:v,blocks:B,description:y.trim(),...x&&x.startsWith("data:")?{previewImage:x}:{},...l?{id:o}:{}})},S=Pe.isPending;return F||W?t.jsx("div",{className:"flex items-center justify-center p-8",children:t.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):$?t.jsxs("div",{className:"p-6 space-y-4",children:[t.jsx("div",{className:"text-destructive font-medium",children:"Block Not Found"}),t.jsx("p",{className:"text-sm text-muted-foreground",children:"This block could not be found on the server. It may have been deleted."}),t.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[t.jsx(c.Button,{type:"button",variant:"outline",onClick:n,children:"Cancel"}),t.jsx(c.Button,{onClick:X,variant:"destructive",children:"Delink Block"})]})]}):t.jsxs("div",{children:[u&&t.jsxs("div",{className:"mb-4 p-3 border border-destructive/50 bg-destructive/10 text-destructive rounded-md flex items-start gap-2",children:[t.jsx(N.AlertCircle,{className:"h-5 w-5 flex-shrink-0 mt-0.5"}),t.jsxs("div",{children:[t.jsx("p",{className:"font-medium",children:"Partial Blocks Detected"}),t.jsx("p",{className:"text-xs mt-1",children:"This block contains one or more Partial Blocks. Partial blocks will be merged into the library block"})]})]}),t.jsxs("form",{onSubmit:w,className:"space-y-4",children:[t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Label,{htmlFor:"name",className:E.name?"text-destructive":"",children:"Name"}),t.jsx(c.Input,{id:"name",placeholder:"Enter block name",value:h,onChange:I=>m(I.target.value),className:E.name?"border-destructive":""}),E.name&&t.jsx("p",{className:"text-xs text-destructive",children:E.name})]}),t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Label,{htmlFor:"group",className:E.group?"text-destructive":"",children:"Group"}),t.jsx(yi,{value:v,onChange:p}),E.group&&t.jsx("p",{className:"text-xs text-destructive",children:E.group})]}),t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Label,{htmlFor:"description",children:"Description (optional)"}),t.jsx(c.Input,{id:"description",placeholder:"Enter a brief description",className:"resize-none",value:y,onChange:I=>j(I.target.value)})]}),t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Label,{htmlFor:"previewImage",children:"Preview Image (optional)"}),t.jsx(ji,{value:x,onChange:b})]}),t.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[l&&K&&t.jsx(xi,{blockId:a,libBlockId:o,blockName:h,className:"mr-auto",close:n}),t.jsx(c.Button,{type:"button",variant:"outline",onClick:n,disabled:S,children:"Cancel"}),t.jsx(c.Button,{type:"submit",disabled:S||!U,children:S?"Saving...":l?"Update Block":"Save Block"})]})]})]})},le={PREVIEW:"Preview",THEME:"Theme",SAVEDRAFT:"Save draft",SAVING:"Saving",SAVED:"Saved",PUBLISHED:"Published",PUBLISH:"Publish",UNPUBLISH:"Unpublish",WEBSITEDATA:"Website data",OPEN:"Open",EDIT_LANGUAGE:"Edit language",ADD_NEW_LANGUAGE:"Add new language page",ENTER_LANGUAGE_DETAILS:"Enter the details for the language",LANGUAGE:"Language",PAGE_NAME:"Page Name",SLUG:"Slug",UPDATE:"Update",UPDATING:"Updating...",ADDING:"Adding...",CHOOSE_LANGUAGE:"Choose language",ALL_AVAILABLE_LANGUAGE_PAGE:"All available language page is created.",TO_UPDATE_SLUG:"To update slug use 'Change slug' action",SLUG_SHOULD_START_WITH:" (Slug should start with /{lang})",CHOOSE_LANGUAGE_TO_ADD_SLUG:"Choose language to add slug",ENTER_PAGE_SLUG:"Enter page slug",ENTER_PAGE_NAME:"Enter page name",DELETE:"Delete",CHANGE_SLUG:"Change slug",PRIMARY:"Primary",SLUG_MUST_START_WITH:"Slug must start with /",EDIT:"Edit",UNPUBLISH_MSG:"Are you sure you want to unpublish",MARK_AS_TEMPLATE:"Mark as template",UNMARK_AS_TEMPLATE:"Unmark as template",PAGE_ADD_SUCCESS:"New page added successfully.",GLOBAL_BLOCK_ADD_SUCCESS:"New global block added successfully.",SEO_SETTINGS_UPDATE_SUCCESS:"SEO Settings updated successfully.",PAGE_UPDATE_SUCCESS:"Page updated successfully.",GLOBAL_BLOCK_UPDATE_SUCCESS:"Global block updated successfully.",PAGE_DELETE_SUCCESS:"Page deleted successfully.",GLOBAL_BLOCK_DELETE_SUCCESS:"Global block deleted successfully.",PAGE_UNPUBLISH_SUCCESS:"Page unpublished successfully.",GLOBAL_BLOCK_UNPUBLISH_SUCCESS:"Global block unpublished successfully.",PAGE_PUBLISH_SUCCESS:"Page published successfully.",GLOBAL_BLOCK_PUBLISH_SUCCESS:"Global block published successfully.",PAGES_PUBLISH_SUCCESS:"Your changes have been published successfully.",SLUG_CHANGE_SUCCESS:"Slug changed successfully."},Si={SLUG_ALREADY_USED:"This slug is already in use. Please choose a different one."},Ae=()=>{const e=oe(),s=se();return G.useQuery({queryKey:[_.GET_PAGE_TYPES],initialData:[],queryFn:async()=>s(e,{action:_.GET_PAGE_TYPES})})},ya=e=>{const{data:s}=Ae();return f.useMemo(()=>s==null?void 0:s.find(n=>n.key===e),[s,e])},wi=()=>{const e=oe(),s=se();return G.useMutation({mutationFn:async({pageType:n,query:a})=>{try{return s(e,{action:_.SEARCH_PAGES,data:{pageType:n,query:Array.isArray(a)&&a.length>0?a[0]:a}})||[]}catch(r){return console.error(r),[]}}})},va=()=>{const e=oe(),s=G.useQueryClient(),n=se(),{data:a}=Ae();return G.useMutation({mutationFn:async r=>await n(e,{action:_.CREATE_PAGE,data:r}),onSuccess:(r,i)=>{var l;i&&(i!=null&&i.primaryPage)?(s.invalidateQueries({queryKey:[_.GET_LANGUAGE_PAGES,i==null?void 0:i.primaryPage]}),s.invalidateQueries({queryKey:[_.GET_WEBSITE_PAGES,i==null?void 0:i.lang]})):s.invalidateQueries({queryKey:[_.GET_WEBSITE_PAGES]});const o=i.template?`Page created from "${i.template.name}" template`:i.hasSlug===!1?"New "+((l=g.find(a,{key:i.pageType}))==null?void 0:l.name)+" added successfully":"New page added successfully";Q.toast.success(o)},onError:(r,i)=>{const o=g.find(a,{key:i.pageType});Q.toast.error(`Failed to add new ${o!=null&&o.hasSlug?"page":o.name}.`,{description:g.get(Si,r.message,r.message)})}})},gn=()=>{const e=oe(),s=G.useQueryClient(),n=se(),{data:a}=Qe(),{data:r}=Ae();return G.useMutation({mutationFn:async i=>await n(e,{action:_.UPDATE_PAGE,data:i}),onSuccess:(i,o)=>{(a==null?void 0:a.id)===(o==null?void 0:o.id)&&s.invalidateQueries({queryKey:[_.GET_LANGUAGE_PAGES]}),o&&(o!=null&&o.primaryPage||o!=null&&o.seo)?(s.invalidateQueries({queryKey:[_.GET_LANGUAGE_PAGES,o==null?void 0:o.primaryPage]}),s.invalidateQueries({queryKey:[_.GET_WEBSITE_PAGES]})):s.invalidateQueries({queryKey:[_.GET_WEBSITE_PAGES]})},onError:(i,o)=>{const l=g.find(r,{key:o.pageType});Q.toast.error(`Failed to update ${l!=null&&l.hasSlug?"page":l.name}.`,{description:i.message})}})},Ei=()=>{const e=oe(),s=G.useQueryClient(),n=se(),{data:a}=Ae();return G.useMutation({mutationFn:async r=>n(e,{action:_.DELETE_PAGE,data:{id:r==null?void 0:r.id}}),onSuccess:(r,i)=>{if(r.code==="PAGE_LOCKED"){Q.toast.error("Delete not allowed",{description:"Page is currently being edited by another user."});return}i&&(i!=null&&i.primaryPage)?(s.invalidateQueries({queryKey:[_.GET_LANGUAGE_PAGES,i==null?void 0:i.primaryPage]}),s.invalidateQueries({queryKey:[_.GET_WEBSITE_PAGES]})):s.invalidateQueries({queryKey:[_.GET_WEBSITE_PAGES]})},onError:(r,i)=>{const o=g.find(a,{key:i.pageType});Q.toast.error(`Failed to delete ${o!=null&&o.hasSlug?"page":o.name}.`,{description:r.message})}})},Ni=()=>{const e=oe(),s=G.useQueryClient(),n=se(),{data:a}=Ae();return G.useMutation({mutationFn:async r=>n(e,{action:_.TAKE_OFFLINE,data:{id:r==null?void 0:r.id}}),onSuccess:(r,i)=>{i&&(i!=null&&i.primaryPage)?s.invalidateQueries({queryKey:[_.GET_LANGUAGE_PAGES,i==null?void 0:i.primaryPage]}):s.invalidateQueries({queryKey:[_.GET_WEBSITE_PAGES]});const o=g.find(a,{key:i.pageType});Q.toast.success(o!=null&&o.hasSlug?le.PAGE_UNPUBLISH_SUCCESS:"New "+o.name+" added successfully.")},onError:(r,i)=>{const o=g.find(a,{key:i.pageType});Q.toast.error(`Failed to take offline ${o!=null&&o.hasSlug?"page":o.name}.`,{description:r.message})}})},xn=()=>{const e=oe(),s=se(),n=G.useQueryClient(),{data:a}=ke(),{savePageAsync:r}=V.useSavePage();return G.useMutation({mutationFn:async({ids:i})=>(await r(),s(e,{action:_.PUBLISH_CHANGES,data:{ids:i}})),onSuccess:()=>{n.invalidateQueries({queryKey:[_.GET_CHANGES]}),n.invalidateQueries({queryKey:[_.GET_WEBSITE_PAGES]}),n.invalidateQueries({queryKey:[_.GET_LANGUAGE_PAGES,a==null?void 0:a.id]})},onError:i=>{console.log("##",i),Q.toast.error("Failed to publish pages.")}})},Ci=()=>{const e=oe(),s=se(),n=G.useQueryClient();return G.useMutation({mutationFn:async a=>{var r;return s(e,{action:_.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:[_.GET_WEBSITE_PAGES]}),Q.toast.success("Page marked as template successfully.")},onError:()=>{Q.toast.error("Failed to mark page as template.")}})},Ti=()=>{const e=oe(),s=se(),n=G.useQueryClient();return G.useMutation({mutationFn:async a=>s(e,{action:_.UNMARK_AS_TEMPLATE,data:{id:a==null?void 0:a.id}}),onSuccess:()=>{n.invalidateQueries({queryKey:[_.GET_WEBSITE_PAGES]}),Q.toast.success("Page unmarked as template successfully.")},onError:()=>{Q.toast.error("Failed to unmark page as template.")}})},Ai=()=>{const e=oe(),s=se(),n=G.useQueryClient();return G.useMutation({mutationFn:async({id:a,slug:r})=>s(e,{action:_.CHANGE_SLUG,data:{id:a,slug:r}}),onSuccess:(a,{primaryPage:r})=>{Q.toast.success(le.SLUG_CHANGE_SUCCESS),r?n.invalidateQueries({queryKey:[_.GET_LANGUAGE_PAGES,r]}):n.invalidateQueries({queryKey:[_.GET_WEBSITE_PAGES]})},onError:()=>{Q.toast.error("Failed to change slug")}})};var pn={};(function e(s,n,a,r){var i=!!(s.Worker&&s.Blob&&s.Promise&&s.OffscreenCanvas&&s.OffscreenCanvasRenderingContext2D&&s.HTMLCanvasElement&&s.HTMLCanvasElement.prototype.transferControlToOffscreen&&s.URL&&s.URL.createObjectURL),o=typeof Path2D=="function"&&typeof DOMMatrix=="function",l=function(){if(!s.OffscreenCanvas)return!1;var w=new OffscreenCanvas(1,1),S=w.getContext("2d");S.fillRect(0,0,1,1);var I=w.transferToImageBitmap();try{S.createPattern(I,"no-repeat")}catch{return!1}return!0}();function u(){}function d(w){var S=n.exports.Promise,I=S!==void 0?S:s.Promise;return typeof I=="function"?new I(w):(w(u,u),null)}var h=function(w,S){return{transform:function(I){if(w)return I;if(S.has(I))return S.get(I);var B=new OffscreenCanvas(I.width,I.height),R=B.getContext("2d");return R.drawImage(I,0,0),S.set(I,B),B},clear:function(){S.clear()}}}(l,new Map),m=function(){var w=Math.floor(16.666666666666668),S,I,B={},R=0;return typeof requestAnimationFrame=="function"&&typeof cancelAnimationFrame=="function"?(S=function(O){var M=Math.random();return B[M]=requestAnimationFrame(function C(q){R===q||R+w-1<q?(R=q,delete B[M],O()):B[M]=requestAnimationFrame(C)}),M},I=function(O){B[O]&&cancelAnimationFrame(B[O])}):(S=function(O){return setTimeout(O,w)},I=function(O){return clearTimeout(O)}),{frame:S,cancel:I}}(),v=function(){var w,S,I={};function B(R){function O(M,C){R.postMessage({options:M||{},callback:C})}R.init=function(C){var q=C.transferControlToOffscreen();R.postMessage({canvas:q},[q])},R.fire=function(C,q,ne){if(S)return O(C,null),S;var z=Math.random().toString(36).slice(2);return S=d(function(J){function ce(me){me.data.callback===z&&(delete I[z],R.removeEventListener("message",ce),S=null,h.clear(),ne(),J())}R.addEventListener("message",ce),O(C,z),I[z]=ce.bind(null,{data:{callback:z}})}),S},R.reset=function(){R.postMessage({reset:!0});for(var C in I)I[C](),delete I[C]}}return function(){if(w)return w;if(!a&&i){var R=["var CONFETTI, SIZE = {}, module = {};","("+e.toString()+")(this, module, true, SIZE);","onmessage = function(msg) {"," if (msg.data.options) {"," CONFETTI(msg.data.options).then(function () {"," if (msg.data.callback) {"," postMessage({ callback: msg.data.callback });"," }"," });"," } else if (msg.data.reset) {"," CONFETTI && CONFETTI.reset();"," } else if (msg.data.resize) {"," SIZE.width = msg.data.resize.width;"," SIZE.height = msg.data.resize.height;"," } else if (msg.data.canvas) {"," SIZE.width = msg.data.canvas.width;"," SIZE.height = msg.data.canvas.height;"," CONFETTI = module.exports.create(msg.data.canvas);"," }","}"].join(`
|
|
2
|
+
`);try{w=new Worker(URL.createObjectURL(new Blob([R])))}catch(O){return typeof console!==void 0&&typeof console.warn=="function"&&console.warn("🎊 Could not load worker",O),null}B(w)}return w}}(),p={particleCount:50,angle:90,spread:45,startVelocity:45,decay:.9,gravity:1,drift:0,ticks:200,x:.5,y:.5,shapes:["square","circle"],zIndex:100,colors:["#26ccff","#a25afd","#ff5e7e","#88ff5a","#fcff42","#ffa62d","#ff36ff"],disableForReducedMotion:!1,scalar:1};function y(w,S){return S?S(w):w}function j(w){return w!=null}function x(w,S,I){return y(w&&j(w[S])?w[S]:p[S],I)}function b(w){return w<0?0:Math.floor(w)}function E(w,S){return Math.floor(Math.random()*(S-w))+w}function P(w){return parseInt(w,16)}function U(w){return w.map(L)}function L(w){var S=String(w).replace(/[^0-9a-f]/gi,"");return S.length<6&&(S=S[0]+S[0]+S[1]+S[1]+S[2]+S[2]),{r:P(S.substring(0,2)),g:P(S.substring(2,4)),b:P(S.substring(4,6))}}function F(w){var S=x(w,"origin",Object);return S.x=x(S,"x",Number),S.y=x(S,"y",Number),S}function re(w){w.width=document.documentElement.clientWidth,w.height=document.documentElement.clientHeight}function $(w){var S=w.getBoundingClientRect();w.width=S.width,w.height=S.height}function k(w){var S=document.createElement("canvas");return S.style.position="fixed",S.style.top="0px",S.style.left="0px",S.style.pointerEvents="none",S.style.zIndex=w,S}function D(w,S,I,B,R,O,M,C,q){w.save(),w.translate(S,I),w.rotate(O),w.scale(B,R),w.arc(0,0,1,M,C,q),w.restore()}function K(w){var S=w.angle*(Math.PI/180),I=w.spread*(Math.PI/180);return{x:w.x,y:w.y,wobble:Math.random()*10,wobbleSpeed:Math.min(.11,Math.random()*.1+.05),velocity:w.startVelocity*.5+Math.random()*w.startVelocity,angle2D:-S+(.5*I-Math.random()*I),tiltAngle:(Math.random()*(.75-.25)+.25)*Math.PI,color:w.color,shape:w.shape,tick:0,totalTicks:w.ticks,decay:w.decay,drift:w.drift,random:Math.random()+2,tiltSin:0,tiltCos:0,wobbleX:0,wobbleY:0,gravity:w.gravity*3,ovalScalar:.6,scalar:w.scalar,flat:w.flat}}function H(w,S){S.x+=Math.cos(S.angle2D)*S.velocity+S.drift,S.y+=Math.sin(S.angle2D)*S.velocity+S.gravity,S.velocity*=S.decay,S.flat?(S.wobble=0,S.wobbleX=S.x+10*S.scalar,S.wobbleY=S.y+10*S.scalar,S.tiltSin=0,S.tiltCos=0,S.random=1):(S.wobble+=S.wobbleSpeed,S.wobbleX=S.x+10*S.scalar*Math.cos(S.wobble),S.wobbleY=S.y+10*S.scalar*Math.sin(S.wobble),S.tiltAngle+=.1,S.tiltSin=Math.sin(S.tiltAngle),S.tiltCos=Math.cos(S.tiltAngle),S.random=Math.random()+2);var I=S.tick++/S.totalTicks,B=S.x+S.random*S.tiltCos,R=S.y+S.random*S.tiltSin,O=S.wobbleX+S.random*S.tiltCos,M=S.wobbleY+S.random*S.tiltSin;if(w.fillStyle="rgba("+S.color.r+", "+S.color.g+", "+S.color.b+", "+(1-I)+")",w.beginPath(),o&&S.shape.type==="path"&&typeof S.shape.path=="string"&&Array.isArray(S.shape.matrix))w.fill(je(S.shape.path,S.shape.matrix,S.x,S.y,Math.abs(O-B)*.1,Math.abs(M-R)*.1,Math.PI/10*S.wobble));else if(S.shape.type==="bitmap"){var C=Math.PI/10*S.wobble,q=Math.abs(O-B)*.1,ne=Math.abs(M-R)*.1,z=S.shape.bitmap.width*S.scalar,J=S.shape.bitmap.height*S.scalar,ce=new DOMMatrix([Math.cos(C)*q,Math.sin(C)*q,-Math.sin(C)*ne,Math.cos(C)*ne,S.x,S.y]);ce.multiplySelf(new DOMMatrix(S.shape.matrix));var me=w.createPattern(h.transform(S.shape.bitmap),"no-repeat");me.setTransform(ce),w.globalAlpha=1-I,w.fillStyle=me,w.fillRect(S.x-z/2,S.y-J/2,z,J),w.globalAlpha=1}else if(S.shape==="circle")w.ellipse?w.ellipse(S.x,S.y,Math.abs(O-B)*S.ovalScalar,Math.abs(M-R)*S.ovalScalar,Math.PI/10*S.wobble,0,2*Math.PI):D(w,S.x,S.y,Math.abs(O-B)*S.ovalScalar,Math.abs(M-R)*S.ovalScalar,Math.PI/10*S.wobble,0,2*Math.PI);else if(S.shape==="star")for(var A=Math.PI/2*3,Z=4*S.scalar,Ee=8*S.scalar,De=S.x,Ge=S.y,ee=5,Ce=Math.PI/ee;ee--;)De=S.x+Math.cos(A)*Ee,Ge=S.y+Math.sin(A)*Ee,w.lineTo(De,Ge),A+=Ce,De=S.x+Math.cos(A)*Z,Ge=S.y+Math.sin(A)*Z,w.lineTo(De,Ge),A+=Ce;else w.moveTo(Math.floor(S.x),Math.floor(S.y)),w.lineTo(Math.floor(S.wobbleX),Math.floor(R)),w.lineTo(Math.floor(O),Math.floor(M)),w.lineTo(Math.floor(B),Math.floor(S.wobbleY));return w.closePath(),w.fill(),S.tick<S.totalTicks}function X(w,S,I,B,R){var O=S.slice(),M=w.getContext("2d"),C,q,ne=d(function(z){function J(){C=q=null,M.clearRect(0,0,B.width,B.height),h.clear(),R(),z()}function ce(){a&&!(B.width===r.width&&B.height===r.height)&&(B.width=w.width=r.width,B.height=w.height=r.height),!B.width&&!B.height&&(I(w),B.width=w.width,B.height=w.height),M.clearRect(0,0,B.width,B.height),O=O.filter(function(me){return H(M,me)}),O.length?C=m.frame(ce):J()}C=m.frame(ce),q=J});return{addFettis:function(z){return O=O.concat(z),ne},canvas:w,promise:ne,reset:function(){C&&m.cancel(C),q&&q()}}}function Y(w,S){var I=!w,B=!!x(S||{},"resize"),R=!1,O=x(S,"disableForReducedMotion",Boolean),M=i&&!!x(S||{},"useWorker"),C=M?v():null,q=I?re:$,ne=w&&C?!!w.__confetti_initialized:!1,z=typeof matchMedia=="function"&&matchMedia("(prefers-reduced-motion)").matches,J;function ce(A,Z,Ee){for(var De=x(A,"particleCount",b),Ge=x(A,"angle",Number),ee=x(A,"spread",Number),Ce=x(A,"startVelocity",Number),cs=x(A,"decay",Number),qs=x(A,"gravity",Number),zs=x(A,"drift",Number),us=x(A,"colors",U),Vs=x(A,"ticks",Number),ds=x(A,"shapes"),$s=x(A,"scalar"),Ks=!!x(A,"flat"),hs=F(A),Dt=De,nt=[],ct=w.width*hs.x,ms=w.height*hs.y;Dt--;)nt.push(K({x:ct,y:ms,angle:Ge,spread:ee,startVelocity:Ce,color:us[Dt%us.length],shape:ds[E(0,ds.length)],ticks:Vs,decay:cs,gravity:qs,drift:zs,scalar:$s,flat:Ks}));return J?J.addFettis(nt):(J=X(w,nt,q,Z,Ee),J.promise)}function me(A){var Z=O||x(A,"disableForReducedMotion",Boolean),Ee=x(A,"zIndex",Number);if(Z&&z)return d(function(Ce){Ce()});I&&J?w=J.canvas:I&&!w&&(w=k(Ee),document.body.appendChild(w)),B&&!ne&&q(w);var De={width:w.width,height:w.height};C&&!ne&&C.init(w),ne=!0,C&&(w.__confetti_initialized=!0);function Ge(){if(C){var Ce={getBoundingClientRect:function(){if(!I)return w.getBoundingClientRect()}};q(Ce),C.postMessage({resize:{width:Ce.width,height:Ce.height}});return}De.width=De.height=null}function ee(){J=null,B&&(R=!1,s.removeEventListener("resize",Ge)),I&&w&&(document.body.contains(w)&&document.body.removeChild(w),w=null,ne=!1)}return B&&!R&&(R=!0,s.addEventListener("resize",Ge,!1)),C?C.fire(A,De,ee):ce(A,De,ee)}return me.reset=function(){C&&C.reset(),J&&J.reset()},me}var W;function ie(){return W||(W=Y(null,{useWorker:!0,resize:!0})),W}function je(w,S,I,B,R,O,M){var C=new Path2D(w),q=new Path2D;q.addPath(C,new DOMMatrix(S));var ne=new Path2D;return ne.addPath(q,new DOMMatrix([Math.cos(M)*R,Math.sin(M)*R,-Math.sin(M)*O,Math.cos(M)*O,I,B])),ne}function fe(w){if(!o)throw new Error("path confetti are not supported in this browser");var S,I;typeof w=="string"?S=w:(S=w.path,I=w.matrix);var B=new Path2D(S),R=document.createElement("canvas"),O=R.getContext("2d");if(!I){for(var M=1e3,C=M,q=M,ne=0,z=0,J,ce,me=0;me<M;me+=2)for(var A=0;A<M;A+=2)O.isPointInPath(B,me,A,"nonzero")&&(C=Math.min(C,me),q=Math.min(q,A),ne=Math.max(ne,me),z=Math.max(z,A));J=ne-C,ce=z-q;var Z=10,Ee=Math.min(Z/J,Z/ce);I=[Ee,0,0,Ee,-Math.round(J/2+C)*Ee,-Math.round(ce/2+q)*Ee]}return{type:"path",path:S,matrix:I}}function Pe(w){var S,I=1,B="#000000",R='"Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji", "EmojiOne Color", "Android Emoji", "Twemoji Mozilla", "system emoji", sans-serif';typeof w=="string"?S=w:(S=w.text,I="scalar"in w?w.scalar:I,R="fontFamily"in w?w.fontFamily:R,B="color"in w?w.color:B);var O=10*I,M=""+O+"px "+R,C=new OffscreenCanvas(O,O),q=C.getContext("2d");q.font=M;var ne=q.measureText(S),z=Math.ceil(ne.actualBoundingBoxRight+ne.actualBoundingBoxLeft),J=Math.ceil(ne.actualBoundingBoxAscent+ne.actualBoundingBoxDescent),ce=2,me=ne.actualBoundingBoxLeft+ce,A=ne.actualBoundingBoxAscent+ce;z+=ce+ce,J+=ce+ce,C=new OffscreenCanvas(z,J),q=C.getContext("2d"),q.font=M,q.fillStyle=B,q.fillText(S,me,A);var Z=1/I;return{type:"bitmap",bitmap:C.transferToImageBitmap(),matrix:[Z,0,0,Z,-z*Z/2,-J*Z/2]}}n.exports=function(){return ie().apply(this,arguments)},n.exports.reset=function(){ie().reset()},n.exports.create=Y,n.exports.shapeFromPath=fe,n.exports.shapeFromText=Pe})(function(){return typeof window<"u"?window:typeof self<"u"?self:this||{}}(),pn,!1);const ki=pn.exports;pn.exports.create;const Pi={particleCount:350,spread:120,origin:{y:.6},angle:90},Ii={TOP_RIGHT:{angle:225,origin:{x:.9,y:0}},BOTTOM_RIGHT:{angle:100,origin:{x:.9,y:.9}}},Gt=e=>{let s=Ii[e];s||(s={});const n={...Pi,...s};ki(n)},_i=()=>{const[e]=V.useTheme(),{mutate:s,isPending:n}=xn(),{mutateAsync:a,isPending:r}=oa(),i=()=>{a({settings:{theme:e}})},o=async()=>{await a({settings:{theme:e}}),s({ids:["THEME"]},{onSuccess:()=>{Gt("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:o,children:"Publish"})]})},We=()=>{const{data:e}=$e();return f.useMemo(()=>(e==null?void 0:e.fallbackLang)||"en",[e])},_t=()=>{const e=se(),s=oe();return G.useQuery({queryKey:[_.GET_WEBSITE_PAGES],staleTime:1e3*60*5,queryFn:async()=>e(s,{action:_.GET_WEBSITE_PAGES})||[],placeholderData:n=>n||[]})},Li=e=>{const s=se(),n=oe(),a=We();return G.useQuery({queryKey:[_.GET_WEBSITE_PAGES,e,a],staleTime:1e3*60*5,enabled:!!e,queryFn:async()=>{if(a===e)return{};const r=await s(n,{action:_.GET_WEBSITE_PAGES,data:{lang:e}})||[];return g.keyBy(g.map(r,i=>({...i,lang:e})),"primaryPage")},placeholderData:r=>r||{}})};function Rt(e,s,n=!1){const a=e.toString()?`?${e.toString()}`:"/";n?window.history.replaceState(null,"",a):window.history.pushState({},"",a),s(e),window.dispatchEvent(new PopStateEvent("popstate"))}const os=ye.atom(null),Di=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}},lt=e=>{if(!e)return e;const{base:s}=Di(e);return s};function Bi(e,s){const n=(e||"").split("/").filter(Boolean);let a="",r=!0;if(s.slug==="/"){const i=n.pop()||"";if(we[i])r=!0;else{a=i;const o=n.pop()||"";r=!!we[o]}}else if(s.parent)n.length&&(a=n.pop()||"");else if(n.length){a=n.pop()||"";const i=n.pop()||"";r=!!we[i]}return{initSlug:a,prefix:r}}const Oi=e=>e&<(e),Dn=(e,s)=>{const n=lt(e||"");return!n||n==="/"?`/${s}`:`${n}/${s}`};function yn({value:e,onChange:s,placeholder:n,parentSlug:a,onValidationChange:r,disabled:i=!1,fullSlug:o}){const[l,u]=f.useState(e),[d,h]=f.useState(null);f.useEffect(()=>{u(e)},[e]);const m=v=>{const y=v.target.value.replace(/\//g,"").replace(/\s+/g,"-").replace(/[^a-zA-Z0-9-_.]/g,"-").replace(/-+/g,"-").replace(/^-+/,"").toLowerCase(),j=(y.match(/\./g)||[]).length,x=j<=1;j>1?h("Invalid slug. Only one dot (.) is allowed in the slug"):h(null),r&&r(x),u(y),s(y)};return t.jsxs("div",{children:[a&&t.jsx("div",{className:"mb-1 flex items-center",children:t.jsxs("span",{className:"text-xs text-gray-500",children:["Parent: ",t.jsx("span",{className:"font-mono text-gray-900",children:Oi(a)})]})}),t.jsxs("div",{className:"relative",children:[t.jsx(c.Input,{disabled:i,value:l,onChange:m,placeholder:n,className:d?"border-red-500":""}),d&&t.jsx("div",{className:"mt-1 text-xs text-red-500",children:d})]}),o&&o!=="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:o})]})})]})}const ja=({edit:e,lang:s,languages:n,name:a,setLang:r,setName:i,primaryPageObject:o})=>t.jsxs("div",{className:"space-y-1",children:[t.jsx(c.Label,{htmlFor:"lang",children:le.LANGUAGE}),t.jsxs("select",{value:e?"":s,disabled:e||!n.length,onChange:l=>{const u=l.target.value;r(u),!e&&(g.startsWith(a,o==null?void 0:o.name)||a.length===0)&&i(`${o==null?void 0:o.name} - ${we[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?we[s]||s:n.length?le.CHOOSE_LANGUAGE:le.ALL_AVAILABLE_LANGUAGE_PAGE}),n.map(l=>t.jsx("option",{value:l,children:we[l]||l},l))]})]}),ba=({lang:e,name:s,setName:n,parentHasSelectedLanguagePage:a})=>t.jsxs("div",{className:"space-y-1",children:[t.jsx(c.Label,{htmlFor:"name",children:le.PAGE_NAME}),t.jsx(c.Input,{id:"name",value:e?s:"",onChange:r=>n(r.target.value),required:!0,placeholder:e?le.ENTER_PAGE_NAME:le.CHOOSE_LANGUAGE_TO_ADD_SLUG,disabled:!a||!e})]}),Mi=({dynamic:e,isNonSlugPageType:s,isRootPage:n,lang:a,useLanguagePrefix:r,setUseLanguagePrefix:i,isHomePage:o,parentSlug:l,parentHasSelectedLanguagePage:u,slug:d,setSlug:h,setIsSlugValid:m,getSlug:v})=>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:p=>i(p.target.checked),className:"rounded border-gray-300"}),t.jsxs(c.Label,{htmlFor:"useLanguagePrefix",className:"text-sm font-normal leading-tight",children:["Add language code (",t.jsxs("span",{className:"font-mono text-gray-900",children:["/",a]}),") as slug prefix"]})]}),t.jsx(c.Label,{htmlFor:"slug",children:le.SLUG}),e?t.jsx(c.Alert,{variant:"default",className:"p-2 text-xs font-medium italic text-muted-foreground",children:"This page will use dynamic slug as defined in primary page"}):t.jsx(yn,{disabled:!a||!u,value:d,onChange:h,placeholder:a?o&&r?"Leave empty for home page":le.ENTER_PAGE_SLUG:le.CHOOSE_LANGUAGE_TO_ADD_SLUG,parentSlug:l,onValidationChange:m,fullSlug:v()})]}),Sa=({parentHasSelectedLanguagePage:e,name:s,lang:n,slug:a,edit:r,id:i,primaryPageObject:o,pages:l,isNonSlugPageType:u,isHomePage:d,useLanguagePrefix:h,isSlugValid:m,isPending:v})=>{const p=v||!s||!n||l.some(y=>(r?y.id!==i:!0)&&y.parent===(o==null?void 0:o.id)&&y.lang===n)||!u&&!(d&&h)&&(!m||!a);return t.jsx(c.DialogFooter,{children:e?t.jsxs(t.Fragment,{children:[t.jsx(c.Button,{type:"submit",disabled:p&&!o.dynamic,children:v?t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsx("span",{className:"loader mr-2"}),r?le.UPDATING:le.ADDING]}):r?le.UPDATE:le.ADD_NEW_LANGUAGE}),l.some(y=>(r?y.id!==i:!0)&&y.parent===(o==null?void 0:o.id)&&y.lang===n)&&t.jsx("p",{className:"mt-2 text-xs text-red-500",children:"A page for this language already exists."})]}):n&&t.jsx(c.Alert,{variant:"destructive",children:t.jsxs("p",{className:"mx-auto w-5/6 text-center",children:["You need to create the ",t.jsx("span",{className:"font-medium",children:we[n]})," page in the parent to add here."]})})})},Gi=({onSubmit:e,edit:s,lang:n,languages:a,name:r,setLang:i,setName:o,primaryPageObject:l,parentHasSelectedLanguagePage:u,id:d,pages:h,isNonSlugPageType:m,isHomePage:v,useLanguagePrefix:p,slug:y,isSlugValid:j,isPending:x})=>t.jsxs("form",{onSubmit:e,children:[t.jsxs("div",{className:"grid gap-4 py-4",children:[t.jsx(ja,{edit:s,lang:n,languages:a,name:r,setLang:i,setName:o,primaryPageObject:l}),t.jsx(ba,{lang:n,name:r,setName:o,parentHasSelectedLanguagePage:u})]}),t.jsx(Sa,{parentHasSelectedLanguagePage:u,name:r,lang:n,slug:y,edit:s,id:d,primaryPageObject:l,pages:h,isNonSlugPageType:m,isHomePage:v,useLanguagePrefix:p,isSlugValid:j,isPending:x})]}),Ri=({loading:e,onSubmit:s,edit:n,lang:a,languages:r,name:i,setLang:o,setName:l,primaryPageObject:u,parentHasSelectedLanguagePage:d,isNonSlugPageType:h,isRootPage:m,useLanguagePrefix:v,setUseLanguagePrefix:p,isHomePage:y,parentSlug:j,slug:x,setSlug:b,isSlugValid:E,setIsSlugValid:P,getSlug:U,isPending:L,id:F,pages:re})=>e?t.jsx("div",{className:"flex h-80 items-center justify-center",children:t.jsx(N.Loader,{className:"animate-spin"})}):h?t.jsx(Gi,{onSubmit:s,edit:n,lang:a,languages:r,name:i,setLang:o,setName:l,primaryPageObject:u,parentHasSelectedLanguagePage:d,id:F,pages:re,isNonSlugPageType:h,isHomePage:y,useLanguagePrefix:v,slug:x,isSlugValid:E,isPending:L}):t.jsxs("form",{onSubmit:s,children:[t.jsxs("div",{className:"grid gap-4 py-4",children:[t.jsx(ja,{edit:n,lang:a,languages:r,name:i,setLang:o,setName:l,primaryPageObject:u}),t.jsx(ba,{lang:a,name:i,setName:l,parentHasSelectedLanguagePage:d}),t.jsx(Mi,{dynamic:u==null?void 0:u.dynamic,isNonSlugPageType:h,isRootPage:m,lang:a,useLanguagePrefix:v,setUseLanguagePrefix:p,isHomePage:y,parentSlug:j,parentHasSelectedLanguagePage:d,slug:x,setSlug:b,isSlugValid:E,setIsSlugValid:P,getSlug:U})]}),t.jsx(Sa,{parentHasSelectedLanguagePage:d,name:i,lang:a,slug:x,edit:n,id:F,primaryPageObject:u,pages:re,isNonSlugPageType:h,isHomePage:y,useLanguagePrefix:v,isSlugValid:E,isPending:L})]}),Ui=({id:e,isOpen:s,onClose:n,primaryPage:a,edit:r=!1,preselectedLang:i})=>{const{data:o=[]}=_t(),l=f.useMemo(()=>o.find(z=>z.id===a),[o,a]),[u,d]=f.useState(""),[h,m]=f.useState(""),[v,p]=f.useState(""),[y,j]=f.useState(!0),[x,b]=f.useState(!0),{mutate:E,isPending:P}=va(),{mutate:U,isPending:L}=gn(),F=P||L,{data:re,isFetching:$}=$e(),k=We(),{data:D,isFetching:K}=Oe(a),{data:H=[],isFetching:X}=Oe(l==null?void 0:l.parent),{data:Y=[],isFetching:W}=Ae(),{setSelectedLang:ie}=V.useLanguages(),[,je]=_e(),[,fe]=V.useSidebarActivePanel(),Pe=$||K||X||W,w=f.useMemo(()=>g.filter(re==null?void 0:re.languages,z=>!g.find(D,{lang:z})),[re,D]),S=f.useMemo(()=>Y.find(z=>z.key===(l==null?void 0:l.pageType)),[Y,l==null?void 0:l.pageType]),I=!(S!=null&&S.hasSlug),B=(l==null?void 0:l.slug)==="/";f.useEffect(()=>{if(!r&&l&&i&&(m(i),d(`${l.name} - ${we[i]}`)),!r||!l)return;const z=D==null?void 0:D.find(A=>A.id===e);if(!z)return;d(z.name),m(z.lang);const J=z.slug||"",{initSlug:ce,prefix:me}=Bi(J,l);p(ce),b(me)},[r,e,D,l,i]),f.useEffect(()=>{if(i)m(i);else if((w==null?void 0:w.length)===1&&!r){const z=w[0];if(!z||!we[z])return;m(z),(!u||u===(l==null?void 0:l.name))&&d(`${l==null?void 0:l.name} - ${we[z]}`)}},[i,w,r,u,l]);const{parentSlug:R,isRootPage:O}=f.useMemo(()=>{if(B||!h)return{parentSlug:void 0,isRootPage:!(l!=null&&l.parent)};if(!(l!=null&&l.parent))return{parentSlug:x?`/${h}`:void 0,isRootPage:!0};const z=H==null?void 0:H.find(J=>J.lang===h);return{parentSlug:z==null?void 0:z.slug,isRootPage:!1}},[l==null?void 0:l.parent,H,x,h,B]),M=f.useMemo(()=>O?!0:!!(H!=null&&H.some(z=>(z==null?void 0:z.lang)===h)),[h,H,O]),C=()=>{let z="";return O?z=`/${x?[h,v].filter(Boolean).join("/"):v}`:z=`${lt(R)}/${v}`,z.replace(/\/{2,}/g,"/").replace(/\/$/,"")},q=z=>{const J=new URLSearchParams(window.location.search);k&&z===k?J.delete("lang"):J.set("lang",z),je(J),window.dispatchEvent(new PopStateEvent("popstate"))},ne=z=>{z.preventDefault();const J={name:u,lang:h,primaryPage:l==null?void 0:l.id,slug:I?"":C(),pageType:l==null?void 0:l.pageType,...r&&{id:e}},ce=()=>{!r&&h&&(ie(h),q(h)),fe("outline"),n()};r?U(J,{onSuccess:ce}):E(J,{onSuccess:ce})};return t.jsx(c.Dialog,{open:s,onOpenChange:n,children:t.jsxs(c.DialogContent,{className:"text-slate-600 sm:max-w-[425px]",children:[t.jsxs(c.DialogHeader,{children:[t.jsx(c.DialogTitle,{children:r?le.EDIT_LANGUAGE:le.ADD_NEW_LANGUAGE}),t.jsx(c.DialogDescription,{className:"font-light",children:le.ENTER_LANGUAGE_DETAILS})]}),t.jsx(Ri,{id:e,pages:o,loading:Pe,onSubmit:ne,edit:r,lang:h,languages:w,name:u,setLang:m,setName:d,primaryPageObject:l,parentHasSelectedLanguagePage:M,isNonSlugPageType:I,isRootPage:O,useLanguagePrefix:x,setUseLanguagePrefix:b,isHomePage:B,parentSlug:R,slug:v,setSlug:p,isSlugValid:y,setIsSlugValid:j,getSlug:C,isPending:F})]})})},Fi=aa("expandedPagesState",[]),vn=e=>g.flatMap(e,s=>[s,...s.children?vn(s.children):[]]),qi=(e,s)=>{const n=(a,r=[])=>{for(const i of a){const o=[...r,i.id];if(i.id===s)return o;if(i.children&&i.children.length>0){const l=n(i.children,o);if(l)return l}}return null};return n(e)||[]},wa=(e,s)=>{if(!s)return[];const n=vn(e),a=g.find(n,r=>r.id===s);if(a){if(a.parent)return[...wa(e,a.parent),s];const r=qi(e,s);if(!g.isEmpty(r))return r}return[s]},zi=e=>{const s=new Set,n=(a,r=[])=>{a.forEach(i=>{const o=[...r,i.id];i.shouldExpandOnSearch&&o.forEach(l=>s.add(l)),i.children&&!g.isEmpty(i.children)&&n(i.children,o)})};return n(e),Array.from(s)},Ms=e=>{const[s,n]=ye.useAtom(Fi),a=e?g.includes(s,e):!1,r=f.useCallback(()=>{n(d=>a?g.filter(d,h=>h!==e):[...d,e])},[n,a,e]),i=f.useCallback((d,h)=>{if(!h||g.isEmpty(d))return;const m=vn(d),v=wa(m,h);if(!Array.isArray(v)||g.isEmpty(v))return;const p=v.slice(0,-1);g.isEmpty(p)||n(y=>g.uniq([...y,...p]))},[n]),o=f.useCallback(d=>{if(g.isEmpty(d))return;const h=zi(d);g.isEmpty(h)||n(m=>g.union(m,h))},[n]),l=f.useCallback(d=>{if(g.isEmpty(d))return;const h=g.flatMap(d,m=>{const v=p=>[p.id,...p.children?g.flatMap(p.children,v):[]];return v(m)});n(h)},[n]),u=f.useCallback(()=>{n([])},[n]);return{isExpanded:a,toggleExpanded:r,updateForSelectedPage:i,expandedPages:s,expandPagesOnSearch:o,setExpandedPages:n,expandAll:l,collapseAll:u}},Bn=(e,s)=>!e||!Array.isArray(e)?[]:g.isEmpty(s)?e:g.compact(g.filter(e,n=>{const a=g.toLower(s);return g.includes(g.toLower((n==null?void 0:n.name)||""),a)||g.includes(g.toLower((n==null?void 0:n.slug)||""),a)})),Vi=(e,s)=>{const n=new Set,a=g.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])},en=(e,s,n)=>g.isEmpty(s)?e:e.map(a=>{if(!n(a.pageType))return{...a,shouldExpandOnSearch:!0,children:a.children?en(a.children,s,n):[]};const r=a.children&&a.children.some(i=>g.includes(g.toLower(i.name||""),g.toLower(s))||g.includes(g.toLower(i.slug||""),g.toLower(s)));return{...a,shouldExpandOnSearch:r,children:a.children?en(a.children,s,n):[]}}),$i=e=>{if(!e||!e.length)return[];const s={};e.forEach(a=>{s[a.id]={...a,children:[]}});const n=[];return Object.values(s).forEach(a=>{a.parent&&s[a.parent]?s[a.parent].children.push(a):n.push(a)}),n},Ea=e=>!e||!e.length?[]:[...e].sort((n,a)=>(n.name||"").localeCompare(a.name||"")).map(n=>({...n,children:n.children?Ea(n.children):[]})),Ki=(e,s,n,a)=>{if(!e||!e.length)return[];let r=e;if(n!=="all"&&(r=g.compact(g.filter(e,{pageType:n}))),g.isEmpty(s))r=Bn(r,s);else{const h=Bn(r,s),m=Vi(e,h);r=g.uniqBy([...h,...m],"id")}const i=Ea($i(r)),o=en(i,s,a),l=g.filter(o,h=>a(h.pageType)).sort((h,m)=>(h.name||"").localeCompare(m.name||"")),u=g.filter(o,h=>!a(h.pageType));let d=[];if(n==="all"){const h=g.keyBy(u,"pageType");d=Object.values(g.mapValues(h,(m,v)=>({...m,id:v,name:g.startCase(v),isPartialGroup:!0,children:o.filter(p=>p.pageType===v)})))}else d=u.sort((h,m)=>(h.name||"").localeCompare(m.name||""));return[...l,...d]},Hi=({selectedPageType:e,setSelectedPageType:s})=>{const[n,a]=f.useState(""),{data:r}=Ae(),i=l=>{if(!n)return!0;const u=n.toLowerCase(),d=h=>String(g.get(l,h,"")).toLowerCase().includes(u);return d("name")||d("key")},o=r.find(l=>l.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:(o==null?void 0:o.name)||"All"}),t.jsx(N.ListFilter,{className:`${e!=="all"?"fill-sky-50 text-sky-500":""} pointer-events-none h-4 w-4 text-muted-foreground hover:bg-blue-300`})]})}),t.jsxs(c.SelectContent,{children:[t.jsx("div",{className:"sticky top-0 z-10 bg-white pb-2",children:t.jsxs("div",{className:"relative",children:[t.jsx(N.Search,{strokeWidth:2,className:"absolute left-2 top-2.5 h-3.5 w-3.5 text-gray-400"}),t.jsx(c.Input,{placeholder:"Search page types...",className:"h-8 w-full rounded border pl-8 text-xs shadow-none",value:n,onChange:l=>a(l.target.value),onKeyDown:l=>l.stopPropagation()})]})}),t.jsx(c.SelectItem,{value:"all",children:"All"}),!g.isEmpty(g.filter(r,l=>l.hasSlug&&i(l)))&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"mt-2 border-t px-2 py-1.5 pt-2 text-xs font-semibold text-gray-500",children:"Pages"}),g.map([...g.filter(r,l=>l.hasSlug&&i(l))].sort((l,u)=>g.get(l,"name","").localeCompare(g.get(u,"name",""))),l=>t.jsx(c.SelectItem,{value:g.get(l,"key"),children:g.get(l,"name")},g.get(l,"key")))]}),!g.isEmpty(g.filter(r,l=>!l.hasSlug&&i(l)))&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"mt-2 border-t px-2 py-1.5 pt-2 text-xs font-semibold text-gray-500",children:"Partials"}),g.map([...g.filter(r,l=>!l.hasSlug&&i(l))].sort((l,u)=>g.get(l,"name","").localeCompare(g.get(u,"name",""))),l=>t.jsx(c.SelectItem,{value:g.get(l,"key"),children:g.get(l,"name")},g.get(l,"key")))]}),g.isEmpty(g.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(N.Search,{className:`${e?"fill-sky-50 text-sky-500":""} pointer-events-none h-4 w-4 text-muted-foreground`,"aria-hidden":"true"}),t.jsx(c.Input,{id:"page-search-input",placeholder:"Search pages",value:e,onChange:n=>s(n.target.value),className:"border-none px-1.5 shadow-none outline-none ring-0 transition-none focus:outline-none focus:ring-0 focus-visible:ring-0",autoComplete:"off"})]}),Wi=({pages:e})=>{const{expandAll:s,collapseAll:n,expandedPages:a}=Ms(null);return t.jsxs("div",{className:"flex gap-1",children:[t.jsxs(c.Tooltip,{children:[t.jsx(c.TooltipTrigger,{asChild:!0,children:t.jsx(c.Button,{variant:"outline",size:"icon",onClick:()=>s(e),className:"rounded p-1 text-gray-500",children:t.jsx(N.ChevronsUpDown,{})})}),t.jsx(c.TooltipContent,{children:"Expand All"})]}),t.jsxs(c.Tooltip,{children:[t.jsx(c.TooltipTrigger,{asChild:!0,children:t.jsx(c.Button,{disabled:a.length===0,variant:"outline",size:"icon",onClick:()=>n(),className:"rounded p-1 text-gray-500",children:t.jsx(N.ChevronsDownUp,{})})}),t.jsx(c.TooltipContent,{children:"Collapse All"})]})]})},Na=({languages:e,selectedLanguage:s,setSelectedLanguage:n})=>{const a=We();return t.jsx("div",{className:"scrollbar-hide flex gap-1 overflow-x-auto pb-1",children:e.map(r=>t.jsxs(c.Button,{variant:s===r?"default":"outline",size:"sm",className:`h-6 flex-shrink-0 whitespace-nowrap rounded px-3 text-xs font-normal ${s===r?"bg-black text-white hover:bg-black":"text-gray-500"}`,onClick:()=>n(r.toLowerCase()),children:[r===a&&t.jsx(N.Star,{size:4,className:`p-0.5 ${s===a?"fill-white":"fill-black"}`}),we[r]||""]},r))})},On=()=>{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:[_.GET_WEBSITE_PAGES]}),className:"mt-1 h-6 w-6",children:t.jsx(N.RefreshCw,{})})}),t.jsx(c.TooltipContent,{side:"bottom",children:"Refresh pages list"})]})},Ji=({pages:e,search:s,setSearch:n,languages:a,onAddPage:r,selectedLanguage:i,setSelectedLanguage:o,selectedPageType:l,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:l,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(N.Plus,{strokeWidth:2,className:"stroke-white stroke-[3]"}),t.jsx("span",{className:"font-normal text-white",children:"Add Page"})]}),!m&&t.jsx(On,{})]}),m?t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx(Na,{languages:a,selectedLanguage:i,setSelectedLanguage:v=>{o(v),h(d&&(a==null?void 0:a[0])!==i)}}),t.jsxs("div",{className:"flex items-center gap-x-2",children:[(a==null?void 0:a[0])!==i&&t.jsxs(c.Tooltip,{children:[t.jsx(c.TooltipTrigger,{asChild:!0,children:t.jsx(c.Button,{variant:"ghost",onClick:()=>h(!d),className:"h-6 rounded px-3 py-1 text-xs font-normal",children:d?t.jsx(N.FilterXIcon,{}):t.jsx(N.Filter,{})})}),t.jsx(c.TooltipContent,{side:"bottom",children:"Toggle Untranslated Pages"})]}),t.jsx(On,{})]})]}):t.jsx("div",{className:"flex items-center justify-between gap-2"})]})};function Xe({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 Ca=({page:e,setDuplicatePage:s,setAddEditPage:n,setUnpublishPage:a,setDeletePage:r,setMarkAsTemplate:i,setUnmarkAsTemplate:o,children:l,isLanguagePage:u})=>{const{hasPermission:d}=V.usePermissions(),{data:h}=Ae(),m=f.useMemo(()=>g.find(h,{key:e.pageType}),[h,e.pageType]),v=f.useMemo(()=>!!e.isTemplate,[e.isTemplate]),p=f.useMemo(()=>!!(m!=null&&m.hasSlug),[m==null?void 0:m.hasSlug]);return!d(Se.EDIT_PAGE)&&!d(Se.DELETE_PAGE)&&!d(Se.UNPUBLISH_PAGE)||!e?null:t.jsxs(c.DropdownMenu,{children:[t.jsx(c.DropdownMenuTrigger,{asChild:!0,onClick:j=>j.stopPropagation(),children:l}),t.jsxs(c.DropdownMenuContent,{align:"center",className:"text-sm",children:[d(Se.ADD_PAGE)&&!u&&t.jsxs(c.DropdownMenuItem,{className:"flex cursor-pointer items-center gap-2",onClick:j=>{j.stopPropagation(),s(e)},children:[t.jsx(N.CopyPlusIcon,{className:"size-3"}),"Duplicate page"]}),d(Se.EDIT_PAGE)&&t.jsxs(c.DropdownMenuItem,{className:"flex cursor-pointer items-center gap-2",onClick:j=>{j.stopPropagation(),n({...e,global:!(m!=null&&m.hasSlug)})},children:[t.jsx(N.Pencil,{className:"size-3"}),"Edit"]}),(e==null?void 0:e.online)&&d(Se.UNPUBLISH_PAGE)&&t.jsxs(c.DropdownMenuItem,{className:"flex cursor-pointer items-center gap-2",onClick:j=>{j.stopPropagation(),a(e)},children:[t.jsx(N.Power,{className:"size-3"}),le.UNPUBLISH]}),d(Se.DELETE_PAGE)&&t.jsxs(c.DropdownMenuItem,{className:"flex cursor-pointer items-center gap-2",onClick:j=>{j.stopPropagation(),r(e)},children:[t.jsx(N.Trash,{className:"size-3"}),le.DELETE]}),d(Se.MARK_AS_TEMPLATE)&&p&&!u&&t.jsx(t.Fragment,{children:v?t.jsxs(c.DropdownMenuItem,{className:"flex cursor-pointer items-center gap-2",onClick:j=>{j.stopPropagation(),o(e)},children:[t.jsx(N.SquareLibrary,{className:"size-3"}),le.UNMARK_AS_TEMPLATE]}):t.jsxs(c.DropdownMenuItem,{className:"flex cursor-pointer items-center gap-2",onClick:j=>{j.stopPropagation(),i(e)},children:[t.jsx(N.SquareLibrary,{className:"size-3"}),le.MARK_AS_TEMPLATE]})})]})]})},Yi=({page:e})=>{var a,r;const{isExpanded:s,toggleExpanded:n}=Ms(e==null?void 0:e.id);return t.jsx("button",{onClick:i=>{i.stopPropagation(),n()},disabled:!((a=e==null?void 0:e.children)!=null&&a.length),className:`flex h-[calc(100%-2px)] w-5 items-center justify-center rounded text-gray-400 transition-colors hover:bg-gray-200 hover:px-1 hover:text-gray-500 ${(r=e==null?void 0:e.children)!=null&&r.length?"hover:text-blue-400":"opacity-0"}`,children:t.jsx(N.ChevronRight,{size:12,className:`stroke-[4] transition-transform duration-200 ${s?"rotate-90":""}`})})},Xi=({page:e,pageType:s})=>t.jsx("div",{className:"flex h-full items-center justify-center gap-x-1",children:e.dynamic?t.jsx(N.StarsIcon,{size:12,className:"text-yellow-400"}):s!=null&&s.icon?t.jsx("div",{className:"flex h-4 max-h-4 w-4 max-w-4 items-center justify-center stroke-[1] text-slate-500",dangerouslySetInnerHTML:{__html:s.icon}}):s!=null&&s.hasSlug?t.jsx(N.File,{size:12,className:"stroke-[1] text-slate-500"}):t.jsx(N.Globe,{size:12,className:"stroke-[1] text-slate-500"})}),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:o})=>{const[l]=ga(),u=We(),d=n===e.id,h=!!e.isTemplate,m=f.useMemo(()=>g.find(s,{key:e.pageType}),[s,e.pageType]),v=l==null?void 0:l[e.id],{data:p}=ls(v),y=p?p==null?void 0:p.name:null;let j=g.get(r,e==null?void 0:e.id);j=g.get(j,"lang")===i?j:null;const x=i===u||!!j,b=(j==null?void 0:j.name)||(e==null?void 0:e.name)||"No name";let E=(j==null?void 0:j.slug)||(e==null?void 0:e.slug)||"";const P=E+(e!=null&&e.dynamic?`/${m==null?void 0:m.dynamicSlug}`:"")+(e!=null&&e.dynamicSlugCustom?`${e.dynamicSlugCustom}`:"");if(E.startsWith("/")&&!o){const L=E.split("/").pop();E=E.endsWith(L)&&e.dynamic?"":`/${L}`}const U=f.useMemo(()=>{const L="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]",F=`${d?"border-primary/30 bg-primary/5":"border-transparent hover:border-gray-200 hover:bg-gray-100"}`;return x?`${L} ${F} ${y?"opacity-60":""}`:`${L} bg-gray-100 opacity-50 group-hover:border-gray-200 border-transparent group-hover:bg-blue-100`},[x,d,y]);return t.jsxs("div",{className:"group relative",children:[t.jsxs("div",{onClick:()=>!e.isPartialGroup&&x&&a("select",e==null?void 0:e.id),className:U,children:[t.jsx(Yi,{page:e}),!e.isPartialGroup&&t.jsx(Zi,{isOnline:j?j.online:e.online}),t.jsx(Xi,{page:e,pageType:m}),t.jsx(Xe,{content:b,side:"top",showTooltip:b.length>35,children:t.jsx("span",{className:"max-w-[40%] truncate font-medium text-black",children:b})}),(E||e.dynamic)&&t.jsx(Xe,{content:P,side:"top",showTooltip:!0,children:t.jsxs("span",{className:"max-w-[40%] truncate font-mono text-xs text-muted-foreground",children:[E,e.dynamic&&(m==null?void 0:m.dynamicSlug)&&t.jsxs("span",{className:"text-xs text-gray-500",children:["/",m==null?void 0:m.dynamicSlug,e.dynamicSlugCustom]})]})}),h&&t.jsx(Xe,{content:"Template",side:"top",children:t.jsx("span",{className:"text-blue-500",children:t.jsx(N.NotepadText,{size:16})})}),!e.isPartialGroup&&x&&!y?t.jsx("div",{className:"duration absolute right-0.5 top-[3px]",children:t.jsx(Ca,{isLanguagePage:!!j,page:j||e,setDuplicatePage:L=>a("duplicate",L),setAddEditPage:L=>a("edit",j||L),setUnpublishPage:L=>a("unpublish",L),setDeletePage:L=>a("delete",j||L),setMarkAsTemplate:L=>a("markAsTemplate",L),setUnmarkAsTemplate:L=>a("unmarkAsTemplate",L),children:t.jsx("div",{className:"m-0 cursor-pointer rounded border border-transparent p-0.5 duration-100 hover:border-gray-400 hover:bg-white",children:t.jsx(N.MoreHorizontal,{className:"h-4 w-4",onClick:L=>L.stopPropagation()})})})}):y?t.jsx("span",{className:"duration absolute right-1.5 top-1/2 -translate-y-1/2 text-xs text-gray-500",children:t.jsx(N.Lock,{className:"h-3.5 w-3.5 fill-red-200 text-red-500"})}):null]}),t.jsx(t.Fragment,{children:y&&t.jsxs("button",{className:"absolute right-0 top-0 flex h-full items-center gap-x-1 rounded bg-red-50 px-2 py-0.5 text-xs font-light text-red-500 opacity-0 group-hover:opacity-100",children:[t.jsx(N.Edit,{size:12,className:"stroke-[3]"})," ",t.jsx("span",{className:"font-medium",children:y})," is editing this page"]})}),t.jsx(t.Fragment,{children:!x&&!e.isPartialGroup&&!y&&t.jsxs("button",{onClick:L=>{L.stopPropagation(),a("addLanguagePage",{language:i,page:e})},className:"absolute left-1/2 top-1 flex -translate-x-1/2 items-center gap-x-1 rounded bg-blue-500 px-2 py-0.5 text-xs text-white opacity-0 duration-200 hover:bg-blue-700 group-hover:opacity-100",children:[t.jsx(N.Plus,{size:12,className:"stroke-[3]"})," ",t.jsxs("span",{className:"text-[10px]",children:["Add ",g.get(we,i)," Page"]})]})})]})},Ta=({pages:e,tier:s,pageTypes:n,currentPage:a,onClickAction:r,languagePages:i,selectedLanguage:o,showUntranslatedPages:l})=>{const{expandedPages:u}=Ms();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:o,showUntranslatedPages:l}),d.children&&d.children.length>0&&(u==null?void 0:u.includes(d.id))&&t.jsx(Ta,{pages:d.children,tier:s+1,pageTypes:n,currentPage:a,onClickAction:r,languagePages:i,selectedLanguage:o,showUntranslatedPages:l})]},d.id))})};function tl({value:e,onChange:s,placeholder:n="Enter custom slug part",dynamicPattern:a,onValidationChange:r}){const[i,o]=f.useState(null),l=f.useRef(null),[u,d]=f.useState(a+e);f.useEffect(()=>{d(a+e)},[e,a]);const h=p=>{const y=p.target.value;if(!y.startsWith(a)){const U=y.replace(a,""),L=a+U;d(L),s(U);return}const x=y.substring(a.length).replace(/\//g,"").replace(/\s+/g,"-").replace(/[^a-zA-Z0-9-_.]/g,"-").replace(/-+/g,"-").replace(/^-+/,"").toLowerCase(),b=(x.match(/\./g)||[]).length,E=b<=1;b>1?o("Invalid slug. Only one dot (.) is allowed in the slug"):o(null),r&&r(E);const P=a+x;d(P),s(x)},m=()=>{if(l.current){const p=l.current;setTimeout(()=>{const y=a.length;p.setSelectionRange(y,y)},0)}},v=p=>{const y=p.currentTarget;(y.selectionStart||0)<=a.length&&setTimeout(()=>{const x=a.length;y.setSelectionRange(x,x)},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:l,value:u,onChange:h,onFocus:m,onClick:v,placeholder:n,className:i?"border-red-500":""}),i&&t.jsx("div",{className:"text-red-500 text-xs mt-1",children:i})]})})}const ws=({children:e,onWheel:s,...n})=>{const a=r=>{try{r.preventDefault();const i=r.currentTarget;i.scrollTop+=r.deltaY}catch{r.preventDefault()}s&&s(r)};return t.jsx(c.CommandList,{...n,onWheel:a,children:e})},Hs=(...e)=>e.filter(Boolean).join(" ");function sl({pages:e,selectedParentId:s,onChange:n,className:a,id:r="parentPage",currentPage:i}){const[o,l]=f.useState(!1),[u,d]=f.useState(""),h=V.useChaiFeatureFlag("enable-add-page-dropdown");h||(a="w-full rounded-md border border-gray-300 px-3 py-2");const m=f.useMemo(()=>!e||e.length===0?[]:e.filter(E=>!g.isEmpty(E.slug)).filter(E=>E.slug!=="/").sort((E,P)=>E.slug.localeCompare(P.slug)),[e]),v=f.useMemo(()=>{if(!u.trim())return m;const b=u.toLowerCase();return m.filter(E=>E.name.toLowerCase().includes(b)||E.slug.toLowerCase().includes(b))},[m,u]),p=b=>Math.max(0,(b.match(/\//g)||[]).length-1),y=b=>" ".repeat(b),j=b=>{if(b==="/")return"/";const E=b.split("/").filter(Boolean);if(E.length<=1){const P=E[0]||"";return`/${lt(P)}`}return`/${lt(E[E.length-1])}`},x=()=>{if(!s||s==="none")return"None";const b=m.find(E=>E.id===s);return b?`${b.name} (${j(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:o,onOpenChange:l,children:[t.jsx(c.PopoverTrigger,{asChild:!0,children:t.jsxs(c.Button,{id:r,variant:"outline",role:"combobox",className:Hs("w-full justify-between",a),"data-testid":"parent-page-selector",children:[x(),t.jsx(N.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),t.jsx(c.PopoverContent,{className:"w-[var(--radix-popover-trigger-width)] p-0",align:"start",children:t.jsxs(c.Command,{shouldFilter:!1,children:[t.jsx("div",{className:"relative border-none py-2",children:t.jsx("div",{className:"sticky top-0 z-10 bg-white px-3 py-2",children:t.jsxs("div",{className:"relative",children:[t.jsx(N.Search,{strokeWidth:2,className:"absolute left-2 top-2 h-4 w-4 text-gray-400"}),t.jsx(c.Input,{placeholder:"Search pages...",className:"h-8 pl-8 text-xs",value:u,onChange:b=>d(b.target.value)})]})})}),t.jsxs(ws,{className:"max-h-[300px] overflow-y-auto",children:[t.jsx(c.CommandEmpty,{children:"No pages found."}),t.jsxs(c.CommandGroup,{children:[t.jsxs(c.CommandItem,{value:"none",onSelect:()=>{n(""),l(!1),d("")},className:"flex cursor-pointer items-center justify-between",children:[t.jsx("span",{children:"None"}),t.jsx(N.Check,{className:Hs("mr-2 h-4 w-4",s?"opacity-0":"opacity-100")})]}),v.map(b=>{const E=y(p(b.slug)),P=j(b.slug),U=t.jsxs("span",{className:"flex items-center text-sm",children:[E,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),l(!1),d("")},className:"flex cursor-pointer items-center justify-between whitespace-pre-wrap",children:[t.jsx("span",{children:U}),t.jsx(N.Check,{className:Hs("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 E=p(b.slug),P=E>0?y(E):"",U=j(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," (",U,")"]},b.id)})]})]})}const nl=(...e)=>e.filter(Boolean).join(" "),al=({templates:e,selectedTemplateId:s,onSelectTemplate:n,isLoading:a=!1})=>{const[r,i]=f.useState(""),[o,l]=f.useState(!1),[u,d]=f.useState(""),h=V.useChaiFeatureFlag("enable-add-page-dropdown");if(f.useEffect(()=>{if(s){const j=e.find(x=>x.id===s);i((j==null?void 0:j.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(j=>{const x=j.libraryName;m[x]||(m[x]=[]),m[x].push(j)});const v=Object.entries(m).reduce((j,[x,b])=>{const E=b.filter(P=>P.name.toLowerCase().includes(u.toLowerCase())||x.toLowerCase().includes(u.toLowerCase()));return E.length>0&&(j[x]=E),j},{}),p=e.find(j=>j.id===s),y=p?g.startCase(p.name):"No Template";return t.jsxs("div",{className:"space-y-4",children:[h?t.jsxs(c.Popover,{open:o,onOpenChange:l,children:[t.jsx(c.PopoverTrigger,{asChild:!0,children:t.jsxs(c.Button,{variant:"outline",role:"combobox",className:"w-full justify-between",children:[y,t.jsx(N.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),t.jsx(c.PopoverContent,{className:"w-[var(--radix-popover-trigger-width)] p-0",align:"start",children:t.jsxs(c.Command,{shouldFilter:!1,children:[t.jsx("div",{className:"sticky top-0 z-10 bg-white px-3 py-2",children:t.jsxs("div",{className:"relative",children:[t.jsx(N.Search,{strokeWidth:2,className:"absolute left-2 top-2 h-4 w-4 text-gray-400"}),t.jsx(c.Input,{placeholder:"Search templates...",className:"h-8 pl-8 text-xs",value:u,onChange:j=>d(j.target.value)})]})}),t.jsxs(ws,{className:"max-h-[300px] overflow-y-auto",children:[t.jsx(c.CommandEmpty,{children:"No templates found."}),Object.entries(v).map(([j,x])=>t.jsx(c.CommandGroup,{heading:j,children:x.map(b=>t.jsxs(c.CommandItem,{value:b.id,onSelect:()=>{n(b.id),l(!1),d("")},className:"flex cursor-pointer items-center justify-between",children:[g.startCase(b.name),t.jsx(N.Check,{className:nl("mr-2 h-4 w-4",s===b.id?"opacity-100":"opacity-0")})]},b.id))},j))]})]})})]}):t.jsxs("select",{className:"w-full rounded-md border border-gray-300 px-3 py-2",value:s,onChange:j=>n(j.target.value),children:[t.jsx("option",{value:"",children:"No Template"}),Object.entries(m).map(([j,x])=>t.jsx("optgroup",{label:j,children:x.map(b=>t.jsx("option",{value:b.id,children:g.startCase(b.name)},b.id))},j))]}),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"})]})]})},rl=()=>{const e=oe(),s=se();return G.useQuery({queryKey:[_.GET_LIBRARIES],queryFn:async()=>await s(e,{action:_.GET_LIBRARIES})||[]})},il=e=>{const s=oe(),n=se();return G.useQuery({queryKey:[_.GET_TEMPLATES_BY_TYPE,e],enabled:!!e,queryFn:async()=>{const a=await n(s,{action:_.GET_TEMPLATES_BY_TYPE,data:{pageType:e}});return(e?g.filter(a,{pageType:e}):a)||[]}})},ll=e=>{const{data:s=[],isLoading:n}=il(e),{data:a=[],isLoading:r}=rl(),i=f.useMemo(()=>n||r?[]:s.map(l=>{const u=g.find(a,{id:l.library});return{...l,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]),o=f.useMemo(()=>g.groupBy(i,"libraryName"),[i]);return{data:i,groupedData:o,isLoading:n||r}},jn=()=>{const[,e]=_e();return f.useCallback((s,n)=>{const r=new URLSearchParams(window.location.search).get("lang"),i=new URLSearchParams({page:s});r&&i.set("lang",r),window.history.pushState({},"",`?${i.toString()}`),e(i),window.dispatchEvent(new PopStateEvent("popstate")),n==null||n()},[e])},Ut=(e,s)=>{const n={seo:{keyword:"",title:"",description:"",noIndex:!1,noFollow:!1,canonicalUrl:"",ogTitle:"",ogDescription:"",jsonLD:"",metaOther:""},jsonLD:{},metaOther:{}};e!=null&&e.defaultSeo&&(g.has(e.defaultSeo,s)&&g.isObject(e.defaultSeo[s])?n.seo={...n.seo,...e.defaultSeo[s]}:n.seo={...n.seo,...e.defaultSeo});let a={};e!=null&&e.defaultJSONLD&&(g.has(e.defaultJSONLD,s)&&g.isObject(e.defaultJSONLD[s])?(a=e.defaultJSONLD[s],g.set(n,"seo.jsonLD",JSON.stringify(a))):(a=e.defaultJSONLD,g.set(n,"seo.jsonLD",JSON.stringify(a))));let r={};return e!=null&&e.defaultMetaTags&&(g.has(e.defaultMetaTags,s)&&g.isObject(e.defaultMetaTags[s])?(r=e.defaultMetaTags[s],g.set(n,"seo.metaOther",JSON.stringify(r))):(r=e.defaultMetaTags,g.set(n,"seo.metaOther",JSON.stringify(r)))),{seo:n.seo,jsonLD:n.jsonLD,metaOther:r}},at=(...e)=>e.filter(Boolean).join(" ");function ol({addEditPage:e,close:s,closePanel:n}){var ms,kn;const{data:a}=Ae(),r=f.useMemo(()=>a??[],[a]),i=jn(),o=!!(e!=null&&e.id),{data:l}=_t(),{mutate:u,isPending:d}=va(),{mutate:h,isPending:m}=gn(),[v,p]=f.useState(null),[y,j]=f.useState(!0),[x,b]=f.useState((e==null?void 0:e.pageType)??"page"),{hasPermission:E}=V.usePermissions(),P=E(Se.CHANGE_PAGE_TYPE),[U,L]=f.useState(!1),[F,re]=f.useState(""),{selectedLang:$,fallbackLang:k}=V.useLanguages(),D=$||k,[K,H]=f.useState(""),[X,Y]=f.useState(!1),W=f.useMemo(()=>{const T=r.find(ue=>ue.key===x);return(T==null?void 0:T.hasSlug)===!1},[x,r]),[ie,je]=f.useState((e==null?void 0:e.parent)??""),[fe,Pe]=f.useState((e==null?void 0:e.name)??""),[w,S]=f.useState((e==null?void 0:e.dynamic)??!1),[I,B]=f.useState(w?"":((e==null?void 0:e.slug)??"").split("/").pop()||""),[R,O]=f.useState((e==null?void 0:e.dynamicSlugCustom)??""),[M,C]=f.useState(!0),[q,ne]=f.useState(!1),[z,J]=f.useState(""),{data:ce,isLoading:me}=ll(x),A=d||m,Z=V.useChaiFeatureFlag("enable-add-page-dropdown"),Ee=f.useMemo(()=>!o||!(e!=null&&e.id)||!l?null:l.find(T=>T.id===e.id),[o,e==null?void 0:e.id,l]),De=(Ee==null?void 0:Ee.online)||!1,Ge=f.useMemo(()=>!o||!(e!=null&&e.id)||!l?!1:l.some(T=>T.parent===e.id),[o,e==null?void 0:e.id,l]),ee=r.find(T=>T.key===x),Ce=T=>{if(o&&x!==T){re(T),L(!0),H(""),Y(!1);return}b(T),H(""),Y(!1)},cs=()=>{b(F),L(!1),S(!1)},qs=T=>{S(T),T?B(""):O("")},zs=T=>{if(je(T),T&&T!=="none"){const ue=l==null?void 0:l.find(Le=>Le.id===T),Re=(ue==null?void 0:ue.slug)||"";if(I.startsWith(Re)){const Le=I.slice(Re.length).replace(/^\/+/,"");B(Le)}else B(I.replace(/^\/+/,""))}else B(I?`${I}`:"")},us=T=>{J(T)},Vs=()=>fe.trim()?w&&!g.isEmpty(I)?(p("Slug must be empty when using dynamic slug"),!1):w&&!M?(p("Dynamic slug is invalid"),!1):!0:(Q.toast.error("Name is required"),!1),ds=()=>{const T={pageType:ee==null?void 0:ee.key,name:fe,slug:"",hasSlug:!1};o?h({id:e==null?void 0:e.id,name:fe},{onSuccess:()=>{Q.toast.success((ee==null?void 0:ee.name)+" updated successfully"),s()}}):u(T,{onSuccess:ue=>{s(),i(ue.page.id,n)}})},$s=(T,ue)=>{if(!T.trim()&&!w)return p("Child page slug is required"),!1;const Re=lt(ue),Le=Dn(Re,T);return Object.keys(we).some(fs=>Le===`/${fs}`||(Le==null?void 0:Le.startsWith(`/${fs}/`)))?(p("Slugs cannot start with a language code for primary page"),!1):!0},Ks=(T,ue)=>{const Re=lt(ue),Le=Dn(Re,T),Be={pageType:x,name:fe,slug:Le.replace(/\/$/,""),parent:ie,dynamic:w,hasSlug:!0,template:z||void 0,tracking:{},seo:{},jsonLD:{}};if(w&&(Be.dynamicSlugCustom=R),o){const Ue=g.pick(Be,["pageType","parent","name","slug","dynamic","dynamicSlugCustom"]);h({id:e==null?void 0:e.id,...Ue},{onSuccess:()=>{Q.toast.success("Page updated successfully"),s()}})}else{const Ue=g.find(r,{key:x});Ue!=null&&Ue.trackingDefault&&(Be.tracking=Ue.trackingDefault);const{seo:fs,jsonLD:Pr}=Ut(Ue,D);g.set(Be,"seo",fs),g.set(Be,"jsonLD",Pr),u(Be,{onSuccess:Ir=>{s(),i(Ir.page.id,n)}})}},hs=()=>{const T={pageType:x,name:fe,slug:I===""?"/":`/${I.replace(/\/$/,"")}`,template:z||void 0,parent:null,tracking:{}};if(o)h({id:e==null?void 0:e.id,...T},{onSuccess:()=>{Q.toast.success("Page updated successfully"),s()}});else{const ue=g.find(r,{key:x});ue!=null&&ue.trackingDefault&&(T.tracking=ue.trackingDefault);const{seo:Re,jsonLD:Le}=Ut(ue,D);g.set(T,"seo",Re),g.set(T,"jsonLD",Le),u(T,{onSuccess:Be=>{var Ue;(Ue=Be==null?void 0:Be.page)!=null&&Ue.id&&i(Be.page.id,n),s()}})}},Dt=T=>{if(T.preventDefault(),p(null),!!Vs()){if(!(ee!=null&&ee.hasSlug)){ds();return}if(ie&&ie!=="none"){const ue=l==null?void 0:l.find(Le=>Le.id===ie),Re=(ue==null?void 0:ue.slug)||"";if(!$s(I,Re))return;Ks(I,Re)}else hs()}},{pagesType:nt,partialsType:ct}=f.useMemo(()=>{const T=ue=>K?ue.name.toLowerCase().includes(K.toLowerCase())||ue.key.toLowerCase().includes(K.toLowerCase()):!0;return{pagesType:r.filter(ue=>ue.hasSlug!==!1&&T(ue)),partialsType:r.filter(ue=>ue.hasSlug===!1&&T(ue))}},[r,K]);return ee!=null&&ee.hasSlug?t.jsxs("form",{onSubmit:Dt,className:"mx-auto w-full max-w-md space-y-4",children:[t.jsxs("div",{className:"space-y-0.5",children:[t.jsx(c.Label,{htmlFor:"pageType",className:"text-sm",children:"Type"}),Z?t.jsxs(c.Popover,{open:X,onOpenChange:Y,children:[t.jsx(c.PopoverTrigger,{asChild:!0,children:t.jsxs(c.Button,{variant:"outline",role:"combobox",disabled:o&&!P,className:at("w-full justify-between",o&&!P?"cursor-not-allowed text-gray-500":""),children:[(ee==null?void 0:ee.name)||"Select page type",t.jsx(N.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),t.jsx(c.PopoverContent,{className:"w-[var(--radix-popover-trigger-width)] p-0",align:"start",children:t.jsxs(c.Command,{shouldFilter:!1,children:[t.jsx("div",{className:"sticky top-0 z-10 bg-white px-3 py-2",children:t.jsxs("div",{className:"relative",children:[t.jsx(N.Search,{strokeWidth:2,className:"absolute left-2 top-2 h-4 w-4 text-gray-400"}),t.jsx(c.Input,{placeholder:"Search page types...",className:"h-8 pl-8 text-xs",value:K,onChange:T=>H(T.target.value)})]})}),t.jsxs(ws,{className:"overflow-y-auto",children:[t.jsx(c.CommandEmpty,{children:"No page type found."}),o?W?t.jsx(c.CommandGroup,{heading:"Partials",children:ct.map(T=>t.jsxs(c.CommandItem,{value:T.key,onSelect:()=>Ce(T.key),className:"flex cursor-pointer items-center justify-between",children:[T.name,t.jsx(N.Check,{className:at("mr-2 h-4 w-4",x===T.key?"opacity-100":"opacity-0")})]},T.key))}):t.jsx(c.CommandGroup,{heading:"Pages",children:nt.map(T=>t.jsxs(c.CommandItem,{value:T.key,onSelect:()=>Ce(T.key),className:"flex cursor-pointer items-center justify-between",children:[T.name,t.jsx(N.Check,{className:at("mr-2 h-4 w-4",x===T.key?"opacity-100":"opacity-0")})]},T.key))}):t.jsxs(t.Fragment,{children:[nt.length>0&&t.jsx(c.CommandGroup,{heading:"Pages",children:nt.map(T=>t.jsxs(c.CommandItem,{value:T.key,onSelect:()=>Ce(T.key),className:"flex cursor-pointer items-center justify-between",children:[T.name,t.jsx(N.Check,{className:at("mr-2 h-4 w-4",x===T.key?"opacity-100":"opacity-0")})]},T.key))}),ct.length>0&&t.jsx(c.CommandGroup,{heading:"Partials",children:ct.map(T=>t.jsxs(c.CommandItem,{value:T.key,onSelect:()=>Ce(T.key),className:"flex cursor-pointer items-center justify-between",children:[T.name,t.jsx(N.Check,{className:at("mr-2 h-4 w-4",x===T.key?"opacity-100":"opacity-0")})]},T.key))})]})]})]})})]}):t.jsx("select",{id:"pageType",value:x,disabled:o&&!P,onChange:T=>Ce(T.target.value),className:`w-full rounded-md border border-gray-300 px-3 py-2 ${o&&!P?"cursor-not-allowed text-gray-500":""}`,children:o?W?t.jsx("optgroup",{label:"Partials",children:r.filter(T=>T.hasSlug===!1).map(T=>t.jsx("option",{value:T.key,children:T.name},T.key))}):t.jsx("optgroup",{label:"Pages",children:r.filter(T=>T.hasSlug!==!1).map(T=>t.jsx("option",{value:T.key,children:T.name},T.key))}):t.jsxs(t.Fragment,{children:[t.jsx("optgroup",{label:"Pages",children:r.filter(T=>T.hasSlug!==!1).map(T=>t.jsx("option",{value:T.key,children:T.name},T.key))}),t.jsx("optgroup",{label:"Partials",children:r.filter(T=>T.hasSlug===!1).map(T=>t.jsx("option",{value:T.key,children:T.name},T.key))})]})}),U&&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:cs,children:"Confirm"})]})]})]}),!o&&(ee==null?void 0:ee.hasSlug)&&ce.length>0&&t.jsxs("div",{className:"space-y-1",children:[t.jsx(c.Label,{className:"mb-1 block text-sm",children:"Template"}),t.jsx(al,{templates:ce,selectedTemplateId:z,onSelectTemplate:us,isLoading:me})]}),t.jsx(sl,{pages:l,selectedParentId:ie,onChange:zs,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:fe,onChange:T=>Pe(T.target.value),required:!0,"aria-required":"true",placeholder:"Enter page name"})]}),(ee==null?void 0:ee.dynamicSegments)&&ie&&ie!=="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:w,onChange:T=>qs(T.target.checked),className:"rounded border-gray-300"}),t.jsx(c.Label,{htmlFor:"useDynamicSlug",className:"text-sm",children:"Use Dynamic Slug"})]}),w&&t.jsx("div",{className:"space-y-2",children:t.jsx("div",{className:"space-y-0.5",children:t.jsx(tl,{value:R,onChange:O,dynamicPattern:(ee==null?void 0:ee.dynamicSlug)||"{{id}}",placeholder:"Enter custom slug part (optional)",onValidationChange:C})})})]}),(!(ee!=null&&ee.dynamicSegments)||!w)&&t.jsxs("div",{className:"space-y-0.5",children:[t.jsx(c.Label,{htmlFor:"slug",className:"text-sm",children:"Slug"}),t.jsx(yn,{value:I,onChange:T=>{var ue;B(T),o&&T!==(((ue=e==null?void 0:e.slug)==null?void 0:ue.split("/").pop())||"")?ne(!!(De||Ge)):ne(!1)},placeholder:ie&&ie!=="none"?"Enter page slug":x==="page"?"Leave empty for home page":"Required - e.g. your-slug",parentSlug:ie&&ie!=="none"?(kn=l==null?void 0:l.find(T=>T.id===ie))==null?void 0:kn.slug:void 0,onValidationChange:j}),v&&t.jsx("p",{className:"text-xs text-red-500",children:v}),q&&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:A||!y&&(!(ee!=null&&ee.dynamicSegments)||!w)||w&&!M,type:"submit",className:"w-full",children:o?A?"Updating...":"Update page":A?"Creating...":"Create Page"})]}):t.jsxs("form",{onSubmit:Dt,className:"mx-auto w-full max-w-md space-y-4",children:[t.jsxs("div",{className:"space-y-0.5",children:[t.jsx(c.Label,{htmlFor:"pageType",className:"text-sm",children:"Type"}),Z?t.jsxs(c.Popover,{open:X,onOpenChange:Y,children:[t.jsx(c.PopoverTrigger,{asChild:!0,children:t.jsxs(c.Button,{variant:"outline",role:"combobox",disabled:o&&!P,className:at("w-full justify-between",o&&!P?"cursor-not-allowed text-gray-500":""),children:[(ee==null?void 0:ee.name)||"Select page type",t.jsx(N.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),t.jsx(c.PopoverContent,{className:"w-[var(--radix-popover-trigger-width)] p-0",align:"start",children:t.jsxs(c.Command,{shouldFilter:!1,children:[t.jsx("div",{className:"sticky top-0 z-10 bg-white px-3 py-2",children:t.jsxs("div",{className:"relative",children:[t.jsx(N.Search,{strokeWidth:2,className:"absolute left-2 top-2 h-4 w-4 text-gray-400"}),t.jsx(c.Input,{placeholder:"Search page types...",className:"h-8 pl-8 text-xs",value:K,onChange:T=>H(T.target.value)})]})}),t.jsxs(ws,{className:"max-h-[200px] overflow-y-auto",children:[t.jsx(c.CommandEmpty,{children:"No page type found."}),t.jsx(c.CommandGroup,{heading:"Partials",children:ct.map(T=>t.jsxs(c.CommandItem,{value:T.key,onSelect:()=>{Ce(T.key),Y(!1)},className:"flex cursor-pointer items-center justify-between",children:[T.name,t.jsx(N.Check,{className:at("mr-2 h-4 w-4",x===T.key?"opacity-100":"opacity-0")})]},T.key))})]})]})})]}):t.jsx("select",{id:"pageType",value:x,disabled:o&&!P,onChange:T=>Ce(T.target.value),className:`w-full rounded-md border border-gray-300 px-3 py-2 ${o&&!P?"cursor-not-allowed text-gray-500":""}`,children:t.jsx("optgroup",{label:"Partials",children:r.filter(T=>T.hasSlug===!1).map(T=>t.jsx("option",{value:T.key,children:T.name},T.key))})}),U&&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:cs,children:"Confirm"})]})]}),t.jsx("p",{className:"text-xs text-gray-500",children:(ms=r.find(T=>T.key===x))==null?void 0:ms.helpText})]}),t.jsxs("div",{className:"space-y-0.5",children:[t.jsx(c.Label,{htmlFor:"name",className:"text-sm",children:"Name"}),t.jsx(c.Input,{id:"name",value:fe,onChange:T=>Pe(T.target.value),required:!0,"aria-required":"true"})]}),t.jsx(c.Button,{disabled:A,type:"submit",className:"w-full",children:o?A?"Updating...":"Update "+(ee==null?void 0:ee.name):A?"Creating...":"Create "+(ee==null?void 0:ee.name)})]})}const Aa=({addEditPage:e,setAddEditPage:s,closePanel:n})=>{const a=!!(e!=null&&e.id),r=!!e;return t.jsx(c.Dialog,{open:r,onOpenChange:()=>s(void 0),children:r&&t.jsxs(c.DialogContent,{className:"sm:max-w-[425px]",children:[t.jsxs(c.DialogHeader,{children:[t.jsxs(c.DialogTitle,{children:[a?"Edit":"Add New"," "]}),t.jsx(c.DialogDescription,{children:a?"Update your page name":"Enter details to create a new page"})]}),t.jsx(ol,{closePanel:n,addEditPage:e,close:()=>s(void 0)})]})})};function bn({page:e,onClose:s}){const[,n]=_e(),{mutate:a,isPending:r}=Ei(),{data:i}=Ae(),{setSelectedLang:o,fallbackLang:l}=V.useLanguages(),[,u]=V.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")),o(l),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:g.get(we,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 cl=()=>{const e=oe(),s=G.useQueryClient(),n=se();return G.useMutation({mutationFn:async({pageId:a,name:r,slug:i})=>{const o={pageId:a,name:r};return i&&(o.slug=i),await n(e,{action:"DUPLICATE_PAGE",data:o})},onSuccess:()=>{s.invalidateQueries({queryKey:[_.GET_WEBSITE_PAGES]}),Q.toast.success("Page duplicated successfully")},onError:a=>{Q.toast.error("Failed to duplicate page",{description:a.message||"An error occurred while duplicating the page"})}})},ka=({page:e,onClose:s,closePanel:n=()=>{}})=>{const{mutate:a,isPending:r}=cl(),[i,o]=f.useState(null),[l,u]=f.useState(`${e.name} (Copy)`),d=jn(),h=g.isEmpty(e.slug),[m,v]=f.useState(h?"":`${e.slug.split("/").pop()}-copy`),p=h?"":g.initial(e.slug.split("/")).join("/"),[y,j]=f.useState(!1),x=b=>{if(b.preventDefault(),!l.trim()){o("Name is required");return}if(!h&&!m.trim()){o("Slug is required");return}o(null),j(!0);const E={pageId:e.id,name:l};h||(E.slug=`${p}/${m}`),a(E,{onSuccess:P=>{j(!1),s(),d(P.id,n)},onError:P=>{j(!1),P.code==="SLUG_EXISTS"?o("A page with this slug already exists. Please choose a different slug."):P.code==="INVALID_SLUG"?o("The slug format is invalid. Please use only lowercase letters, numbers, and hyphens."):P.code==="PERMISSION_DENIED"?o("You don't have permission to duplicate this page."):o(P.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]}),!h&&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:x,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:b=>u(b.target.value),required:!0})]}),!h&&t.jsxs("div",{className:"space-y-2",children:[t.jsx(c.Label,{htmlFor:"slug",className:"text-sm",children:"Slug"}),t.jsx(yn,{value:m,onChange:b=>v(b),parentSlug:p,onValidationChange:b=>{o(b?null:"Invalid slug")}})]}),i&&t.jsxs(c.Alert,{variant:"destructive",className:"py-2",children:[t.jsx(N.AlertCircle,{className:"h-4 w-4"}),t.jsx("span",{className:"text-sm",children:i})]}),t.jsxs("div",{className:"flex justify-end gap-2",children:[t.jsx(c.Button,{type:"button",variant:"outline",onClick:s,disabled:r,children:"Cancel"}),t.jsx(c.Button,{type:"submit",disabled:!l.trim()||!h&&!m.trim()||r||y,children:r||y?"Duplicating...":"Duplicate"})]})]})]})})},ul=1*1024*1024,Pa=({page:e,onClose:s})=>{const[n,a]=f.useState(!1),[r,i]=f.useState(""),[o,l]=f.useState(""),[u,d]=f.useState(!1),h=f.useRef(null),m=Ci(),{data:v}=Ae(),p=v==null?void 0:v.find(P=>P.key===e.pageType),y=(p==null?void 0:p.name)||g.startCase(e.pageType),j=f.useCallback(P=>{var L;const U=(L=P.target.files)==null?void 0:L[0];if(U){if(U.size>ul){Q.toast.error("File too large",{description:`Maximum file size is 1MB. Selected file is ${(U.size/1024).toFixed(2)}KB.`}),h.current&&(h.current.value="");return}try{d(!0);const F=new FileReader;F.onloadend=()=>{l(F.result),d(!1)},F.readAsDataURL(U)}catch(F){console.error("Error reading file:",F),d(!1),Q.toast.error("Failed to process image",{description:F instanceof Error?F.message:"Unknown error"})}}},[]),x=()=>{l(""),h.current&&(h.current.value="")},b=()=>{var P;(P=h.current)==null||P.click()},E=()=>{a(!0),m.mutate({page:e,name:e.name,description:r.trim()||void 0,pageType:e.pageType,...o?{previewImage:o}:{}},{onSuccess:()=>{a(!1),s()},onError:()=>{a(!1)}})};return t.jsx(c.Dialog,{open:!0,onOpenChange:s,children:t.jsxs(c.DialogContent,{children:[t.jsxs(c.DialogHeader,{children:[t.jsx(c.DialogTitle,{children:"Mark as template"}),t.jsxs(c.DialogDescription,{className:"py-4 text-slate-500 space-y-1 text-xs",children:["Are you sure you want to mark this page as a template?",t.jsx("br",{}),"Templates can be used to create new pages with the same content."]})]}),t.jsxs("div",{className:"space-y-4 mb-4 text-xs",children:[t.jsxs("div",{className:"p-4 border rounded bg-slate-50 space-y-3",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(N.Tag,{className:"w-4 h-4 text-slate-500"}),t.jsx("span",{className:"font-medium text-slate-500",children:"Page Name:"}),t.jsx("span",{className:"font-semibold",children:g.startCase(e.name)})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(N.File,{className:"w-4 h-4 text-slate-500"}),t.jsx("span",{className:"font-medium text-slate-500",children:"Type:"}),t.jsx("span",{className:"font-semibold",children:y})]})]}),t.jsxs("div",{children:[t.jsx(c.Label,{htmlFor:"description",className:"text-xs font-medium",children:"Description (Optional)"}),t.jsx(c.Textarea,{id:"description",placeholder:"Describe this template's purpose",className:"text-xs resize-none h-24 mt-1",value:r,onChange: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:j,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(N.ImageIcon,{className:"h-4 w-4"}),"Select image"]})}),o&&t.jsx(c.Button,{type:"button",variant:"outline",size:"icon",onClick:x,children:t.jsx(N.X,{className:"h-4 w-4"})})]}),o&&t.jsx("div",{className:"rounded-md overflow-hidden border aspect-video",children:t.jsx("img",{src:o,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:E,children:"Mark as template"})]})]})})},Ia=({page:e,onClose:s})=>{const[n,a]=f.useState(!1),r=Ti(),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:o=>{o.stopPropagation(),s()},children:"Cancel"}),t.jsx(c.Button,{variant:"default",disabled:n,onClick:i,children:"Unmark as template"})]})]})})},Gs=({page:e,onClose:s})=>{const{mutate:n,isPending:a}=Ni(),r=async()=>{n(e,{onSuccess:s})};return t.jsx(c.Dialog,{open:!!e,onOpenChange:s,children:t.jsxs(c.DialogContent,{children:[t.jsxs(c.DialogHeader,{children:[t.jsx(c.DialogTitle,{children:"Confirm action"}),t.jsxs(c.DialogDescription,{children:[le.UNPUBLISH_MSG," ",t.jsx("b",{children:(e==null?void 0:e.name)??(e==null?void 0:e.slug)}),"?"]})]}),t.jsxs(c.DialogFooter,{children:[t.jsx(c.Button,{variant:"outline",onClick:s,children:"Cancel"}),t.jsx(c.Button,{variant:"destructive",disabled:a,onClick:r,children:a?le.UPDATING:le.UNPUBLISH})]})]})})},_a=({close:e})=>{const{languages:s,setSelectedLang:n}=V.useLanguages(),{data:a}=Ae(),{data:r,isFetching:i}=_t(),[o,l]=_e(),{updateForSelectedPage:u,expandPagesOnSearch:d}=Ms(null),h=We(),m=o.get("page"),[v,p]=f.useState(""),[y,j]=f.useState(null),[x,b]=f.useState(null),[E,P]=f.useState(null),[U,L]=f.useState(null),[F,re]=f.useState(""),[$,k]=f.useState(null),[D,K]=f.useState(null),[H,X]=f.useState(h),[Y,W]=f.useState(!1),[,ie]=ye.useAtom(os),je=Y&&H!==h,{data:fe,isFetching:Pe}=Li(H),w=f.useCallback(O=>{var M;return(M=g.find(a,{key:O}))==null?void 0:M.hasSlug},[a]),S=f.useMemo(()=>r?je?g.filter(r,O=>!(fe!=null&&fe[O.id])):Ki(r,v,F,w):[],[r,w,v,F,fe,je]);f.useEffect(()=>{n(h)},[h,n]),f.useEffect(()=>{if(!g.isEmpty(F))return;const O=sessionStorage.getItem("pageTypeFilter")||"all";!g.isEmpty(a)&&O&&(g.find(a,{key:O})?re(O):re("all"))},[a,F]),f.useEffect(()=>{if(m&&!i&&!g.find(r,{id:m})){const M=g.find(r,{slug:"/"});if(M){const C=new URLSearchParams({page:M.id});Rt(C,l)}else Rt(new URLSearchParams({}),l,!0)}},[r,m,i,l]),f.useEffect(()=>{m&&!i&&!g.isEmpty(S)&&u(S,m)},[m,i,S,u]),f.useEffect(()=>{!g.isEmpty(v)&&!g.isEmpty(S)&&d(S)},[v,S,d]);const{setSelectedLang:I}=V.useLanguages(),B=f.useCallback(O=>{const M=new URLSearchParams({page:O});H!==h?(M.set("lang",H),I(H)):I(""),Rt(M,l),e()},[e,l,I,H,h]),R=(O,M)=>{var C;if(M)switch(O){case"add":b(M);break;case"select":B(M);break;case"edit":H!==h?ie({edit:!0,id:M==null?void 0:M.id,primaryPage:M==null?void 0:M.primaryPage}):b(M);break;case"delete":j(M);break;case"unpublish":P(M);break;case"markAsTemplate":L(M);break;case"unmarkAsTemplate":K(M);break;case"duplicate":k(M);break;case"addLanguagePage":ie({edit:!1,primaryPage:((C=M==null?void 0:M.page)==null?void 0:C.id)||"",preselectedLang:(M==null?void 0:M.language)||H});break}};return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex h-full flex-col justify-between",children:[t.jsx(Ji,{pages:S,search:v,setSearch:p,languages:[h,...s],selectedLanguage:H,setSelectedLanguage:X,selectedPageType:F,setSelectedPageType:re,onAddPage:O=>R("add",O),showUntranslatedPages:je,setShowUntranslatedPages:W}),t.jsx("div",{className:"flex-1 overflow-y-auto px-4 pb-6 pt-2",children:i||Pe?t.jsx("div",{className:"space-y-2",children:g.map([...Array(15).keys()],O=>t.jsx("div",{className:"h-7 w-full animate-pulse rounded border border-gray-300 bg-gray-200"},O))}):g.isEmpty(S)?t.jsxs("div",{className:"flex h-[70vh] flex-col items-center justify-center gap-y-1 text-sm font-medium text-slate-500",children:[t.jsx(N.File,{className:"h-6 w-6 stroke-[1]"}),"Empty List!",t.jsx("span",{className:"font-light",children:"Add new page to start"})]}):t.jsx(Ta,{tier:0,pages:S,pageTypes:a,currentPage:m||"",onClickAction:R,languagePages:fe,selectedLanguage:H,showUntranslatedPages:je})})]}),x&&t.jsx(Aa,{closePanel:e,editPage:B,addEditPage:x,setAddEditPage:b}),y&&t.jsx(bn,{page:y,onClose:()=>j(null)}),E&&t.jsx(Gs,{page:E,onClose:()=>P(null)}),U&&t.jsx(Pa,{page:U,onClose:()=>L(null)}),D&&t.jsx(Ia,{page:D,onClose:()=>K(null)}),$&&t.jsx(ka,{page:$,onClose:()=>k(null),closePanel:e})]})},dl=()=>{const e=Me("topLeftCorner",null);return e?t.jsx("div",{className:"max-h-9 w-full overflow-hidden pr-2",children:f.createElement(e,{})}):null},hl=()=>{const[e,s]=_e(),n=e.get("page"),{data:a,isFetching:r}=ke(),{data:i,isFetching:o}=_t(),[l,u]=f.useState(!1),[d,h]=f.useState(!0),{savePage:m}=V.useSavePage(),v=!!n&&!g.isEmpty(a),p=f.useMemo(()=>{if(!i||o)return!1;const b=i.find(E=>E.slug==="/");return b==null?void 0:b.id},[i,o]);f.useEffect(()=>{if(o||!p||i.some(P=>P.id===n))return;const E=new URLSearchParams({page:p});Rt(E,s),!o&&i&&h(!1)},[n,o,i,p,s]);const y=!d&&!n,j=!d&&!r&&g.isEmpty(a),x=l||y||j;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:()=>{m(),u(!0)},children:t.jsx(N.LogsIcon,{className:"h-4 w-4"})},"template-viewer")}),t.jsx(c.TooltipContent,{side:"right",children:t.jsx("p",{children:"Open pages manager"})})]})})}),t.jsx(c.Sheet,{open:x,onOpenChange:b=>!b&&v&&u(!1),children:t.jsxs(c.SheetContent,{side:"left","aria-describedby":"pages-manager-description",className:`z-50 !min-w-[50vh] !max-w-[800px] border-border p-0 ${v?"":"sheet-hide-close-btn"}`,children:[t.jsxs(c.SheetHeader,{className:"mb-3 px-4 pt-4",children:[t.jsxs(c.SheetTitle,{className:"flex items-center gap-2 text-sm font-semibold",children:[t.jsx("div",{className:"flex h-9 w-9 items-center justify-center rounded-lg bg-primary text-primary-foreground",children:t.jsx(N.Folder,{className:"h-4 w-4"})}),t.jsxs("div",{className:"flex flex-col",children:[t.jsx("span",{className:"text-sm font-semibold",children:"Pages"}),t.jsx("span",{id:"pages-manager-description",className:"text-xs font-normal text-muted-foreground",children:"Manage your site structure"})]})]}),t.jsx(c.SheetDescription,{className:"sr-only",children:"Manage your site structure"})]}),t.jsx("div",{className:`${x?"h-[calc(100vh-80px)] overflow-y-auto":"h-[calc(100vh-70px)] overflow-y-auto"}`,children:t.jsx(_a,{close:()=>u(!1)})})]})})]})},Sn=({showAdd:e=!0,variant:s="ghost"})=>{const{fallbackLang:n,languages:a,selectedLang:r,setSelectedLang:i}=V.useLanguages(),o=g.isEmpty(r)?n:r,[,l]=_e(),{isLocked:u}=st();f.useEffect(()=>{const x=new URLSearchParams(window.location.search),b=x.get("lang");b&&(a.includes(b)?i(b):(x.delete("lang"),l(x),i("")))},[a,l,i]);const[,d]=ye.useAtom(os),{data:h}=ke(),{data:m}=$e(),{data:v}=Oe(),p=f.useMemo(()=>{const x=g.compact(g.map(g.get(m,"languages"),b=>{const E=g.find(v,{lang:b});return{key:b,value:g.get(we,b,b),isLangPageAdded:!!E}})).filter(Boolean);return[{key:n,value:g.get(we,n),isLangPageAdded:!0},...x]},[n,v,m]),y=x=>{if(document.querySelector('[data-panel-id="seo"]')){const E=new CustomEvent("seo-language-switch-check",{detail:{fromLang:o,toLang:x,switchHandler:()=>j(x)}});window.dispatchEvent(E);return}j(x)},j=x=>{i(x);const b=new URLSearchParams(window.location.search);x===n?b.delete("lang"):b.set("lang",x),Rt(b,l)};return g.isEmpty(a)?null:u?t.jsxs(c.Button,{variant:"ghost",size:"sm",className:"ml-px h-max cursor-not-allowed gap-2 py-1.5 opacity-50",children:[t.jsx(N.Languages,{className:"h-4 w-4"}),g.get(we,o,o),t.jsx(N.ChevronDown,{className:"h-4 w-4"})]}):t.jsx(t.Fragment,{children:t.jsxs(c.DropdownMenu,{children:[t.jsx(c.DropdownMenuTrigger,{asChild:!0,className:"focus:outline-none",children:t.jsxs(c.Button,{disabled:!!u,variant:s,size:"sm",className:"ml-px h-max gap-2 py-1.5",children:[t.jsx(N.Languages,{className:"h-4 w-4"}),g.get(we,o,o),t.jsx(N.ChevronDown,{className:"h-4 w-4"})]})}),t.jsxs(c.DropdownMenuContent,{className:"space-y-1 border-border",children:[g.map(p.filter(x=>x.isLangPageAdded),x=>t.jsxs(c.DropdownMenuItem,{className:V.mergeClasses("flex cursor-pointer items-center justify-between text-xs font-medium text-gray-800",x.key===o&&"!bg-gray-200 text-gray-700"),onClick:()=>y(x.key),children:[t.jsx("div",{className:"text-slate-600",children:x.value}),x.key===n&&t.jsxs("small",{className:"flex items-center gap-x-1 text-[9px] leading-none text-orange-500",children:[t.jsx(N.Star,{fill:"orange",className:"h-2 w-2"}),"Primary"]})]},x.value)),e&&!g.isEmpty(p.filter(x=>!x.isLangPageAdded))&&t.jsxs(t.Fragment,{children:[t.jsx(c.Separator,{}),t.jsxs(c.Button,{size:"sm",variant:"ghost",onClick:()=>{h&&d({edit:!1,primaryPage:h.id})},className:"text-xs font-normal duration-200 hover:bg-slate-300 hover:text-slate-800",children:[t.jsx(N.Plus,{className:"mr-1 h-3 w-3"})," Add Langauge"]})]})]})]})})};function ml(){const[e,s]=ye.useAtom(os);return t.jsxs("div",{className:"relative z-10 flex items-center justify-end gap-1",children:[t.jsx(dl,{}),t.jsx(hl,{}),e&&t.jsx(Ui,{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)})]})}function fl(){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))})}const gl=be.lazy(()=>Promise.resolve().then(()=>require("./page-revisions-content-Gx-Qf_91.cjs")));function xl(){const[e,s]=be.useState(!1);return t.jsx(c.TooltipProvider,{children:t.jsxs(c.Tooltip,{children:[t.jsxs(c.Sheet,{open:e,onOpenChange:s,children:[t.jsx(c.SheetTrigger,{asChild:!0,children:t.jsx(c.TooltipTrigger,{asChild:!0,children:t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsxs(c.Button,{variant:"ghost",size:"icon",className:"h-8 w-8",children:[t.jsx(N.History,{className:"h-4 w-4"}),t.jsx("span",{className:"sr-only",children:"View revision history"})]}),t.jsx("div",{className:"h-4 w-px bg-gray-200 dark:bg-gray-700"})]})})}),t.jsx(c.SheetContent,{className:"flex h-[100vh] flex-col",children:e&&t.jsx(f.Suspense,{fallback:t.jsx(fl,{}),children:t.jsx(gl,{isOpen:e})})})]}),t.jsx(c.TooltipContent,{side:"bottom",children:t.jsx("p",{children:"Revision history"})})]})})}const ze=({permission:e,permissions:s,children:n,fallback:a=null})=>{const{hasPermission:r}=V.usePermissions();return e&&!r(e)||s&&!s.some(i=>r(i))?a:n},pl=()=>{const e=oe(),s=se();return G.useQuery({queryKey:[_.GET_CHANGES],queryFn:async()=>s(e,{action:_.GET_CHANGES})})},yl=({page:e,selectedPages:s,handleCheckboxChange:n,getPageType:a,hasSlug:r,currentOwnerId:i})=>{const{data:o}=ls(i),l=o==null?void 0:o.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 ${l?"opacity-50":""}`,children:[l?t.jsx(N.Lock,{className:"h-4 w-4 fill-red-200 text-red-500"}):t.jsx("input",{checked:g.includes(s,e==null?void 0:e.id),onClick:u=>{u.stopPropagation(),n(e==null?void 0:e.id)},type:"checkbox",className:"cursor-pointer rounded focus:outline-none focus:ring-0"})," ",r(e.pageType)?t.jsx(N.File,{className:"h-4 w-4"}):t.jsx(N.GlobeIcon,{className:"h-4 w-4"}),t.jsx(Xe,{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(Xe,{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:g.first(e.changes)||""}),t.jsx(t.Fragment,{children:l&&t.jsxs("button",{className:"absolute right-0 top-0 flex h-full items-center gap-x-1 rounded bg-red-50 px-2 py-0.5 text-xs font-light text-red-500 opacity-0 group-hover:opacity-100",children:[t.jsx(N.Edit,{size:12,className:"stroke-[3]"})," ",t.jsx("span",{className:"font-medium",children:l})," is editing this page"]})})]},e==null?void 0:e.id)},vl=({onClose:e=()=>{},isPending:s,publishPage:n})=>{const[a]=ga(),[r,i]=f.useState([]),o=We(),[l,u]=f.useState(o),{data:d,isFetching:h}=pl(),{data:m}=Ae(),v=f.useCallback(k=>{var D;return(D=g.find(m,{key:k}))==null?void 0:D.hasSlug},[m]),p=f.useMemo(()=>g.filter(m,k=>!v(k.key)).map(k=>k.key),[v,m]),j=g.uniq(g.map(d,"lang")).filter(Boolean),x=f.useMemo(()=>g.filter(d,k=>k.pageType==="theme"?!1:l===o?k.lang===l||k.lang==="":k.lang===l),[d,l,o]),b=f.useMemo(()=>g.filter(x,k=>!p.includes(k.pageType)),[x,p]),E=f.useMemo(()=>g.filter(x,k=>p.includes(k.pageType)),[x,p]);f.useEffect(()=>{const k=g.map(g.filter(x,{online:!0}),"id");i(k)},[x]),f.useEffect(()=>{const k=Object.keys(a);i(D=>g.filter(D,K=>!g.includes(k,K)))},[a]);const P=r.length===(x==null?void 0:x.length),U=k=>{i(D=>g.includes(D,k)?g.filter(D,K=>K!==k):g.concat(D,k))},L=()=>{i(P?[]:g.map(x,"id"))},F=()=>{n({ids:g.uniq(r)},{onSuccess:()=>{e(),Gt("CENTER_CENTER"),u(o)}})},re=k=>{if(k==="theme")return"Theme";const D=g.find(m,{key:k});return D?D==null?void 0:D.name:k},$=f.useMemo(()=>{const k=[{label:"Updated",top:"pt-2"},...g.orderBy(g.filter(b,{online:!0}),"pageType"),...g.orderBy(g.filter(E,{online:!0}),"pageType")].filter(K=>K.pageType!=="theme"),D=[{label:"Offline",top:"pt-6"},...g.orderBy(g.filter(b,{online:!1}),"pageType"),...g.orderBy(g.filter(E,{online:!1}),"pageType")];return[...k,...D]},[b,E]);return t.jsxs(c.DialogContent,{className:"flex max-h-[80%] max-w-4xl flex-col",children:[t.jsxs(c.DialogHeader,{children:[t.jsx(c.DialogTitle,{children:"Publish changes"}),t.jsx(c.DialogDescription,{className:"text-xs",children:"Select the pages you want to publish. Click publish when you're done."})]}),j.length>0&&t.jsx("div",{className:"my-[2px] mt-0",children:t.jsx(Na,{languages:[o,...j],selectedLanguage:l,setSelectedLanguage:u})}),t.jsx("div",{className:"no-scrollbar relative -mx-4 -mt-4 h-full max-h-full overflow-y-auto",children:h?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:P,onClick:k=>{k.stopPropagation(),L()},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:g.map($,k=>k.label?t.jsx("tr",{children:t.jsxs("td",{colSpan:3,className:`relative px-6 py-2 text-xs font-medium text-gray-800 ${k.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:k.label})})]})},"separator"):t.jsx(yl,{page:k,selectedPages:r,handleCheckboxChange:U,getPageType:re,hasSlug:v,currentOwnerId:a[(k==null?void 0:k.primaryPage)||(k==null?void 0:k.id)]}))})]})}),t.jsxs(c.DialogFooter,{className:"mt-10 flex items-center justify-center",children:[r.length>0&&t.jsxs("span",{className:"text-center text-sm text-muted-foreground",children:[r.length," Page",r.length!==1?"s":""," Selected"]}),t.jsx(c.Button,{disabled:s,variant:"outline",onClick:e,children:"Cancel"}),t.jsx(c.Button,{disabled:s||h||g.isEmpty(r),onClick:F,children:s?"Publishing...":"Publish Selected"})]})]})};function jl({showModal:e=!1,onClose:s=()=>console.log("Cancelled")}){const{mutate:n,isPending:a}=xn();return t.jsx(c.Dialog,{open:e,onOpenChange:a?()=>{}:s,children:e&&t.jsx(vl,{onClose:s,isPending:a,publishPage:n})})}const bl=({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 o=()=>{s()},l=()=>{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:o,disabled:a,children:"Cancel"}),t.jsx(c.Button,{onClick:l,disabled:a,children:a?"Publishing...":"Continue Anyway"})]})]})})},Sl=()=>{const e=se(),s=oe();return G.useQuery({queryKey:[_.GET_WEBSITE_DATA],staleTime:1e3*60*5,queryFn:async()=>e(s,{action:_.GET_WEBSITE_DATA,data:{draft:!0}})})};function wl({onClose:e}){const{data:s,isFetching:n}=Sl(),{mutateAsync:a,isPending:r}=Qr(),i=Me("settingComponent",null),o=g.debounce(async l=>(await a({data:l}),!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:f.createElement(i,{data:s||{},onSave:r?()=>{}:o,cancel:r?()=>{}:e})})]})}):null}const El=()=>{const{selectedLang:e,fallbackLang:s}=V.useLanguages(),n=Me("getPreviewUrl",async m=>m),[a,r]=f.useState(""),{data:i}=ke(),{data:o}=Oe(),{data:l}=Ae(),u=f.useMemo(()=>{var m;return(m=o==null?void 0:o.find(v=>(v==null?void 0:v.lang)===e))==null?void 0:m.slug},[e,o]),d=f.useCallback(m=>{var v;return(v=g.find(l,{key:m}))==null?void 0:v.hasSlug},[l]),h=e===s?"":e;return f.useEffect(()=>{(async()=>{if(typeof n=="function"){const m=!d(i==null?void 0:i.pageType),v=await n(m?`${h!==""?h+"/":""}${i==null?void 0:i.id}`:u||"");r(v)}else r("")})()},[n,u,i==null?void 0:i.pageType,d,i==null?void 0:i.id,h]),t.jsx(t.Fragment,{children:t.jsx("a",{href:a,target:"_blank",rel:"noopener noreferrer",children:t.jsxs(c.Button,{variant:"ghost",size:"sm",className:"gap-2",children:[t.jsx(N.Eye,{className:"h-4 w-4"})," ",le.PREVIEW]})})})},Nl=()=>{const[e,s]=V.useRightPanel();return t.jsxs(t.Fragment,{children:[t.jsx(Xe,{content:le.THEME,children:t.jsx(c.Button,{variant:e==="theme"?"outline":"ghost",size:"icon",className:"gap-2",onClick:()=>s(e==="theme"?"block":"theme"),children:t.jsx(N.Palette,{className:"h-4 w-4"})})}),t.jsx("div",{className:"h-4 w-px bg-gray-200 dark:bg-gray-700"})]})},Cl=()=>{const[e,s]=f.useState(!1),{isLocked:n}=st(),{savePageAsync:a,saveState:r}=V.useSavePage();f.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=f.useCallback(async()=>{e||(s(!0),await a(),s(!1))},[a,e]),{buttonIcon:o,buttonClass:l,tooltipContent:u}=f.useMemo(()=>{switch(r){case"UNSAVED":return{tooltipContent:le.SAVEDRAFT,buttonIcon:t.jsx(N.Save,{className:"h-4 w-4"}),buttonClass:"gap-x-1"};case"SAVING":return{tooltipContent:le.SAVING,buttonIcon:t.jsx(N.Loader,{className:"h-4 w-4 animate-spin text-sky-700"}),buttonClass:"gap-x-1"};case"SAVED":return{tooltipContent:le.SAVED,buttonIcon:t.jsx(N.CheckCircle,{className:"h-4 w-4"}),buttonClass:"text-green-500 gap-x-1"}}},[r]);return n?null:t.jsxs(c.Button,{size:"sm",variant:"ghost",onClick:i,className:l,children:[o," ",u]})},Tl=()=>{const{selectedLang:e}=V.useLanguages(),{data:s}=Qe(),{data:n}=Oe(),[a,r]=f.useState(!1),[i,o]=f.useState(!1),[l,u]=f.useState(null),{savePageAsync:d}=V.useSavePage(),[h,m]=f.useState(!1),{data:v}=ke(),{mutate:p,isPending:y}=xn(),{needTranslations:j}=V.useSavePage(),x=j(),{buttonText:b,buttonClassName:E,isPublished:P}=f.useMemo(()=>{const k=v&&(v==null?void 0:v.online);return{buttonClassName:k?"hover:bg-green-600 bg-green-500":"",isPublished:k,buttonText:k?le.PUBLISHED:le.PUBLISH}},[v]),U=async()=>{if(x){m(!0);return}L()},L=()=>{const k=[s==null?void 0:s.id,s==null?void 0:s.primaryPage];p({ids:g.compact(k)},{onSuccess:()=>Gt("TOP_RIGHT")})},F=()=>{m(!1),L()},re=async()=>{m(!1),await d()},$=f.useMemo(()=>g.map(n??[],"id"),[n]);return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex",children:[t.jsxs(c.Button,{size:"sm",onClick:U,disabled:y||!(v!=null&&v.id),className:`relative flex items-center gap-1 overflow-hidden rounded-r-none text-white transition-all duration-300 ease-in-out ${E}`,onMouseEnter:()=>o(!0),onMouseLeave:()=>o(!1),children:[t.jsx("span",{className:`flex items-center transition-transform duration-300 ease-in-out ${i?"-translate-y-10":""}`,children:P?t.jsx(N.Send,{className:"h-4 w-4"}):t.jsx(N.Rocket,{className:"h-4 w-4"})}),t.jsx("span",{className:`absolute inset-0 left-3 flex items-center transition-transform duration-300 ease-in-out ${i?"":"translate-y-10"}`,children:P?t.jsx(N.Rocket,{className:"h-4 w-4"}):t.jsx(N.Send,{className:"h-4 w-4"})}),t.jsx("span",{children:b}),e?`(${g.upperCase(e)})`:""]}),t.jsxs(c.DropdownMenu,{children:[t.jsx(c.DropdownMenuTrigger,{asChild:!0,children:t.jsx(c.Button,{size:"sm",disabled:y||!(v!=null&&v.id),className:`rounded-l-none border-l border-white/50 px-2 text-white ${E}`,children:t.jsx(N.ChevronDown,{className:"h-4 w-4"})})}),t.jsxs(c.DropdownMenuContent,{align:"end",className:"w-52",children:[t.jsxs(c.DropdownMenuItem,{disabled:y,className:"cursor-pointer text-xs",onClick:()=>p({ids:$},{onSuccess:()=>Gt("TOP_RIGHT")}),children:[le.PUBLISH," with translation pages"]}),!P&&t.jsxs(c.DropdownMenuItem,{disabled:y,className:"cursor-pointer text-xs",onClick:()=>p({ids:[v==null?void 0:v.id]},{onSuccess:()=>Gt("TOP_RIGHT")}),children:[le.PUBLISH," page"]}),t.jsxs(c.DropdownMenuItem,{onClick:()=>r(!0),className:"cursor-pointer text-xs",children:[le.OPEN," publish menu"]}),P&&t.jsxs(c.DropdownMenuItem,{onClick:()=>u(s),className:"cursor-pointer text-xs",children:[le.UNPUBLISH," page ",e?`(${g.upperCase(e)})`:""]})]})]})]}),t.jsx(jl,{showModal:a,onClose:()=>r(!1)}),l&&t.jsx(Gs,{page:l,onClose:()=>u(null)}),t.jsx(bl,{isOpen:h,onClose:re,onContinue:F,isPending:y})]})},Al=()=>{const e=Me("settingComponent",null),[s,n]=f.useState(!1);return e?t.jsxs(t.Fragment,{children:[t.jsx(Xe,{content:le.WEBSITEDATA,children:t.jsx(c.Button,{variant:"ghost",size:"icon",className:"gap-2",onClick:()=>n(!0),children:t.jsx(N.Settings,{className:"h-4 w-4"})})}),s&&t.jsx(wl,{onClose:()=>n(!1)}),t.jsx("div",{className:"h-4 w-px bg-gray-200 dark:bg-gray-700"})]}):null};function kl(){const{isLocked:e}=st(),[s]=_e(),n=s.get("lang"),a=ua(n);return e||!a?t.jsx("div",{}):t.jsxs("div",{className:"flex items-center justify-end gap-1",children:[t.jsx(xl,{}),t.jsx(ze,{permission:Se.EDIT_THEME,children:t.jsx(Nl,{})}),t.jsx(ze,{permission:Se.EDIT_SETTINGS,children:t.jsx(Al,{})}),t.jsx(El,{}),t.jsx(ze,{permission:Se.SAVE_PAGE,children:t.jsx(Cl,{})}),t.jsx(ze,{permission:Se.PUBLISH_PAGE,children:t.jsx(Tl,{})})]})}const Pl=({isDefaultLang:e,searchQuery:s,setSearchQuery:n})=>t.jsx(c.Input,{type:"text",autoFocus:!0,value:e?s:"",onChange:a=>n(a.target.value),placeholder:e?"Search pages...":"To search select default language",disabled:!e,onKeyDown:a=>a.stopPropagation()}),Il=({dynamicPage:e,setDynamicPage:s,searchQuery:n,setSearchQuery:a,dynamicPages:r})=>{const{selectedLang:i,fallbackLang:o}=V.useLanguages(),l=(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?g.get(e,"name"):"Select Page",t.jsx(N.ChevronDown,{className:"ml-2 h-4 w-4"})]})}),t.jsxs(c.DropdownMenuContent,{className:"w-96 divide-y shadow-xl p-0 max-h-[75vh]",children:[t.jsx("div",{className:"p-1.5 bg-gray-50/30",children:t.jsx(Pl,{isDefaultLang:l,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:l?o!==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))]})]})},_l=()=>{const{dynamicPage:e,dynamicPages:s,allLangPages:n,selectedLang:a,searchQuery:r,updateDynamicPage:i,updateSearchQuery:o,onChangeLanguage:l}=ma(),u=f.useRef(void 0);return f.useEffect(()=>{u.current!==a&&e&&(l(),u.current=a)},[a,s]),t.jsx("div",{className:"relative",children:t.jsx(Il,{dynamicPage:e,setDynamicPage:i,searchQuery:r,setSearchQuery:o,dynamicPages:n})})},Ll=()=>{const[e,s]=f.useState(null),[n,a]=f.useState(null),[r,i]=f.useState(null),[o,l]=f.useState(null),[u,d]=f.useState(null),[h,m]=f.useState(null),[v,p]=f.useState(!1),{data:y,isFetching:j}=Qe(),{selectedLang:x,fallbackLang:b}=V.useLanguages(),{data:E}=Oe(),P=E==null?void 0:E.find(k=>k.lang===x),{isLocked:U}=st(),L=!(y!=null&&y.slug),[,F]=ye.useAtom(os),{savePage:re}=V.useSavePage();if(!y)return null;const $=k=>{x.length>0&&x!==b?F({edit:!0,id:k==null?void 0:k.id,primaryPage:k==null?void 0:k.primaryPage}):m(k)};return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex items-center justify-between px-[2px] rounded transition-colors duration-200",children:[t.jsx(c.Button,{className:"flex h-7 max-w-[200px] cursor-pointer items-center truncate rounded px-1 text-xs font-medium",variant:"ghost",onClick:()=>{re(),p(!0)},children:j?t.jsx(N.Loader,{className:"h-4 w-4 animate-spin text-slate-400"}):t.jsxs("span",{className:"flex w-full cursor-pointer items-end overflow-hidden text-ellipsis whitespace-nowrap rounded-sm text-xs font-medium",children:[L?t.jsx(N.Globe,{className:"mr-1 h-4 w-4"}):t.jsx(N.File,{className:"mr-1 h-4 w-4"}),g.get(P||y,"name")??""]})}),U?t.jsx(c.Button,{variant:"ghost",size:"icon",className:"h-7 w-7 cursor-not-allowed rounded opacity-50 hover:bg-transparent",children:t.jsx(N.MoreHorizontal,{className:"h-4 w-4"})}):t.jsx(Ca,{page:y,setDuplicatePage:k=>d(k),setAddEditPage:k=>$(k),setUnpublishPage:k=>a(k),setDeletePage:k=>s(k),setMarkAsTemplate:k=>i(k),setUnmarkAsTemplate:k=>l(k),isLanguagePage:x.length>0&&x!==b,children:t.jsx(c.Button,{variant:"ghost",size:"icon",className:"h-7 w-7 rounded",children:t.jsx(N.MoreHorizontal,{className:"h-4 w-4"})})})]}),h&&t.jsx(Aa,{closePanel:()=>m(null),editPage:()=>{},addEditPage:h,setAddEditPage:m}),e&&t.jsx(bn,{page:e,onClose:()=>s(null)}),n&&t.jsx(Gs,{page:n,onClose:()=>a(null)}),r&&t.jsx(Pa,{page:r,onClose:()=>i(null)}),o&&t.jsx(Ia,{page:o,onClose:()=>l(null)}),u&&t.jsx(ka,{page:u,onClose:()=>d(null),closePanel:()=>m(null)}),t.jsx(c.Sheet,{open:v,onOpenChange:p,children:t.jsxs(c.SheetContent,{side:"left","aria-describedby":"pages-manager-description",className:"z-50 w-full !max-w-screen-md border-border px-1",children:[t.jsxs(c.SheetHeader,{className:"mb-3",children:[t.jsxs(c.SheetTitle,{className:"flex items-center gap-2 px-4 text-sm font-semibold",children:[t.jsx("div",{className:"flex h-9 w-9 items-center justify-center rounded-lg bg-primary text-primary-foreground",children:t.jsx(N.Folder,{className:"h-4 w-4"})}),t.jsxs("div",{className:"flex flex-col",children:[t.jsx("span",{className:"text-sm font-semibold",children:"Pages"}),t.jsx("span",{id:"pages-manager-description",className:"text-xs font-normal text-muted-foreground",children:"Manage your site structure"})]})]}),t.jsx(c.SheetDescription,{className:"sr-only",children:"Manage your site structure"})]}),t.jsx("div",{className:"h-[calc(100vh-80px)] overflow-y-auto",children:t.jsx(_a,{close:()=>p(!1)})})]})})]})},Dl=({hasDynamicPage:e})=>t.jsx(kt,{children:t.jsxs("div",{className:"flex min-w-[300px] max-w-[400px] flex-col items-center justify-center rounded-lg border bg-white p-4 shadow-lg",children:[t.jsx("h1",{className:"text-lg font-medium",children:e?"Select a page":"No pages found"}),t.jsx("p",{className:"pt-2 text-center text-sm font-light text-gray-600",children:e?"Please select a page from the list in the top header. This will enable you to edit the page.":"Please add a new page"})]})}),Bl=()=>{const{data:e,isFetching:s}=Qe(),{data:n,isFetching:a}=ke(),{dynamicPage:r,allLangPages:i,isFetching:o}=ma(),l=g.get(n,"dynamic",!1),u=i.length>0,d=mn(),h=V.useChaiFeatureFlag("dynamic-page-selector"),m=e==null?void 0:e.slug,v=!m,p=fa(),y=s||a,x=(v?`Partial: ${e==null?void 0:e.name} `:`${m}${d}`).replace(window.location.host,"");return t.jsxs("div",{className:"relative z-10 flex items-center gap-x-1",children:[t.jsx("div",{className:V.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",y&&"max-w-0 overflow-hidden opacity-0"),children:t.jsx(Ll,{})}),t.jsxs("div",{className:V.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"+(v?" pr-2":""),y&&"max-w-0 overflow-hidden opacity-0"),children:[t.jsx(Sn,{}),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 ${v?"italic text-gray-400":"font-mono text-gray-500"}`,children:x==="/"?t.jsxs("span",{className:"text-gray-900",children:["/",t.jsx("span",{className:"text-[11px] font-light italic text-gray-400",children:"(Homepage)"})]}):x}),!v&&t.jsx("a",{href:p,target:"_blank",rel:"noopener noreferrer",children:t.jsx("div",{className:"ml-2 mr-px flex-shrink-0 rounded-sm p-1.5 text-gray-500 hover:bg-gray-100 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-300",children:t.jsx(N.ExternalLink,{className:"h-4 w-4",strokeWidth:1})})})]})]}),l&&!o&&h&&t.jsxs("div",{className:"relative",children:[!r&&t.jsx(Dl,{hasDynamicPage:u}),t.jsx(_l,{})]})]})},Ol=()=>t.jsxs("div",{className:"flex h-full w-full items-center justify-between px-2",children:[t.jsx(ml,{}),t.jsx(Bl,{}),t.jsx(kl,{})]}),La=()=>{const e=G.useQueryClient(),{data:s}=G.useQuery({queryKey:[_.AI_CONTEXT],initialData:"",queryFn:()=>"",staleTime:0});return{setAiContext:f.useCallback(a=>{e.setQueryData([_.AI_CONTEXT],a)},[e]),aiContext:s}},Ml=()=>{const e=oe(),{aiContext:s}=La(),n=se();return f.useCallback(async(a,r,i,o)=>n(e,{action:_.ASK_AI,data:{type:a,prompt:r,blocks:i,context:s,lang:o}}),[e,s,n])},Gl=(e,s)=>s.map(n=>{if(g.has(e,n._type)){const a=sa.getDefaultBlockProps(n._type);return{...a,...g.pick(n,[...g.keys(a),"_type","_id","_name","_parent","_bindings"]),...g.pickBy(n,(r,i)=>g.endsWith(i,"_attrs")),...n}}return n}),Rl=e=>{const s=sa.useRegisteredChaiBlocks();return f.useMemo(()=>{if(!e||g.isEmpty(e))return{blocks:[]};const n=g.filter(e,a=>!g.includes(a==null?void 0:a._type,"@chai/"));return{blocks:Gl(s,n)}},[e,s])},Ul=()=>{const[e]=_e(),s=e.get("page"),n=oe(),{setAiContext:a}=La(),[,r]=Os(),[,i]=ni(),[,o]=V.useIsPageLoaded(),l=se();return G.useQuery({queryKey:[_.GET_DRAFT_PAGE,s],staleTime:1/0,gcTime:1/0,queryFn:async()=>{o(!1);const u=await l(n,{action:_.GET_DRAFT_PAGE,data:{id:s,draft:!0}}),d=u.blocks??[],h=g.find(d,{_type:"@chai/ai-context"});return a(g.get(h,"_value","")||""),r(m=>({...m,lastSaved:u.lastSaved})),i(g.get(u,"metadata",{})),setTimeout(()=>o(!0),500),d},enabled:!!s})},wn=()=>{const{data:e}=ke(),{data:s}=Qe(),n=oe(),a=se(),r=We(),i=mn();return G.useQuery({queryKey:[_.GET_BUILDER_PAGE_DATA,s==null?void 0:s.id,i],initialData:{},queryFn:async()=>a(n,{action:_.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,metadata:e.metadata||{}}}}),enabled:!!(e!=null&&e.pageType)&&!!s.id})},Mn={async getUILibraryBlock(e,s,n){const a=await s(n,{action:"GET_LIBRARY_ITEM",data:{id:e.id}}),r=g.get(a,"html",""),i=g.get(a,"blocks",[]);return g.isArray(i)?i:V.getBlocksFromHTML(r)},async getUILibraryBlocks(e,s,n){try{return(await s(n,{action:"GET_LIBRARY_ITEMS",data:{id:e.id}})).map(r=>({...r}))}catch(a){return console.error(a),[]}}},Fl=()=>{const e=oe(),s=se();return G.useQuery({queryKey:["uiLibraries"],initialData:[],queryFn:async()=>{const a=(await s(e,{action:"GET_LIBRARIES"})).map(r=>({...r}));return a.forEach(r=>{V.registerChaiLibrary(r.id,{name:r.isSiteLibrary?r.name+" (Current Site) ":r.name,description:r.description,getBlocksList:i=>Mn.getUILibraryBlocks(i,s,e),getBlock:({block:i})=>Mn.getUILibraryBlock(i,s,e)})}),a}})},Da=()=>{const e=Bs(),s=se(),{user:n}=Fe(),a=n==null?void 0:n.id;return G.useQuery({queryKey:["permissions",a],queryFn:()=>s(e,{action:_.GET_ROLE_AND_PERMISSIONS,data:{userId:a}}),enabled:!!a})},ql=()=>{const e=oe(),s=se(),[,n]=Os();return{onSave:async({page:r,blocks:i,needTranslations:o})=>{try{const l=await s(e,{action:"UPDATE_PAGE",data:{id:r,blocks:i,needTranslations:o}});return l.code==="PAGE_LOCKED"?!0:(n(u=>({...u,lastSaved:new Date().toISOString()})),l)}catch(l){return console.error(l),new Error("Failed to save blocks")}}}},zl=()=>{const{data:e}=_t(),s=oe(),n=se();return{getPartialBlocks:f.useCallback(async()=>{const a={};for(const r of e??[])g.isEmpty(r==null?void 0:r.slug)&&(a[r.id]={type:r.pageType,name:g.startCase(r.name??r.slug),description:""});return a},[e]),getPartialBlockBlocks:f.useCallback(async a=>{if(!a)return[];try{const r=await n(s,{action:"GET_DRAFT_PAGE",data:{id:a,draft:!0,editor:!1}});return g.filter(r.blocks,i=>g.has(i,"_id"))}catch(r){return console.error(r),[]}},[n,s])}},Gn=vs.z.object({email:vs.z.string().email({message:"Please enter a valid email address"}),password:vs.z.string().min(6,{message:"Password must be at least 6 characters"})}),Vl=()=>{const{setUser:e,logout:s}=Fe(),n=Bs(),[a,r]=f.useState(""),[i,o]=f.useState(""),[l,u]=f.useState({}),[d,h]=f.useState(!1),[m,v]=f.useState(""),p=G.useMutation({mutationFn:async x=>{v("");const b=await hn(n,{action:"LOGIN",data:x});if(!b.ok){const P=await b.json();throw new Error(P.error||"Login failed")}const E=await b.json();if(g.has(E,"id")&&g.has(E,"email")&&g.has(E,"accessToken")&&g.has(E,"refreshToken"))e(E);else throw s(),new Error("Something went wrong. Please try again.");return E},onSuccess:()=>{u({}),v("")},onError:x=>{u({email:" ",password:" "}),v(x.message?"Invalid email or password":"Something went wrong")}}),y=async x=>{x.preventDefault(),u({});const b={email:a,password:i};try{const E=Gn.parse(b);p.mutate(E)}catch(E){if(E instanceof vs.z.ZodError){const P=E.issues.reduce((U,L)=>{const F=L.path[0];return U[F]=L.message,U},{});u(P)}}},j=Gn.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:y,className:"space-y-4",children:[t.jsxs("div",{className:"space-y-1",children:[t.jsx(c.Label,{htmlFor:"email",children:"Email"}),t.jsx(c.Input,{id:"email",placeholder:"you@example.com",type:"email",value:a,onChange:x=>r(x.target.value),className:l.email?"border-destructive":""}),l.email&&t.jsx("p",{className:"text-sm text-destructive",children:l.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:x=>o(x.target.value),className:l.password?"border-destructive":""}),t.jsx("button",{type:"button",className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground",onClick:()=>h(!d),children:d?t.jsx(N.EyeOff,{className:"h-4 w-4"}):t.jsx(N.Eye,{className:"h-4 w-4"})})]}),l.password&&t.jsx("p",{className:"text-sm text-destructive",children:l.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:!j||p.isPending,children:p.isPending?t.jsxs(t.Fragment,{children:[t.jsx(N.Loader,{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 tn=Vl;const $l=()=>f.useMemo(()=>tn,[tn]),Kl=e=>{tn=e},Rn=()=>{const e=$l();return t.jsx(f.Suspense,{fallback:t.jsx("div",{children:"Loading..."}),children:t.jsx(e,{})})},Hl=({page:e,onClose:s})=>{const[n,a]=f.useState(e.slug||""),{mutate:r,isPending:i}=Ai(),{data:o}=Ae(),l=g.find(o,{key:e==null?void 0:e.pageType}),u=h=>{if(h.preventDefault(),!(e!=null&&e.primaryPage)&&Object.keys(we).some(p=>n===`/${p}`||g.startsWith(n,`/${p}/`))){Q.toast.error("Error",{description:"Slugs cannot start with a language code for primary page"});return}r({...e,slug:n},{onSuccess:s})},d=(e==null?void 0:e.lang)||"";return t.jsx(c.Dialog,{open:!!e,onOpenChange:s,children:t.jsxs(c.DialogContent,{children:[t.jsxs(c.DialogHeader,{children:[t.jsx(c.DialogTitle,{children:"Change Slug"}),t.jsx(c.DialogDescription,{className:"text-xs",children:t.jsxs(c.Alert,{variant:"destructive",className:"mt-2",children:[t.jsx(N.AlertCircle,{className:"h-4 w-4"}),"Changing the slug may have impact on your SEO. Please proceed with caution."]})})]}),t.jsxs("form",{onSubmit:u,children:[t.jsxs("div",{className:"space-y-4 py-4 text-sm ",children:[t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{children:[t.jsx("span",{children:"Type:"}),t.jsxs("span",{className:"font-medium text-gray-600",children:[" ",(l==null?void 0:l.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;g.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||!g.startsWith(n,`/${d}`)||g.isEqual(e==null?void 0:e.slug,n),children:i?"Changing...":"Change Slug"})})]})]})})},Ql=()=>{const[,e]=ye.useAtom(os),{selectedLang:s,fallbackLang:n,setSelectedLang:a}=V.useLanguages(),{data:r,isFetching:i}=Oe(),{data:o}=ke(),{data:l}=Ae(),u=f.useMemo(()=>{const b=l==null?void 0:l.find(E=>E.key===(o==null?void 0:o.pageType));return o!=null&&o.dynamic?b==null?void 0:b.dynamicSlug:""},[l,o==null?void 0:o.pageType,o==null?void 0:o.dynamic]),[d,h]=f.useState(null),[m,v]=f.useState(null),[p,y]=f.useState(null),{data:j}=$e(),x=g.filter(g.get(j,"languages")||["en"],b=>!g.find(r,{lang:b})&&b!==g.get(j,"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"})]}):g.map(r,b=>{const E=b.lang,P=b.slug,U=!b.primaryPage,L=E===s;return t.jsxs(t.Fragment,{children:[t.jsxs("li",{className:`flex w-full cursor-pointer items-center justify-between rounded p-2 text-slate-500 ${L?"bg-gray-200":"hover:bg-gray-100"}`,onClick:()=>a(E),children:[t.jsxs("div",{className:"flex-1 gap-x-3",children:[t.jsxs("div",{className:"flex items-center gap-x-2 text-[13px] text-slate-800",children:[t.jsx("div",{className:`h-2.5 w-2.5 rounded-full ${b.online?"bg-green-300":"bg-gray-300"}`}),g.get(we,U?n:E,E)]}),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," "]})]})]})]}),U?t.jsxs("div",{className:"flex items-center gap-x-1 text-[11px] text-orange-500",children:[t.jsx(N.StarIcon,{fill:"orange",className:"h-3 w-3"}),t.jsx("b",{children:" Primary"})]}):t.jsx("div",{className:"flex items-center gap-x-3",children:t.jsx(ze,{permissions:[Se.EDIT_PAGE,Se.DELETE_PAGE,Se.UNPUBLISH_PAGE],children:t.jsxs(c.DropdownMenu,{children:[t.jsx(c.DropdownMenuTrigger,{asChild:!0,onClick:F=>F.stopPropagation(),children:t.jsx(c.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",children:t.jsx(N.MoreHorizontal,{className:"h-4 w-4"})})}),t.jsxs(c.DropdownMenuContent,{align:"end",className:"z-[9999] text-sm",children:[t.jsx(ze,{permissions:[Se.EDIT_PAGE],children:t.jsxs(c.DropdownMenuItem,{className:"flex cursor-pointer items-center gap-2",onClick:F=>{F.stopPropagation(),e({edit:!0,id:b.id,primaryPage:b.primaryPage})},children:[t.jsx(N.PencilIcon,{className:"size-3"}),le.EDIT]})}),t.jsx(ze,{permissions:[Se.UNPUBLISH_PAGE],children:(b==null?void 0:b.online)&&t.jsxs(c.DropdownMenuItem,{className:"flex cursor-pointer items-center gap-2",onClick:F=>{F.stopPropagation(),v(b)},children:[t.jsx(N.Power,{className:"size-3"}),le.UNPUBLISH]})}),t.jsx(ze,{permissions:[Se.DELETE_PAGE],children:t.jsxs(c.DropdownMenuItem,{className:"flex cursor-pointer items-center gap-2",onClick:F=>{F.stopPropagation(),h(b)},children:[t.jsx(N.TrashIcon,{className:"size-3"}),le.DELETE]})})]})]})})})]},b.id),t.jsx("div",{className:"h-1 w-full border-b"})]})})}),t.jsx(ze,{permissions:[Se.ADD_PAGE],children:t.jsx("div",{className:"flex w-full justify-center",children:t.jsx(c.Button,{variant:"default",size:"sm",disabled:g.isEmpty(x),onClick:()=>{e({primaryPage:o==null?void 0:o.id,edit:!1})},children:le.ADD_NEW_LANGUAGE})})}),d&&t.jsx(bn,{page:d,onClose:()=>h(null)}),m&&t.jsx(Gs,{page:m,onClose:()=>v(null)}),p&&t.jsx(Hl,{page:p,onClose:()=>y(null)})]})},Wl=({isActive:e,show:s})=>{const{data:n}=$e();return!g.has(n,"languages")||!g.get(n,"languages",[]).length?null:t.jsx(c.Button,{size:"sm",onClick:s,variant:e?"default":"ghost",children:t.jsx(N.LanguagesIcon,{className:"w-4 h-4"})})},Ba="lang",Jl={id:Ba,label:"Languages",position:"top",panel:Ql,button:Wl,view:"modal",width:400};function Ke({data:e,onSelect:s,dataType:n="value",disabled:a=!1}){const[r,i]=be.useState(!1),[o,l]=be.useState([]),[u,d]=be.useState(e);be.useEffect(()=>{r||l([]),d(e)},[e,r]);const h=y=>Array.isArray(y)?"array":typeof y=="object"&&y!==null?"object":"value",m=be.useCallback(y=>{const j=x=>n==="value"?x==="value"||x==="object":n==="array"?x==="array":x===n;y.type==="object"?(l(x=>[...x,y.key]),d(y.value)):j(y.type)&&(s([...o,y.key].join(".")),i(!1))},[o,s,n]),v=be.useCallback(()=>{if(o.length>0){const y=o.slice(0,-1);l(y),d(y.reduce((j,x)=>j[x],e))}},[o,e]),p=be.useMemo(()=>Object.entries(u).map(([y,j])=>({key:y,value:j,type:h(j)})).filter(y=>n==="value"?y.type==="value"||y.type==="object":n==="array"?y.type==="array"||y.type==="object":n==="object"?y.type==="object":!0),[u,n]);return t.jsxs(c.Popover,{open:r,onOpenChange:i,children:[t.jsxs(c.Tooltip,{children:[t.jsx(c.TooltipTrigger,{asChild:!0,children:t.jsx(c.PopoverTrigger,{asChild:!0,children:t.jsx(c.Button,{size:"sm",variant:"outline",className:"h-6 w-6 px-1 py-0 text-[9px] text-muted-foreground",role:"combobox","aria-expanded":r,disabled:a,children:t.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24px",height:"24px",viewBox:"0 0 24 24",fill:"none",children:t.jsx("path",{d:"M9.5 5H9C7.89543 5 7 5.89543 7 7V9C7 10 6.4 12 4 12C5 12 7 12.6 7 15V17.0002C7 18.1048 7.89543 19 9 19H9.5M14.5 5H15C16.1046 5 17 5.89543 17 7V9C17 10 17.6 12 20 12C19 12 17 12.6 17 15V17.0002C17 18.1048 16.1046 19 15 19H14.5",stroke:"#000000",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2"})})})})}),t.jsx(c.TooltipContent,{children:"Add field"})]}),t.jsx(c.PopoverContent,{className:"z-[9999] w-[200px] p-0",children:t.jsxs(c.Command,{children:[t.jsx(c.CommandInput,{className:"border-none",placeholder:"Search..."}),t.jsxs(c.CommandList,{onWheel:y=>{try{y.preventDefault();const j=y.currentTarget;j.scrollTop+=y.deltaY}catch{y.preventDefault()}},children:[t.jsx(c.CommandEmpty,{children:"No option found."}),t.jsxs(c.CommandGroup,{children:[o.length>0&&t.jsxs(c.CommandItem,{onSelect:v,className:"flex items-center text-sm",children:[t.jsx(N.ChevronLeft,{className:"mr-2 h-4 w-4"}),"Back"]}),p.map(y=>t.jsxs(c.CommandItem,{onSelect:()=>m(y),className:"flex items-center justify-between",children:[t.jsx("span",{children:y.key}),t.jsxs("div",{className:"flex items-center gap-2",children:[n==="object"&&y.type==="object"&&t.jsx(c.Button,{size:"sm",variant:"ghost",className:"h-6 px-2 hover:bg-primary hover:text-primary-foreground",onClick:j=>{j.stopPropagation(),s([...o,y.key].join(".")),i(!1)},children:"Select"}),(y.type==="object"||y.type==="array")&&t.jsx("div",{className:"cursor-pointer rounded p-1 hover:bg-muted",children:t.jsx(N.ChevronRight,{className:"h-4 w-4 opacity-50"})})]})]},y.key))]})]})]})})]})}const Yl=()=>{const{selectedLang:e}=V.useLanguages(),{data:s,isFetching:n}=Oe();return{data:f.useMemo(()=>g.find(s,{lang:e||""})||{},[s,e]),isFetching:n}},Xl=()=>{var o;const s=(o=document.getElementById("canvas-iframe").contentDocument)==null?void 0:o.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(l=>l.remove()),a.querySelectorAll("*").forEach(l=>{Array.from(l.attributes).forEach(u=>l.removeAttribute(u.name))});const r=a.querySelectorAll("h1, h2, h3, h4, h5, h6, p");return Array.from(r).map(l=>`<${l.tagName.toLowerCase()}>${l.innerHTML}</${l.tagName.toLowerCase()}>`).join(" ").replace(/<p>Partial block. Double click to edit.<\/p>/,"")},ut=({keyword:e,onComplete:s,field:n})=>{const a=se(),r=oe(),{selectedLang:i,fallbackLang:o}=V.useLanguages(),{mutate:l,isPending:u}=G.useMutation({mutationFn:async()=>{const d=Xl();return await a(r,{action:_.GENERATE_SEO_FIELD,data:{pageContext:"",dynamic:!1,field:n,lang:i||o,pageContent:d,keyword:e}})},onSuccess:d=>{s({fieldValue:d.field})},onError:d=>{s({fieldValue:null,error:d.message})}});return t.jsx(c.Button,{disabled:u,type:"button",className:"h-5 w-5",variant:"ghost",size:"sm",onClick:()=>l(),children:u?t.jsx(N.Loader,{className:"h-3 w-3 animate-spin text-yellow-500"}):t.jsx(N.Wand2Icon,{className:"text-yellow-500"})})},Zl=({isOpen:e,onClose:s,onSave:n,onDiscard:a,isSaving:r=!1,fromLanguage:i,toLanguage:o})=>{const l=we[i]||i,u=we[o]||o;return t.jsx(c.Dialog,{open:e,onOpenChange:s,children:t.jsxs(c.DialogContent,{className:"sm:max-w-[425px]",children:[t.jsxs(c.DialogHeader,{children:[t.jsx(c.DialogTitle,{children:"Unsaved SEO Changes"}),t.jsxs(c.DialogDescription,{children:['You have unsaved changes in the SEO for "',l,'" version. Do you want to save these changes before switching to "',u,'" version?']})]}),t.jsxs("div",{className:"flex justify-end gap-3 pt-4",children:[t.jsx(c.Button,{variant:"outline",onClick:a,disabled:r,children:"Discard Changes"}),t.jsx(c.Button,{onClick:n,disabled:r,children:r?"Saving...":"Save & Switch"})]})]})})},eo=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Es=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],o=r.index,l=`"__placeholder_${n.length}__"`;n.push({original:i,replaced:l,position:o}),a=a.replace(i,l)}try{return{isValid:!0,parsed:JSON.parse(a),error:null,placeholders:n}}catch(i){const o=i,l=o.message.match(/position (\d+)/),u=l?parseInt(l[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:o.message,line:d,column:h,position:u}}}},to=(e,s)=>{let a=JSON.stringify(e,null,2);return s.forEach(({original:r},i)=>{const o=`"__placeholder_${i}__"`,l=new RegExp(eo(o),"g");a=a.replace(l,r)}),a},so=(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],o=g.get(s,i,null);n=n.replace(r[0],o)}return n},Oa=()=>{const e=oe(),s=se();return G.useQuery({queryKey:[_.GET_APP_SHARED_JSONLD],queryFn:async()=>await s(e,{action:_.GET_APP_SHARED_JSONLD})||[],initialData:[],retry:2})},Ma=()=>{const e=oe(),s=se(),{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:_.UPDATE_PAGE_METADATA,data:{id:n.id,metadata:r}})},onSuccess:()=>{a.invalidateQueries({queryKey:[_.GET_BUILDER_PAGE_DATA]}),a.invalidateQueries({queryKey:[_.GET_LANGUAGE_PAGES]})},onError:()=>{console.error("Failed to update metadata")}})};function no(){const{data:e}=ke(),s=g.get(e,"metadata",{})||{},[n,a]=f.useState(g.get(s,"sharedJsonLD",[])||[]),[r,i]=f.useState({show:!1,data:null}),{mutateAsync:o}=Ma(),[l,u]=f.useState(null),{data:d,isLoading:h}=Oa(),{mutateAsync:m}=ca(),{selectedLang:v}=V.useLanguages(),p=async x=>{await o({...s,sharedJsonLD:x}),a(x),u(null)},y=async x=>{u(x);let b=[...n];g.includes(n,x)?b=b.filter(E=>E!==x):b=[...b||[],x],await p(b)},j=async x=>{u(x);try{const b=d==null?void 0:d.filter(E=>E.id!==x);await m(b),a(b),u(null)}catch{u(null)}};return t.jsxs("div",{className:"rounded border bg-muted p-2",children:[t.jsxs("div",{className:"flex items-center justify-between pb-2",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-xs font-medium",children:"Shared JSON-LD Templates"}),t.jsx("div",{className:"w-full text-xs text-gray-500",children:"Manage reusable JSON-LD schemas that can be applied across multiple pages"})]}),!v&&t.jsxs(c.Tooltip,{delayDuration:0,children:[t.jsx(c.TooltipTrigger,{type:"button",disabled:h,className:"rounded-full bg-primary p-1 text-primary-foreground hover:bg-primary/80",onClick:x=>{x.stopPropagation(),i({show:!0,data:null})},children:h?t.jsx(N.Loader,{className:"h-4 w-4 animate-spin"}):t.jsx(N.Plus,{className:"h-4 w-4"})}),t.jsx(c.TooltipContent,{children:"Add new schema"})]})]}),t.jsxs(c.ScrollArea,{className:"max-h-96 overflow-y-auto",children:[t.jsxs("div",{className:"space-y-2",children:[(!d||(d==null?void 0:d.length)===0)&&!h&&t.jsx("div",{className:"flex items-center justify-center px-2 py-4 text-xs",children:"No shared JSON-LD found"}),d==null?void 0:d.map(x=>{const b=Es(x.content),E=b.isValid?b.parsed:"",P=g.includes(n,x.id),U=!v;return t.jsxs(c.Card,{className:`relative border-gray-300 p-0 shadow-none transition-all ${l===x.id?"pointer-events-none":""}`,children:[l===x.id&&t.jsx("div",{className:"absolute bottom-0 left-0 right-0 top-0 z-50 flex items-center justify-center rounded-xl bg-white/80",children:t.jsx(N.Loader,{className:"h-5 w-5 animate-spin text-primary"})}),t.jsx(c.CardHeader,{className:"p-2",children:t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsxs("div",{className:"flex items-center gap-3",children:[U&&t.jsx(c.Switch,{checked:P,onCheckedChange:()=>y(x.id)}),t.jsxs("div",{children:[t.jsx(c.CardTitle,{className:"flex items-center gap-2 text-sm leading-none",children:x.name}),(x==null?void 0:x.description)&&t.jsx("p",{className:"mt-1 text-xs leading-none text-muted-foreground",children:x==null?void 0:x.description})]})]}),U&&t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(c.Button,{type:"button",variant:"ghost",size:"icon",className:"h-5 w-5 p-0",onClick:()=>i({show:!0,data:x}),children:t.jsx(N.Edit,{className:"h-4 w-4"})}),t.jsxs(c.AlertDialog,{children:[t.jsx(c.AlertDialogTrigger,{className:"flex h-5 w-5 items-center justify-center rounded-md text-red-500 hover:bg-red-100 hover:text-red-800",children:t.jsx(N.Trash,{className:"h-4 w-4"})}),t.jsxs(c.AlertDialogContent,{children:[t.jsxs(c.AlertDialogHeader,{children:[t.jsx(c.AlertDialogTitle,{children:"Delete Schema"}),t.jsxs(c.AlertDialogDescription,{children:["Are you sure you want to delete ",t.jsx("span",{className:"font-medium",children:x.name}),"? This action cannot be undone."]})]}),t.jsxs(c.AlertDialogFooter,{children:[t.jsx(c.AlertDialogCancel,{type:"button",children:"Cancel"}),t.jsx(c.AlertDialogAction,{type:"button",onClick:()=>j(x.id),className:"bg-red-500 text-white hover:bg-red-600",children:"Delete"})]})]})]})]})]})}),t.jsx(c.CardContent,{className:"px-2 pb-2",children:U?t.jsx(c.Textarea,{id:x.id,rows:1,readOnly:!0,value:JSON.stringify(E,null,2),className:"no-scrollbar cursor-text overflow-hidden rounded-md border-none bg-gray-100/80 text-xs"}):t.jsxs("div",{className:"flex h-20 w-full flex-col items-center justify-center rounded-lg border bg-gray-100",children:[t.jsx("div",{className:"max-w-xl text-center text-xs text-gray-500",children:"Not available in selected language, but available in default language."}),t.jsx(c.Button,{size:"sm",variant:"outline",className:"mt-2",onClick:()=>{},children:"Copy & Edit from default language"})]})})]})})]}),h&&t.jsx("div",{className:"flex items-center justify-center p-4",children:t.jsx(N.Loader,{className:"h-5 w-5 animate-spin"})})]}),t.jsx(ao,{data:r==null?void 0:r.data,show:r==null?void 0:r.show,onClose:()=>{i({show:!1,data:null})}})]})}const ao=({data:e,show:s,onClose:n})=>t.jsx(c.Dialog,{open:s,onOpenChange:()=>n(),children:s&&t.jsx(ro,{data:e,show:s,onClose:n})}),ro=({data:e,show:s,onClose:n})=>{const[a,r]=f.useState("edit"),[i,o]=f.useState(""),[l,u]=f.useState({name:"",content:"",description:"",enabledByDefaultForNewPages:!1}),{data:d}=Oa(),{mutateAsync:h,isPending:m}=ca();f.useEffect(()=>{r("edit"),u({name:"",description:"",content:"",enabledByDefaultForNewPages:!1}),e&&u({name:e.name,description:e.description,content:e.content,enabledByDefaultForNewPages:e.enabledByDefaultForNewPages})},[e,s]),f.useEffect(()=>{const p=Es(l.content);o(p.isValid?JSON.stringify(p.parsed,null,2):"")},[l.content]);const v=async()=>{if(!l.name||!l.content){Q.toast.error("Please enter a name and content");return}const p={id:e?e.id:crypto.randomUUID(),name:l.name,description:l.description,content:l.content};e?await h([...(d||[]).map(y=>y.id===e.id?p:y)]):await h([...d||[],p]),n()};return t.jsxs(c.DialogContent,{className:"flex max-w-xl flex-col overflow-y-auto",children:[t.jsx(c.DialogHeader,{children:t.jsx(c.DialogTitle,{children:"Add New Shared JSON-LD Schema"})}),t.jsxs("div",{className:"flex max-h-[75vh] flex-col space-y-2 overflow-y-auto",children:[t.jsxs("div",{children:[t.jsx(c.Label,{htmlFor:"new-name",children:"Schema Name"}),t.jsx(c.Input,{id:"new-name",value:l.name,onChange:p=>u({...l,name:p.target.value}),placeholder:"e.g., Product Schema",className:"text-xs"})]}),t.jsxs("div",{children:[t.jsx(c.Label,{htmlFor:"new-description",children:"Description"}),t.jsx(c.Input,{id:"new-description",value:l.description||"",onChange:p=>u({...l,description:p.target.value}),placeholder:"Brief description of this schema"})]}),t.jsxs("div",{children:[t.jsx(c.Label,{htmlFor:"new-content",children:"JSON-LD Content"}),t.jsxs(c.Tabs,{value:a,onValueChange:r,className:"w-full",children:[t.jsxs("div",{className:"mb-2 flex w-full items-center justify-between",children:[t.jsxs(c.TabsList,{className:"w-max",children:[t.jsxs(c.TabsTrigger,{value:"edit",className:"flex items-center gap-1",children:[t.jsx(N.Code,{className:"h-4 w-4"}),t.jsx("span",{children:"Edit"})]}),t.jsxs(c.TabsTrigger,{value:"preview",className:"flex items-center gap-1",disabled:!i,children:[t.jsx(N.Eye,{className:"h-4 w-4"}),t.jsx("span",{children:"Preview"})]})]}),t.jsx("div",{className:"flex items-center gap-2",children:a==="edit"&&t.jsx(c.Button,{type:"button",variant:"outline",size:"sm",onClick:()=>u({...l,content:i}),disabled:!i,children:"Format"})})]}),t.jsxs(c.TabsContent,{value:"edit",children:[t.jsx(c.Textarea,{id:"new-content",value:l.content||"{}",onChange:p=>u({...l,content:p.target.value}),className:"font-mono text-sm",placeholder:"Enter JSON-LD markup...",rows:10}),!i&&l.content?t.jsx("p",{className:"pt-px text-xs text-red-500",children:"Invalid JSON-LD"}):t.jsx("p",{})]}),t.jsx(c.TabsContent,{value:"preview",children:t.jsx(c.Textarea,{id:"new-content",value:i||"{}",className:"bg-muted font-mono text-sm",placeholder:"{}",rows:10,readOnly:!0})})]})]}),e&&t.jsxs("div",{className:"flex items-center justify-between rounded-lg border border-blue-300 bg-blue-500/10 p-2",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-sm font-medium text-blue-900",children:"Apply to All Existing Pages"}),t.jsx("div",{className:"text-xs text-blue-700",children:"This will add this JSON-LD schema to all existing pages on your site a"})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(c.Button,{size:"sm",variant:"outline",onClick:()=>{},children:"Apply to all"}),t.jsx(c.Button,{size:"sm",variant:"ghost",onClick:()=>{},children:"Remove to all"})]})]}),t.jsxs("div",{className:"flex items-center justify-between pt-2",children:[t.jsxs("div",{className:"flex items-center space-x-2",children:[t.jsx(c.Switch,{id:"new-enabled",checked:l.enabledByDefaultForNewPages,onCheckedChange:p=>u({...l,enabledByDefaultForNewPages:p})}),t.jsxs(c.Label,{htmlFor:"new-enabled",children:[t.jsx("div",{children:"Enabled by default for new pages"}),t.jsx("div",{className:"text-xs font-light text-muted-foreground",children:"New pages will automatically include this schema"})]})]}),t.jsxs("div",{className:"flex gap-2",children:[t.jsx(c.Button,{disabled:m,variant:"outline",type:"button",size:"sm",onClick:()=>n(),children:"Cancel"}),t.jsx(c.Button,{disabled:m||!i,type:"button",size:"sm",onClick:v,children:m?t.jsxs(t.Fragment,{children:[t.jsx(N.Loader,{className:"h-4 w-4 animate-spin"})," ",e?"Updating":"Adding"]}):e?"Update Schema":"Add Schema"})]})]})]})]})},sn=({value:e,onChange:s,disabled:n=!1,readOnly:a=!1,placeholder:r="Enter JSON",rows:i=6,id:o="json-input",pageData:l={},handleFieldInsert:u,hasJsonLdForSelectedLang:d,copyJsonLDFromDefaultPage:h})=>{const[m,v]=f.useState("edit"),[p,y]=f.useState(null),[j,x]=f.useState(""),b=f.useRef(null),[E]=Ds(),P=o==="jsonLD"&&g.get(E,"features.sharedJsonLD",!1),U=o==="jsonLD"&&!d&&!!h;f.useEffect(()=>{e.trim()===""&&s("{}")},[e,s]);const L=k=>{if(a)return;const D=k.target.value;s(D)},F=k=>{if(k.key==="Tab"){k.preventDefault();const D=k.currentTarget,K=D.selectionStart,H=D.selectionEnd;if(K!==H){const Y=e.substring(K,H).split(`
|
|
4
|
+
`);if(k.shiftKey){const ie=Y.map(fe=>fe.startsWith(" ")?fe.substring(2):fe).join(`
|
|
5
|
+
`),je=e.substring(0,K)+ie+e.substring(H);s(je),setTimeout(()=>{D.selectionStart=K,D.selectionEnd=K+ie.length},0)}else{const ie=Y.map(fe=>` ${fe}`).join(`
|
|
6
|
+
`),je=e.substring(0,K)+ie+e.substring(H);s(je),setTimeout(()=>{D.selectionStart=K,D.selectionEnd=K+ie.length},0)}}else{const X=e.substring(0,K)+" "+e.substring(H);s(X),setTimeout(()=>{D.selectionStart=D.selectionEnd=K+2},0)}}};f.useEffect(()=>{const k=Es(e);if(k.isValid)if(y(null),k.parsed){const D=so(k.parsed,l);x(D)}else x("");else y(k.error),x("")},[e,l]);const re=()=>{const k=Es(e);if(k.isValid&&k.parsed){const D=to(k.parsed,k.placeholders);s(D)}},$=()=>{p!=null&&p.position&&b.current&&(b.current.focus(),b.current.setSelectionRange(p.position,p.position+1))};return t.jsx("div",{className:"space-y-2",children:t.jsxs(c.Tabs,{value:m,onValueChange:v,className:"w-full",children:[t.jsxs("div",{className:"mb-2 flex items-center justify-between",children:[t.jsxs(c.TabsList,{className:"w-max",children:[t.jsxs(c.TabsTrigger,{value:"edit",className:"flex items-center gap-1",children:[t.jsx(N.Code,{className:"h-4 w-4"}),t.jsx("span",{children:"Edit"})]}),t.jsxs(c.TabsTrigger,{value:"preview",className:"flex items-center gap-1",disabled:!e.trim()||p!==null||U,children:[t.jsx(N.Eye,{className:"h-4 w-4"}),t.jsx("span",{children:"Preview"})]}),P&&t.jsxs(c.TabsTrigger,{value:"shared",className:"flex items-center gap-1",disabled:!e.trim()||p!==null,children:[t.jsx(N.Share2,{className:"h-4 w-4"}),t.jsx("span",{children:"Shared"})]})]}),U?null:m==="edit"&&!a&&t.jsx("div",{className:"flex items-center gap-2",children:t.jsx(Ke,{dataType:"value",data:l??{},onSelect:k=>u&&u(k,o)})})]}),t.jsxs(c.TabsContent,{value:"edit",className:"relative mt-0",children:[!U&&m==="edit"&&t.jsx(Xe,{content:"Format JSON",side:"right",showTooltip:!n&&!p,children:t.jsx(c.Button,{type:"button",variant:"outline",size:"icon",onClick:re,className:"absolute right-1 top-1 h-6 w-6 p-1",disabled:!e.trim()||n||p!==null,children:t.jsx(N.FileCode2,{})})}),U?t.jsx("div",{className:"flex h-40 items-center justify-center rounded-md bg-black/20",children:t.jsxs("div",{className:"flex max-w-[400px] flex-col items-center gap-2 rounded-md bg-white p-4 shadow-lg",children:[t.jsx("div",{className:"max-w-xl text-center text-xs text-gray-500",children:"JSON-LD for is not added for selected language. JSON LD will be used from default language."}),t.jsxs(c.Button,{type:"button",variant:"default",size:"sm",onClick:h,children:[t.jsx(N.Plus,{}),"Copy & Edit from default language"]})]})}):t.jsx(c.Textarea,{ref:b,id:o,name:o,className:`rounded-md border border-input text-xs ${p?"border-red-500":""}`,onChange:L,onKeyDown:F,value:e,placeholder:r,rows:i,disabled:n,readOnly:a}),p&&t.jsxs(c.Alert,{variant:"destructive",className:"mt-2",children:[t.jsx(N.AlertTriangle,{className:"h-4 w-4"}),t.jsxs(c.AlertDescription,{className:"flex flex-col",children:[t.jsx("span",{className:"font-medium",children:"Invalid JSON"}),t.jsx("span",{className:"text-sm",children:p.message}),p.line&&p.column&&t.jsxs("span",{className:"text-sm",children:["Error at line ",p.line,", column ",p.column]}),t.jsx(c.Button,{type:"button",variant:"link",size:"sm",className:"mt-1 h-auto self-start p-0 text-sm",onClick:$,children:"Show position"})]})]})]}),t.jsxs(c.TabsContent,{value:"preview",className:"mt-0",children:[t.jsx(c.Textarea,{rows:i,value:j,readOnly:!0,className:"cursor-default bg-muted font-mono text-sm"}),t.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"This is how the JSON will look after placeholder substitution."})]}),P&&t.jsx(c.TabsContent,{value:"shared",className:"mt-0",children:t.jsx(no,{})})]})})},io=e=>{if(!e)return!0;try{return JSON.parse(e),!0}catch{return!1}},lo=(e,s)=>{const n=e.selectionStart||0,a=e.selectionEnd||0,r=e.value,i=r.substring(0,n),o=r.substring(a),l=`{{${s}}}`,u=i+""+l+o,d=n+0+l.length;return{value:u,newCursorPos:d}},Ga=()=>{const{t:e}=V.useTranslation(),[,s]=V.useSidebarActivePanel(),{data:n}=ke(),{data:a}=wn(),{data:r,isFetching:i}=Yl(),o=r==null?void 0:r.seo,l=f.useRef(null),[u,d]=f.useState("seo"),h=n==null?void 0:n.id,m=n==null?void 0:n.pageType,v=ya(m),{selectedLang:p,fallbackLang:y}=V.useLanguages(),j=p||y,[x,b]=f.useState(!1),[E,P]=f.useState(!1),[U,L]=f.useState(!1),[F,re]=f.useState(null),[$,k]=f.useState({keyword:"",title:"",description:"",cononicalUrl:"",noIndex:!1,noFollow:"",ogTitle:"",ogDescription:"",ogImage:"",ogImageId:"",searchTitle:"",searchDescription:"",jsonLD:"{}",metaOther:"{}",...o}),D=f.useRef({}),{mutate:K,isPending:H}=gn(),X=H||x||E,{hasPermission:Y}=V.usePermissions(),W=Y(Se.EDIT_SEO),[ie]=Ds(),je=g.get(ie,"features.canResetSeoToDefault",!1),fe=!p||$.jsonLD!=="{}";f.useEffect(()=>{if(!i&&o&&h){const C={keyword:"",title:"",description:"",cononicalUrl:"",noIndex:!1,noFollow:"",ogTitle:"",ogDescription:"",ogImage:"",ogImageId:"",searchTitle:"",searchDescription:"",jsonLD:"",metaOther:"",...o};k(C),D.current[j]=C}},[i,o,j,h]),f.useEffect(()=>{const C=q=>{const{fromLang:ne,toLang:z,switchHandler:J}=q.detail,ce=D.current[j];(ce?!g.isEqual(ce,$):!1)?(re({fromLang:ne,toLang:z,switchHandler:J}),L(!0)):J()};return window.addEventListener("seo-language-switch-check",C),()=>{window.removeEventListener("seo-language-switch-check",C)}},[h,$,j]);const Pe=async()=>{if(!(!v||!j))try{b(!0);const C=Ut(v,j),q={...$,keyword:g.get(C,"seo.keyword",""),title:g.get(C,"seo.title",""),description:g.get(C,"seo.description",""),cononicalUrl:g.get(C,"seo.canonicalUrl",""),noIndex:g.get(C,"seo.noIndex",!1),noFollow:g.get(C,"seo.noFollow",!1),ogTitle:g.get(C,"seo.ogTitle",""),ogDescription:g.get(C,"seo.ogDescription","")};k(q),Q.toast.success(e("SEO fields reset to defaults"))}catch(C){Q.toast.error(e("Failed to reset SEO fields")),console.error("Reset SEO error:",C)}finally{b(!1)}},w=async()=>{if(!(!v||!j))try{P(!0);const C=Ut(v,j),q={...$,jsonLD:g.get(C,"seo.jsonLD","")};k(q),Q.toast.success(e("JSON-LD reset to default"))}catch(C){Q.toast.error(e("Failed to reset JSON-LD")),console.error("Reset JSON-LD error:",C)}finally{P(!1)}},S=async()=>{if(!(!v||!j))try{b(!0);const C=Ut(v,j),q={...$,ogTitle:g.get(C,"seo.ogTitle",""),ogDescription:g.get(C,"seo.ogDescription",""),ogImage:g.get(C,"seo.ogImage",""),ogImageId:g.get(C,"seo.ogImageId",""),metaOther:g.get(C,"seo.metaOther","{}")};k(q),Q.toast.success(e("Meta Tag fields reset to defaults"))}catch(C){Q.toast.error(e("Failed to reset Meta Tag fields")),console.error("Reset Meta Tag error:",C)}finally{b(!1)}},I=async()=>{K({id:r==null?void 0:r.id,seo:$,primaryPage:h},{onSuccess:()=>{console.log("SEO & JSON-LD updated successfully",$),D.current[j]=$,Q.toast.success("SEO & JSON-LD updated successfully")}})},B=(C,q)=>{const ne=document.getElementById(q);if(ne){const{value:z,newCursorPos:J}=lo(ne,C);l.current={id:q,position:J},ne.tagName.toLowerCase()==="input"?(ne.value=z,k(A=>({...A,[ne.name]:z})),ne.focus(),ne.setSelectionRange(J,J),[0,10,50,100,200].forEach(A=>{setTimeout(()=>{const Z=document.getElementById(q);Z&&(Z.focus(),Z.setSelectionRange(J,J))},A)})):(k(me=>({...me,[ne.name]:z})),requestAnimationFrame(()=>{const me=document.getElementById(q);me&&(me.focus(),me.setSelectionRange(J,J),setTimeout(()=>{const A=document.getElementById(q);A&&(A.focus(),A.setSelectionRange(J,J))},50))}))}},R=C=>{const q={...$,[C.target.name]:C.target.name==="noIndex"||C.target.name==="noFollow"?C.target.checked:C.target.value};k(q)},O=C=>q=>{g.isEmpty(q.fieldValue)||R({target:{name:C,value:typeof q.fieldValue=="string"?q.fieldValue.replace(/^"(.*)"$/,"$1"):q.fieldValue}}),q.error&&Q.toast.error(t.jsxs("div",{children:[t.jsx("h2",{children:"Failed to generate:"}),t.jsx("p",{children:q.error})]}))},M=()=>{const C=g.get(n,"seo.jsonLD","{}");if((C==null?void 0:C.trim())==="{}"){Q.toast.error("Default page JSON-LD is empty");return}R({target:{name:"jsonLD",value:C}})};return t.jsxs("div",{className:"relative flex h-full flex-col","data-panel-id":"seo",children:[!W&&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 px-2 py-1 text-left text-sm",children:[t.jsxs("span",{children:[t.jsx("div",{className:"font-medium",children:r==null?void 0:r.name}),t.jsx("span",{className:"font-mono text-xs leading-tight text-gray-500",children:r==null?void 0:r.slug})]}),t.jsx(Sn,{variant:"outline",showAdd:!1})]}),t.jsx("form",{className:"space-y-8",children:t.jsxs(c.Tabs,{value:u,onValueChange:d,className:"w-full",children:[t.jsxs(c.TabsList,{className:"mb-4 grid w-full grid-cols-3",children:[t.jsx(c.TabsTrigger,{value:"seo",children:e("SEO")}),t.jsx(c.TabsTrigger,{value:"opengraph",children:e("Meta Tags")}),t.jsx(c.TabsTrigger,{value:"jsonld",children:e("JSON-LD")})]}),t.jsx("div",{className:u==="seo"?"":"sr-only",children: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:"keyword",children:e("Keyword")}),W&&t.jsx(Ke,{dataType:"value",data:a??{},onSelect:C=>B(C,"keyword")})]}),t.jsx(c.Input,{type:"text",id:"keyword",name:"keyword",value:$.keyword,onChange:R,disabled:X||!W,placeholder:e("Enter keyword"),readOnly:!W})]}),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(ut,{keyword:$.keyword,onComplete:O("title"),field:"title"}),W&&t.jsx(Ke,{dataType:"value",data:a??{},onSelect:C=>B(C,"title")})]})]}),t.jsx(c.Input,{type:"text",id:"title",name:"title",value:$.title,onChange:R,disabled:X||!W,placeholder:e("Enter SEO title"),readOnly:!W})]}),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(ut,{keyword:$.keyword,onComplete:O("description"),field:"description"}),W&&t.jsx(Ke,{data:a??{},onSelect:C=>B(C,"description")})]})]}),t.jsx(c.Textarea,{id:"description",name:"description",rows:5,value:$.description,onChange:R,disabled:X||!W,placeholder:e("Enter SEO description"),readOnly:!W})]}),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")}),W&&t.jsx(Ke,{dataType:"value",data:a??{},onSelect:C=>B(C,"canonicalUrl")})]}),t.jsx(c.Input,{type:"text",id:"canonicalUrl",name:"canonicalUrl",value:$.canonicalUrl,onChange:R,disabled:X||!W,placeholder:e("Enter Canonical URL"),readOnly:!W})]}),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:$.noIndex,onChange:R,disabled:X||!W,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:$.noFollow,onChange:R,disabled:X||!W,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.jsx("div",{className:u==="opengraph"?"":"sr-only",children:t.jsx("div",{className:"space-y-4",children: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(ut,{keyword:$.keyword,onComplete:O("ogTitle"),field:"ogTitle"}),W&&t.jsx(Ke,{dataType:"value",data:a??{},onSelect:C=>B(C,"ogTitle")})]})]}),t.jsx(c.Input,{type:"text",id:"ogTitle",name:"ogTitle",value:$.ogTitle,onChange:R,disabled:X||!W,placeholder:e("Enter OG title"),readOnly:!W})]}),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(ut,{keyword:$.keyword,onComplete:O("ogDescription"),field:"ogDescription"}),W&&t.jsx(Ke,{dataType:"value",data:a??{},onSelect:C=>B(C,"ogDescription")})]})]}),t.jsx(c.Textarea,{id:"ogDescription",name:"ogDescription",rows:5,value:$.ogDescription,onChange:R,disabled:X||!W,placeholder:e("Enter OG description"),readOnly:!W})]}),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:"ogImage",children:e("OG Image")}),W&&t.jsx(Ke,{dataType:"value",data:a??{},onSelect:C=>{k({...$,ogImage:`{{${C}}}`,ogImageId:""})}})]}),t.jsx(Ls,{assetId:$.ogImageId,assetUrl:$.ogImage,onChange:C=>{k({...$,ogImage:C.url,ogImageId:C.id})},disabled:X||!W,placeholder:e("Select OG image"),className:"mb-2"})]}),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:"metaOther",children:e("Meta Tags")}),t.jsx("div",{className:"flex items-center gap-2",children:t.jsx(ut,{keyword:$.keyword,onComplete:O("metaOther"),field:"metaOther"})})]}),t.jsx(sn,{id:"metaOther",value:$.metaOther,onChange:C=>{R({target:{name:"metaOther",value:C}})},placeholder:e("Enter Meta Tags JSON"),disabled:X||!W,readOnly:!W,pageData:a||{},rows:8,handleFieldInsert:B})]})]})]})})}),t.jsx("div",{className:u==="jsonld"?"":"sr-only",children:t.jsx("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:"jsonLD",children:e("JSON-LD")}),fe&&t.jsx("div",{className:"flex items-center gap-2",children:t.jsx(ut,{keyword:$.keyword,onComplete:O("jsonLD"),field:"jsonLD"})})]}),t.jsx("div",{className:"hidden",children:JSON.stringify(a)}),t.jsx(sn,{id:"jsonLD",value:$.jsonLD,onChange:C=>{R({target:{name:"jsonLD",value:C}})},placeholder:e("Enter JSON-LD"),disabled:X||!W,readOnly:!W,pageData:a||{},rows:12,handleFieldInsert:B,hasJsonLdForSelectedLang:fe,copyJsonLDFromDefaultPage:M})]})})})]})})]}),W&&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:[je?t.jsx(c.Button,{type:"button",variant:"ghost",size:"sm",onClick:()=>{u==="jsonld"?w():u==="opengraph"?S():Pe()},disabled:X||!W||!v,children:e(x?"Resetting...":`Reset to ${u==="jsonld"?"Default JSON-LD":u==="opengraph"?"Default Open Graph":"Default SEO"}`)}):t.jsx("div",{}),t.jsxs("div",{className:"flex items-center gap-4",children:[t.jsx(c.Button,{onClick:I,disabled:!io($==null?void 0:$.jsonLD)||(D.current[j]?g.isEqual(D.current[j],$):!1)||X||!W,children:e(H?"Saving...":"Save")}),t.jsx(c.Button,{variant:"link",className:"text-gray-500 hover:text-gray-700",onClick:()=>s("outline"),children:e("Cancel")})]})]}),t.jsx(Zl,{isOpen:U,onClose:()=>{L(!1),re(null)},onSave:async()=>{F&&(await I(),F.switchHandler(),L(!1),re(null))},onDiscard:()=>{if(F){const C=D.current[j];C&&k(C),F.switchHandler(),L(!1),re(null)}},isSaving:H,fromLanguage:(F==null?void 0:F.fromLang)||j,toLanguage:(F==null?void 0:F.toLang)||""})]})};Ga.displayName="SeoPanel";const Ra="seo",oo=({isActive:e,show:s})=>{const{data:n}=ke(),a=ya(n==null?void 0:n.pageType);return!g.has(a,"hasSlug")||!a.hasSlug?null:t.jsx(c.Button,{size:"icon",className:"my-1 p-0",onClick:s,variant:e?"default":"ghost",children:t.jsxs("svg",{stroke:"currentColor",fill:"none",style:{height:"20px",width:"20px"},strokeWidth:"2",viewBox:"0 0 24 24",strokeLinecap:"round",strokeLinejoin:"round",children:[t.jsx("path",{d:"M7 8h-3a1 1 0 0 0 -1 1v2a1 1 0 0 0 1 1h2a1 1 0 0 1 1 1v2a1 1 0 0 1 -1 1h-3"}),t.jsx("path",{d:"M14 16h-4v-8h4"}),t.jsx("path",{d:"M11 12h2"}),t.jsx("path",{d:"M17 8m0 1a1 1 0 0 1 1 -1h2a1 1 0 0 1 1 1v6a1 1 0 0 1 -1 1h-2a1 1 0 0 1 -1 -1z"})]})})},co={id:Ra,label:"SEO",panel:Ga,button:oo,position:"top",width:600,view:"modal"},Ua="user-info",uo=()=>{const{user:e,logout:s}=Fe(),n=Me("onLogout",g.noop);return e?t.jsxs(c.HoverCard,{children:[t.jsx(c.HoverCardTrigger,{asChild:!0,children:t.jsx(c.Button,{variant:"ghost",className:"text-sm font-medium",children:t.jsx(N.User,{className:"h-4 w-4"})})}),t.jsxs(c.HoverCardContent,{className:"w-auto space-y-2 p-4",children:[t.jsx("div",{className:"text-sm font-medium",children:e.name??e.email}),t.jsx("div",{className:"text-xs text-muted-foreground",children:e.email}),t.jsxs(c.AlertDialog,{children:[t.jsx(c.AlertDialogTrigger,{asChild:!0,children:t.jsx(c.Button,{variant:"outline",size:"sm",className:"w-full",children:"Logout"})}),t.jsxs(c.AlertDialogContent,{children:[t.jsxs(c.AlertDialogHeader,{children:[t.jsx(c.AlertDialogTitle,{children:"Are you sure you want to logout?"}),t.jsx(c.AlertDialogDescription,{children:"You will be redirected to the login page."})]}),t.jsxs(c.AlertDialogFooter,{children:[t.jsx(c.AlertDialogCancel,{children:"Cancel"}),t.jsx(c.AlertDialogAction,{onClick:()=>{s(),g.isFunction(n)&&n()},children:"Logout"})]})]})]})]})]}):null},ho={id:Ua,label:"User Info",button:uo,position:"bottom"},mo=()=>{V.registerChaiSidebarPanel(Ra,co),V.registerChaiSidebarPanel(Ba,Jl),V.registerChaiSidebarPanel(Ua,ho)};var ae={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 ae.context.id+(n?String.fromCharCode(96+n):"")+s}function Bt(e){ae.context=e}var Fa=!1,fo=(e,s)=>e===s,Ns=Symbol("solid-proxy"),qa=typeof Proxy=="function",En=Symbol("solid-track"),Cs={equals:fo},za=Ya,Je=1,Ts=2,Va={owned:null,cleanups:null,context:null,owner:null},Qs={},de=null,Ws=null,go=null,xe=null,Ie=null,He=null,Rs=0;function Ze(e,s){const n=xe,a=de,r=e.length===0,i=s===void 0?a:s,o=r?Va:{owned:null,cleanups:null,context:i?i.context:null,owner:i},l=r?e:()=>e(()=>Te(()=>zt(o)));de=o,xe=null;try{return Ve(l,!0)}finally{xe=n,de=a}}function ve(e,s){s=s?Object.assign({},Cs,s):Cs;const n={value:e,observers:null,observerSlots:null,comparator:s.equals||void 0},a=r=>(typeof r=="function"&&(r=r(n.value)),Ja(n,r));return[Wa.bind(n),a]}function $a(e,s,n){const a=Us(e,s,!0,Je);Lt(a)}function et(e,s,n){const a=Us(e,s,!1,Je);Lt(a)}function Nn(e,s,n){za=Ao;const a=Us(e,s,!1,Je);(!n||!n.render)&&(a.user=!0),He?He.push(a):Lt(a)}function Ne(e,s,n){n=n?Object.assign({},Cs,n):Cs;const a=Us(e,s,!0,0);return a.observers=null,a.observerSlots=null,a.comparator=n.equals||void 0,Lt(a),Wa.bind(a)}function xo(e){return e&&typeof e=="object"&&"then"in e}function po(e,s,n){let a,r,i;a=!0,r=e,i={};let o=null,l=Qs,u=null,d=!1,h="initialValue"in i,m=typeof a=="function"&&Ne(a);const v=new Set,[p,y]=(i.storage||ve)(i.initialValue),[j,x]=ve(void 0),[b,E]=ve(void 0,{equals:!1}),[P,U]=ve(h?"ready":"unresolved");ae.context&&(u=ae.getNextContextId(),i.ssrLoadFrom==="initial"?l=i.initialValue:ae.load&&ae.has(u)&&(l=ae.load(u)));function L(D,K,H,X){return o===D&&(o=null,X!==void 0&&(h=!0),(D===l||K===l)&&i.onHydrated&&queueMicrotask(()=>i.onHydrated(X,{value:K})),l=Qs,F(K,H)),K}function F(D,K){Ve(()=>{K===void 0&&y(()=>D),U(K!==void 0?"errored":h?"ready":"unresolved"),x(K);for(const H of v.keys())H.decrement();v.clear()},!1)}function re(){const D=No,K=p(),H=j();if(H!==void 0&&!o)throw H;return xe&&xe.user,K}function $(D=!0){if(D!==!1&&d)return;d=!1;const K=m?m():a;if(K==null||K===!1){L(o,Te(p));return}let H;const X=l!==Qs?l:Te(()=>{try{return r(K,{value:p(),refetching:D})}catch(Y){H=Y}});if(H!==void 0){L(o,void 0,js(H),K);return}else if(!xo(X))return L(o,X,void 0,K),X;return o=X,"v"in X?(X.s===1?L(o,X.v,void 0,K):L(o,void 0,js(X.v),K),X):(d=!0,queueMicrotask(()=>d=!1),Ve(()=>{U(h?"refreshing":"pending"),E()},!1),X.then(Y=>L(X,Y,void 0,K),Y=>L(X,void 0,js(Y),K)))}Object.defineProperties(re,{state:{get:()=>P()},error:{get:()=>j()},loading:{get(){const D=P();return D==="pending"||D==="refreshing"}},latest:{get(){if(!h)return re();const D=j();if(D&&!o)throw D;return p()}}});let k=de;return m?$a(()=>(k=de,$(!1))):$(!1),[re,{refetch:D=>Ha(k,()=>$(D)),mutate:y}]}function yo(e){return Ve(e,!1)}function Te(e){if(xe===null)return e();const s=xe;xe=null;try{return e()}finally{xe=s}}function vo(e,s,n){const a=Array.isArray(e);let r,i=n&&n.defer;return o=>{let l;if(a){l=Array(e.length);for(let d=0;d<e.length;d++)l[d]=e[d]()}else l=e();if(i)return i=!1,o;const u=Te(()=>s(l,r,o));return r=l,u}}function Ka(e){Nn(()=>Te(e))}function Pt(e){return de===null||(de.cleanups===null?de.cleanups=[e]:de.cleanups.push(e)),e}function Fn(){return de}function Ha(e,s){const n=de,a=xe;de=e,xe=null;try{return Ve(s,!0)}catch(r){Cn(r)}finally{de=n,xe=a}}function jo(e){const s=xe,n=de;return Promise.resolve().then(()=>{xe=s,de=n;let a;return Ve(e,!1),xe=de=null,a?a.done:void 0})}var[bo,Ou]=ve(!1);function So(){return[bo,jo]}function wo(e,s){const n=Symbol("context");return{id:n,Provider:ko(n),defaultValue:e}}function Eo(e){let s;return de&&de.context&&(s=de.context[e.id])!==void 0?s:e.defaultValue}function Qa(e){const s=Ne(e),n=Ne(()=>nn(s()));return n.toArray=()=>{const a=n();return Array.isArray(a)?a:a!=null?[a]:[]},n}var No;function Wa(){if(this.sources&&this.state)if(this.state===Je)Lt(this);else{const e=Ie;Ie=null,Ve(()=>ks(this),!1),Ie=e}if(xe){const e=this.observers?this.observers.length:0;xe.sources?(xe.sources.push(this),xe.sourceSlots.push(e)):(xe.sources=[this],xe.sourceSlots=[e]),this.observers?(this.observers.push(xe),this.observerSlots.push(xe.sources.length-1)):(this.observers=[xe],this.observerSlots=[xe.sources.length-1])}return this.value}function Ja(e,s,n){let a=e.value;return(!e.comparator||!e.comparator(a,s))&&(e.value=s,e.observers&&e.observers.length&&Ve(()=>{for(let r=0;r<e.observers.length;r+=1){const i=e.observers[r],o=Ws&&Ws.running;o&&Ws.disposed.has(i),(o?!i.tState:!i.state)&&(i.pure?Ie.push(i):He.push(i),i.observers&&Xa(i)),o||(i.state=Je)}if(Ie.length>1e6)throw Ie=[],new Error},!1)),s}function Lt(e){if(!e.fn)return;zt(e);const s=Rs;Co(e,e.value,s)}function Co(e,s,n){let a;const r=de,i=xe;xe=de=e;try{a=e.fn(s)}catch(o){return e.pure&&(e.state=Je,e.owned&&e.owned.forEach(zt),e.owned=null),e.updatedAt=n+1,Cn(o)}finally{xe=i,de=r}(!e.updatedAt||e.updatedAt<=n)&&(e.updatedAt!=null&&"observers"in e?Ja(e,a):e.value=a,e.updatedAt=n)}function Us(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:de,context:de?de.context:null,pure:n};return de===null||de!==Va&&(de.owned?de.owned.push(i):de.owned=[i]),i}function As(e){if(e.state===0)return;if(e.state===Ts)return ks(e);if(e.suspense&&Te(e.suspense.inFallback))return e.suspense.effects.push(e);const s=[e];for(;(e=e.owner)&&(!e.updatedAt||e.updatedAt<Rs);)e.state&&s.push(e);for(let n=s.length-1;n>=0;n--)if(e=s[n],e.state===Je)Lt(e);else if(e.state===Ts){const a=Ie;Ie=null,Ve(()=>ks(e,s[0]),!1),Ie=a}}function Ve(e,s){if(Ie)return e();let n=!1;s||(Ie=[]),He?n=!0:He=[],Rs++;try{const a=e();return To(n),a}catch(a){n||(He=null),Ie=null,Cn(a)}}function To(e){if(Ie&&(Ya(Ie),Ie=null),e)return;const s=He;He=null,s.length&&Ve(()=>za(s),!1)}function Ya(e){for(let s=0;s<e.length;s++)As(e[s])}function Ao(e){let s,n=0;for(s=0;s<e.length;s++){const a=e[s];a.user?e[n++]=a:As(a)}if(ae.context){if(ae.count){ae.effects||(ae.effects=[]),ae.effects.push(...e.slice(0,n));return}Bt()}for(ae.effects&&(ae.done||!ae.count)&&(e=[...ae.effects,...e],n+=ae.effects.length,delete ae.effects),s=0;s<n;s++)As(e[s])}function ks(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<Rs)&&As(a):r===Ts&&ks(a,s)}}}function Xa(e){for(let s=0;s<e.observers.length;s+=1){const n=e.observers[s];n.state||(n.state=Ts,n.pure?Ie.push(n):He.push(n),n.observers&&Xa(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(),o=n.observerSlots.pop();a<r.length&&(i.sourceSlots[o]=a,r[a]=i,n.observerSlots[a]=o)}}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=de){throw js(e)}function nn(e){if(typeof e=="function"&&!e.length)return nn(e());if(Array.isArray(e)){const s=[];for(let n=0;n<e.length;n++){const a=nn(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 et(()=>r=Te(()=>(de.context={...de.context,[e]:a.value},Qa(()=>a.children))),void 0),r}}var an=Symbol("fallback");function Ps(e){for(let s=0;s<e.length;s++)e[s]()}function Po(e,s,n={}){let a=[],r=[],i=[],o=0,l=s.length>1?[]:null;return Pt(()=>Ps(i)),()=>{let u=e()||[],d=u.length,h,m;return u[En],Te(()=>{let p,y,j,x,b,E,P,U,L;if(d===0)o!==0&&(Ps(i),i=[],a=[],r=[],o=0,l&&(l=[])),n.fallback&&(a=[an],r[0]=Ze(F=>(i[0]=F,n.fallback())),o=1);else if(o===0){for(r=new Array(d),m=0;m<d;m++)a[m]=u[m],r[m]=Ze(v);o=d}else{for(j=new Array(d),x=new Array(d),l&&(b=new Array(d)),E=0,P=Math.min(o,d);E<P&&a[E]===u[E];E++);for(P=o-1,U=d-1;P>=E&&U>=E&&a[P]===u[U];P--,U--)j[U]=r[P],x[U]=i[P],l&&(b[U]=l[P]);for(p=new Map,y=new Array(U+1),m=U;m>=E;m--)L=u[m],h=p.get(L),y[m]=h===void 0?-1:h,p.set(L,m);for(h=E;h<=P;h++)L=a[h],m=p.get(L),m!==void 0&&m!==-1?(j[m]=r[h],x[m]=i[h],l&&(b[m]=l[h]),m=y[m],p.set(L,m)):i[h]();for(m=E;m<d;m++)m in j?(r[m]=j[m],i[m]=x[m],l&&(l[m]=b[m],l[m](m))):r[m]=Ze(v);r=r.slice(0,o=d),a=u.slice(0)}return r});function v(p){if(i[m]=p,l){const[y,j]=ve(m);return l[m]=j,s(u[m],y)}return s(u[m])}}}function Io(e,s,n={}){let a=[],r=[],i=[],o=[],l=0,u;return Pt(()=>Ps(i)),()=>{const d=e()||[],h=d.length;return d[En],Te(()=>{if(h===0)return l!==0&&(Ps(i),i=[],a=[],r=[],l=0,o=[]),n.fallback&&(a=[an],r[0]=Ze(v=>(i[0]=v,n.fallback())),l=1),r;for(a[0]===an&&(i[0](),i=[],a=[],r=[],l=0),u=0;u<h;u++)u<a.length&&a[u]!==d[u]?o[u](()=>d[u]):u>=a.length&&(r[u]=Ze(m));for(;u<a.length;u++)i[u]();return l=o.length=i.length=h,a=d.slice(0),r=r.slice(0,l)});function m(v){i[u]=v;const[p,y]=ve(d[u]);return o[u]=y,s(p,u)}}}function Tn(e,s){return Te(()=>e(s||{}))}function xs(){return!0}var rn={get(e,s,n){return s===Ns?n:e.get(s)},has(e,s){return s===Ns?!0:e.has(s)},set:xs,deleteProperty:xs,getOwnPropertyDescriptor(e,s){return{configurable:!0,enumerable:!0,get(){return e.get(s)},set:xs,deleteProperty:xs}},ownKeys(e){return e.keys()}};function Js(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 An(...e){let s=!1;for(let o=0;o<e.length;o++){const l=e[o];s=s||!!l&&Ns in l,e[o]=typeof l=="function"?(s=!0,Ne(l)):l}if(qa&&s)return new Proxy({get(o){for(let l=e.length-1;l>=0;l--){const u=Js(e[l])[o];if(u!==void 0)return u}},has(o){for(let l=e.length-1;l>=0;l--)if(o in Js(e[l]))return!0;return!1},keys(){const o=[];for(let l=0;l<e.length;l++)o.push(...Object.keys(Js(e[l])));return[...new Set(o)]}},rn);const n={},a=Object.create(null);for(let o=e.length-1;o>=0;o--){const l=e[o];if(!l)continue;const u=Object.getOwnPropertyNames(l);for(let d=u.length-1;d>=0;d--){const h=u[d];if(h==="__proto__"||h==="constructor")continue;const m=Object.getOwnPropertyDescriptor(l,h);if(!a[h])a[h]=m.get?{enumerable:!0,configurable:!0,get:_o.bind(n[h]=[m.get.bind(l)])}:m.value!==void 0?m:void 0;else{const v=n[h];v&&(m.get?v.push(m.get.bind(l)):m.value!==void 0&&v.push(()=>m.value))}}}const r={},i=Object.keys(a);for(let o=i.length-1;o>=0;o--){const l=i[o],u=a[l];u&&u.get?Object.defineProperty(r,l,u):r[l]=u?u.value:void 0}return r}function Za(e,...s){if(qa&&Ns in e){const r=new Set(s.length>1?s.flat():s[0]),i=s.map(o=>new Proxy({get(l){return o.includes(l)?e[l]:void 0},has(l){return o.includes(l)&&l in e},keys(){return o.filter(l=>l in e)}},rn));return i.push(new Proxy({get(o){return r.has(o)?void 0:e[o]},has(o){return r.has(o)?!1:o in e},keys(){return Object.keys(e).filter(o=>!r.has(o))}},rn)),i}const n={},a=s.map(()=>({}));for(const r of Object.getOwnPropertyNames(e)){const i=Object.getOwnPropertyDescriptor(e,r),o=!i.get&&!i.set&&i.enumerable&&i.writable&&i.configurable;let l=!1,u=0;for(const d of s)d.includes(r)&&(l=!0,o?a[u][r]=i.value:Object.defineProperty(a[u],r,i)),++u;l||(o?n[r]=i.value:Object.defineProperty(n,r,i))}return[...a,n]}function er(e){let s,n;const a=r=>{const i=ae.context;if(i){const[l,u]=ve();ae.count||(ae.count=0),ae.count++,(n||(n=e())).then(d=>{!ae.done&&Bt(i),ae.count--,u(()=>d.default),Bt()}),s=l}else if(!s){const[l]=po(()=>(n||(n=e())).then(u=>u.default));s=l}let o;return Ne(()=>(o=s())?Te(()=>{if(!i||ae.done)return o(r);const l=ae.context;Bt(i);const u=o(r);return Bt(l),u}):"")};return a.preload=()=>n||((n=e()).then(r=>s=()=>r.default),n),a}var Lo=0;function Do(){return ae.context?ae.getNextContextId():`cl-${Lo++}`}var tr=e=>`Stale read from <${e}>.`;function Bo(e){const s="fallback"in e&&{fallback:()=>e.fallback};return Ne(Po(()=>e.each,e.children,s||void 0))}function Oo(e){const s="fallback"in e&&{fallback:()=>e.fallback};return Ne(Io(()=>e.each,e.children,s||void 0))}function Mo(e){const s=e.keyed,n=Ne(()=>e.when,void 0,void 0),a=s?n:Ne(n,void 0,{equals:(r,i)=>!r==!i});return Ne(()=>{const r=a();if(r){const i=e.children;return typeof i=="function"&&i.length>0?Te(()=>i(s?r:()=>{if(!Te(a))throw tr("Show");return n()})):i}return e.fallback},void 0,void 0)}function Go(e){const s=Qa(()=>e.children),n=Ne(()=>{const a=s(),r=Array.isArray(a)?a:[a];let i=()=>{};for(let o=0;o<r.length;o++){const l=o,u=r[o],d=i,h=Ne(()=>d()?void 0:u.when,void 0,void 0),m=u.keyed?h:Ne(h,void 0,{equals:(v,p)=>!v==!p});i=()=>d()||(m()?[l,h,u]:void 0)}return i});return Ne(()=>{const a=n()();if(!a)return e.fallback;const[r,i,o]=a,l=o.children;return typeof l=="function"&&l.length>0?Te(()=>l(o.keyed?i():()=>{var d;if(((d=Te(n)())==null?void 0:d[0])!==r)throw tr("Match");return i()})):l},void 0,void 0)}function Ro(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","noValidate","formNoValidate","isMap","noModule","playsInline",...Uo]),qo=new Set(["innerHTML","textContent","innerText","children"]),zo=Object.assign(Object.create(null),{className:"class",htmlFor:"for"}),Vo=Object.assign(Object.create(null),{class:"className",novalidate:{$:"noValidate",FORM:1},formnovalidate:{$:"formNoValidate",BUTTON:1,INPUT:1},ismap:{$:"isMap",IMG:1},nomodule:{$:"noModule",SCRIPT:1},playsinline:{$:"playsInline",VIDEO:1},readonly:{$:"readOnly",INPUT:1,TEXTAREA:1}});function $o(e,s){const n=Vo[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"},Wo=e=>Ne(()=>e());function Jo(e,s,n){let a=n.length,r=s.length,i=a,o=0,l=0,u=s[r-1].nextSibling,d=null;for(;o<r||l<i;){if(s[o]===n[l]){o++,l++;continue}for(;s[r-1]===n[i-1];)r--,i--;if(r===o){const h=i<a?l?n[l-1].nextSibling:n[i-l]:u;for(;l<i;)e.insertBefore(n[l++],h)}else if(i===l)for(;o<r;)(!d||!d.has(s[o]))&&s[o].remove(),o++;else if(s[o]===n[i-1]&&n[l]===s[r-1]){const h=s[--r].nextSibling;e.insertBefore(n[l++],s[o++].nextSibling),e.insertBefore(n[--i],h),s[r]=n[i]}else{if(!d){d=new Map;let m=l;for(;m<i;)d.set(n[m],m++)}const h=d.get(s[o]);if(h!=null)if(l<h&&h<i){let m=o,v=1,p;for(;++m<r&&m<i&&!((p=d.get(s[m]))==null||p!==h+v);)v++;if(v>h-l){const y=s[o];for(;l<h;)e.insertBefore(n[l++],y)}else e.replaceChild(n[l++],s[o++])}else o++;else s[o++].remove()}}}var Ft="_$DX_DELEGATE";function sr(e,s,n,a={}){let r;return Ze(i=>{r=i,s===document?e():_s(s,e(),s.firstChild?null:void 0,n)},a.owner),()=>{r(),s.textContent=""}}function Yo(e,s,n,a){let r;const i=()=>{const l=document.createElement("template");return l.innerHTML=e,l.content.firstChild},o=()=>(r||(r=i())).cloneNode(!0);return o.cloneNode=o,o}function nr(e,s=window.document){const n=s[Ft]||(s[Ft]=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,or))}}function Xo(e=window.document){if(e[Ft]){for(let s of e[Ft].keys())e.removeEventListener(s,or);delete e[Ft]}}function Is(e,s,n){ot(e)||(n==null?e.removeAttribute(s):e.setAttribute(s,n))}function Zo(e,s,n,a){ot(e)||(a==null?e.removeAttributeNS(s,n):e.setAttributeNS(s,n,a))}function ec(e,s,n){ot(e)||(n?e.setAttribute(s,""):e.removeAttribute(s))}function ar(e,s){ot(e)||(s==null?e.removeAttribute("class"):e.className=s)}function rr(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 tc(e,s,n={}){const a=Object.keys(s||{}),r=Object.keys(n);let i,o;for(i=0,o=r.length;i<o;i++){const l=r[i];!l||l==="undefined"||s[l]||(qn(e,l,!1),delete n[l])}for(i=0,o=a.length;i<o;i++){const l=a[i],u=!!s[l];!l||l==="undefined"||n[l]===u||!u||(qn(e,l,!0),n[l]=u)}return n}function sc(e,s,n){if(!s)return n?Is(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 ir(e,s={},n,a){const r={};return a||et(()=>r.children=Vt(e,s.children,r.children)),et(()=>typeof s.ref=="function"&&lr(s.ref,e)),et(()=>nc(e,s,n,!0,r,!0)),r}function lr(e,s,n){return Te(()=>e(s,n))}function _s(e,s,n,a){if(n!==void 0&&!a&&(a=[]),typeof s!="function")return Vt(e,s,a,n);et(r=>Vt(e,s(),r,n),a)}function nc(e,s,n,a,r={},i=!1){s||(s={});for(const o in r)if(!(o in s)){if(o==="children")continue;r[o]=zn(e,o,null,r[o],n,i,s)}for(const o in s){if(o==="children")continue;const l=s[o];r[o]=zn(e,o,l,r[o],n,i,s)}}function ac(e){let s,n;return!ot()||!(s=ae.registry.get(n=ic()))?e():(ae.completed&&ae.completed.add(s),ae.registry.delete(n),s)}function ot(e){return!!ae.context&&!ae.done&&(!e||e.isConnected)}function rc(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 zn(e,s,n,a,r,i,o){let l,u,d,h,m;if(s==="style")return sc(e,n,a);if(s==="classList")return tc(e,n,a);if(n===a)return a;if(s==="ref")i||n(e);else if(s.slice(0,3)==="on:"){const v=s.slice(3);a&&e.removeEventListener(v,a,typeof a!="function"&&a),n&&e.addEventListener(v,n,typeof n!="function"&&n)}else if(s.slice(0,10)==="oncapture:"){const v=s.slice(10);a&&e.removeEventListener(v,a,!0),n&&e.addEventListener(v,n,!0)}else if(s.slice(0,2)==="on"){const v=s.slice(2).toLowerCase(),p=Ko.has(v);if(!p&&a){const y=Array.isArray(a)?a[0]:a;e.removeEventListener(v,y)}(p||n)&&(rr(e,v,n,p),p&&nr([v]))}else if(s.slice(0,5)==="attr:")Is(e,s.slice(5),n);else if(s.slice(0,5)==="bool:")ec(e,s.slice(5),n);else if((m=s.slice(0,5)==="prop:")||(d=qo.has(s))||!r&&((h=$o(s,e.tagName))||(u=Fo.has(s)))||(l=e.nodeName.includes("-")||"is"in o)){if(m)s=s.slice(5),u=!0;else if(ot(e))return n;s==="class"||s==="className"?ar(e,n):l&&!u&&!d?e[rc(s)]=n:e[h||s]=n}else{const v=r&&s.indexOf(":")>-1&&Qo[s.split(":")[0]];v?Zo(e,v,s,n):Is(e,zo[s]||s,n)}return n}function or(e){if(ae.registry&&ae.events&&ae.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}),o=()=>{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},l=()=>{for(;o()&&(s=s._$host||s.parentNode||s.host););};if(Object.defineProperty(e,"currentTarget",{configurable:!0,get(){return s||document}}),ae.registry&&!ae.done&&(ae.done=_$HY.done=!0),e.composedPath){const u=e.composedPath();i(u[0]);for(let d=0;d<u.length-2&&(s=u[d],!!o());d++){if(s._$host){s=s._$host,l();break}if(s.parentNode===r)break}}else l();i(a)}function Vt(e,s,n,a,r){const i=ot(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 o=typeof s,l=a!==void 0;if(e=l&&n[0]&&n[0].parentNode||e,o==="string"||o==="number"){if(i||o==="number"&&(s=s.toString(),s===n))return n;if(l){let u=n[0];u&&u.nodeType===3?u.data!==s&&(u.data=s):u=document.createTextNode(s),n=dt(e,n,a,u)}else n!==""&&typeof n=="string"?n=e.firstChild.data=s:n=e.textContent=s}else if(s==null||o==="boolean"){if(i)return n;n=dt(e,n,a)}else{if(o==="function")return et(()=>{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(ln(u,s,n,r))return et(()=>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=dt(e,n,a),l)return n}else d?n.length===0?Vn(e,u,a):Jo(e,n,u):(n&&dt(e),Vn(e,u));n=u}else if(s.nodeType){if(i&&s.parentNode)return n=l?[s]:s;if(Array.isArray(n)){if(l)return n=dt(e,n,a,s);dt(e,n,null,s)}else n==null||n===""||!e.firstChild?e.appendChild(s):e.replaceChild(s,e.firstChild);n=s}}return n}function ln(e,s,n,a){let r=!1;for(let i=0,o=s.length;i<o;i++){let l=s[i],u=n&&n[e.length],d;if(!(l==null||l===!0||l===!1))if((d=typeof l)=="object"&&l.nodeType)e.push(l);else if(Array.isArray(l))r=ln(e,l,u)||r;else if(d==="function")if(a){for(;typeof l=="function";)l=l();r=ln(e,Array.isArray(l)?l:[l],Array.isArray(u)?u:[u])||r}else e.push(l),r=!0;else{const h=String(l);u&&u.nodeType===3&&u.data===h?e.push(u):e.push(document.createTextNode(h))}}return r}function Vn(e,s,n=null){for(let a=0,r=s.length;a<r;a++)e.insertBefore(s[a],n)}function dt(e,s,n,a){if(n===void 0)return e.textContent="";const r=a||document.createTextNode("");if(s.length){let i=!1;for(let o=s.length-1;o>=0;o--){const l=s[o];if(r!==l){const u=l.parentNode===e;!i&&!o?u?e.replaceChild(r,l):e.insertBefore(r,n):u&&l.remove()}else i=!0}}else e.insertBefore(r,n);return[r]}function ic(){return ae.getNextContextId()}var lc="http://www.w3.org/2000/svg";function cr(e,s=!1){return s?document.createElementNS(lc,e):document.createElement(e)}function oc(e){const{useShadow:s}=e,n=document.createTextNode(""),a=()=>e.mount||document.body,r=Fn();let i,o=!!ae.context;return Nn(()=>{o&&(Fn().user=o=!1),i||(i=Ha(r,()=>Ne(()=>e.children)));const l=a();if(l instanceof HTMLHeadElement){const[u,d]=ve(!1),h=()=>d(!0);Ze(m=>_s(l,()=>u()?m():i(),null)),Pt(h)}else{const u=cr(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}),_s(d,i),l.appendChild(u),e.ref&&e.ref(u),Pt(()=>l.removeChild(u))}},void 0,{render:!o}),n}function cc(e,s){const n=Ne(e);return Ne(()=>{const a=n();switch(typeof a){case"function":return Te(()=>a(s));case"string":const r=Ho.has(a),i=ae.context?ac():cr(a,r);return ir(i,s,r),i}})}function uc(e){const[,s]=Za(e,["component"]);return cc(()=>e.component,s)}var dc=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()}},ur=class{constructor(e){this.generateIdentifier=e,this.kv=new dc}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)}},hc=class extends ur{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 mc(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 fc(e,s){const n=mc(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 It(e,s){Object.entries(e).forEach(([n,a])=>s(a,n))}function bs(e,s){return e.indexOf(s)!==-1}function $n(e,s){for(let n=0;n<e.length;n++){const a=e[n];if(s(a))return a}}var gc=class{constructor(){this.transfomers={}}register(e){this.transfomers[e.name]=e}findApplicable(e){return fc(this.transfomers,s=>s.isApplicable(e))}findByName(e){return this.transfomers[e]}},xc=e=>Object.prototype.toString.call(e).slice(8,-1),dr=e=>typeof e>"u",pc=e=>e===null,$t=e=>typeof e!="object"||e===null||e===Object.prototype?!1:Object.getPrototypeOf(e)===null?!0:Object.getPrototypeOf(e)===Object.prototype,on=e=>$t(e)&&Object.keys(e).length===0,tt=e=>Array.isArray(e),yc=e=>typeof e=="string",vc=e=>typeof e=="number"&&!isNaN(e),jc=e=>typeof e=="boolean",bc=e=>e instanceof RegExp,Kt=e=>e instanceof Map,Ht=e=>e instanceof Set,hr=e=>xc(e)==="Symbol",Sc=e=>e instanceof Date&&!isNaN(e.valueOf()),wc=e=>e instanceof Error,Kn=e=>typeof e=="number"&&isNaN(e),Ec=e=>jc(e)||pc(e)||dr(e)||vc(e)||yc(e)||hr(e),Nc=e=>typeof e=="bigint",Cc=e=>e===1/0||e===-1/0,Tc=e=>ArrayBuffer.isView(e)&&!(e instanceof DataView),Ac=e=>e instanceof URL,mr=e=>e.replace(/\./g,"\\."),Ys=e=>e.map(String).map(mr).join("."),qt=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 fr=[qe(dr,"undefined",()=>null,()=>{}),qe(Nc,"bigint",e=>e.toString(),e=>typeof BigInt<"u"?BigInt(e):e),qe(Sc,"Date",e=>e.toISOString(),e=>new Date(e)),qe(wc,"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(bc,"regexp",e=>""+e,e=>{const s=e.slice(1,e.lastIndexOf("/")),n=e.slice(e.lastIndexOf("/")+1);return new RegExp(s,n)}),qe(Ht,"set",e=>[...e.values()],e=>new Set(e)),qe(Kt,"map",e=>[...e.entries()],e=>new Map(e)),qe(e=>Kn(e)||Cc(e),"number",e=>Kn(e)?"NaN":e>0?"Infinity":"-Infinity",Number),qe(e=>e===0&&1/e===-1/0,"number",()=>"-0",Number),qe(Ac,"URL",e=>e.toString(),e=>new URL(e))];function Fs(e,s,n,a){return{isApplicable:e,annotation:s,transform:n,untransform:a}}var gr=Fs((e,s)=>hr(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}),kc=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,Uint8ClampedArray].reduce((e,s)=>(e[s.name]=s,e),{}),xr=Fs(Tc,e=>["typed-array",e.constructor.name],e=>[...e],(e,s)=>{const n=kc[s[1]];if(!n)throw new Error("Trying to deserialize unknown typed array");return new n(e)});function pr(e,s){return e!=null&&e.constructor?!!s.classRegistry.getIdentifier(e.constructor):!1}var yr=Fs(pr,(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 '${s[1]}' - check https://github.com/blitz-js/superjson/issues/116#issuecomment-773996564`);return Object.assign(Object.create(a.prototype),e)}),vr=Fs((e,s)=>!!s.customTransformerRegistry.findApplicable(e),(e,s)=>["custom",s.customTransformerRegistry.findApplicable(e).name],(e,s)=>s.customTransformerRegistry.findApplicable(e).serialize(e),(e,s,n)=>{const a=n.customTransformerRegistry.findByName(s[1]);if(!a)throw new Error("Trying to deserialize unknown custom value");return a.deserialize(e)}),Pc=[yr,gr,vr,xr],Hn=(e,s)=>{const n=$n(Pc,r=>r.isApplicable(e,s));if(n)return{value:n.transform(e,s),type:n.annotation(e,s)};const a=$n(fr,r=>r.isApplicable(e,s));if(a)return{value:a.transform(e,s),type:a.annotation}},jr={};fr.forEach(e=>{jr[e.annotation]=e});var Ic=(e,s,n)=>{if(tt(s))switch(s[0]){case"symbol":return gr.untransform(e,s,n);case"class":return yr.untransform(e,s,n);case"custom":return vr.untransform(e,s,n);case"typed-array":return xr.untransform(e,s,n);default:throw new Error("Unknown transformation: "+s)}else{const a=jr[s];if(!a)throw new Error("Unknown transformation: "+s);return a.untransform(e,n)}},mt=(e,s)=>{if(s>e.size)throw new Error("index out of bounds");const n=e.keys();for(;s>0;)n.next(),s--;return n.next().value};function br(e){if(bs(e,"__proto__"))throw new Error("__proto__ is not allowed as a property");if(bs(e,"prototype"))throw new Error("prototype is not allowed as a property");if(bs(e,"constructor"))throw new Error("constructor is not allowed as a property")}var _c=(e,s)=>{br(s);for(let n=0;n<s.length;n++){const a=s[n];if(Ht(e))e=mt(e,+a);else if(Kt(e)){const r=+a,i=+s[++n]==0?"key":"value",o=mt(e,r);switch(i){case"key":e=o;break;case"value":e=e.get(o);break}}else e=e[a]}return e},cn=(e,s,n)=>{if(br(s),s.length===0)return n(e);let a=e;for(let i=0;i<s.length-1;i++){const o=s[i];if(tt(a)){const l=+o;a=a[l]}else if($t(a))a=a[o];else if(Ht(a)){const l=+o;a=mt(a,l)}else if(Kt(a)){if(i===s.length-2)break;const u=+o,d=+s[++i]==0?"key":"value",h=mt(a,u);switch(d){case"key":a=h;break;case"value":a=a.get(h);break}}}const r=s[s.length-1];if(tt(a)?a[+r]=n(a[+r]):$t(a)&&(a[r]=n(a[r])),Ht(a)){const i=mt(a,+r),o=n(i);i!==o&&(a.delete(i),a.add(o))}if(Kt(a)){const i=+s[s.length-2],o=mt(a,i);switch(+r==0?"key":"value"){case"key":{const u=n(o);a.set(u,a.get(o)),u!==o&&a.delete(o);break}case"value":{a.set(o,n(a.get(o)));break}}}return e};function un(e,s,n=[]){if(!e)return;if(!tt(e)){It(e,(i,o)=>un(i,s,[...n,...qt(o)]));return}const[a,r]=e;r&&It(r,(i,o)=>{un(i,s,[...n,...qt(o)])}),s(a,n)}function Lc(e,s,n){return un(s,(a,r)=>{e=cn(e,r,i=>Ic(i,a,n))}),e}function Dc(e,s){function n(a,r){const i=_c(e,qt(r));a.map(qt).forEach(o=>{e=cn(e,o,()=>i)})}if(tt(s)){const[a,r]=s;a.forEach(i=>{e=cn(e,qt(i),()=>e)}),r&&It(r,n)}else It(s,n);return e}var Bc=(e,s)=>$t(e)||tt(e)||Kt(e)||Ht(e)||pr(e,s);function Oc(e,s,n){const a=n.get(e);a?a.push(s):n.set(e,[s])}function Mc(e,s){const n={};let a;return e.forEach(r=>{if(r.length<=1)return;s||(r=r.map(l=>l.map(String)).sort((l,u)=>l.length-u.length));const[i,...o]=r;i.length===0?a=o.map(Ys):n[Ys(i)]=o.map(Ys)}),a?on(n)?[a]:[a,n]:on(n)?void 0:n}var Sr=(e,s,n,a,r=[],i=[],o=new Map)=>{const l=Ec(e);if(!l){Oc(e,r,s);const p=o.get(e);if(p)return a?{transformedValue:null}:p}if(!Bc(e,n)){const p=Hn(e,n),y=p?{transformedValue:p.value,annotations:[p.type]}:{transformedValue:e};return l||o.set(e,y),y}if(bs(i,e))return{transformedValue:null};const u=Hn(e,n),d=(u==null?void 0:u.value)??e,h=tt(d)?[]:{},m={};It(d,(p,y)=>{if(y==="__proto__"||y==="constructor"||y==="prototype")throw new Error(`Detected property ${y}. This is a prototype pollution risk, please remove it from your object.`);const j=Sr(p,s,n,a,[...r,y],[...i,e],o);h[y]=j.transformedValue,tt(j.annotations)?m[y]=j.annotations:$t(j.annotations)&&It(j.annotations,(x,b)=>{m[mr(y)+"."+b]=x})});const v=on(m)?{transformedValue:h,annotations:u?[u.type]:void 0}:{transformedValue:h,annotations:u?[u.type,m]:m};return l||o.set(e,v),v};function wr(e){return Object.prototype.toString.call(e).slice(8,-1)}function Qn(e){return wr(e)==="Array"}function Gc(e){if(wr(e)!=="Object")return!1;const s=Object.getPrototypeOf(e);return!!s&&s.constructor===Object&&s===Object.prototype}function Rc(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 dn(e,s={}){if(Qn(e))return e.map(r=>dn(r,s));if(!Gc(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 o=e[i],l=dn(o,s);return Rc(r,i,l,e,s.nonenumerable),r},{})}var pe=class{constructor({dedupe:e=!1}={}){this.classRegistry=new hc,this.symbolRegistry=new ur(s=>s.description??""),this.customTransformerRegistry=new gc,this.allowedErrorProps=[],this.dedupe=e}serialize(e){const s=new Map,n=Sr(e,s,this,this.dedupe),a={json:n.transformedValue};n.annotations&&(a.meta={...a.meta,values:n.annotations});const r=Mc(s,this.dedupe);return r&&(a.meta={...a.meta,referentialEqualities:r}),a}deserialize(e){const{json:s,meta:n}=e;let a=dn(s);return n!=null&&n.values&&(a=Lc(a,n.values,this)),n!=null&&n.referentialEqualities&&(a=Dc(a,n.referentialEqualities)),a}stringify(e){return JSON.stringify(this.serialize(e))}parse(e){return this.deserialize(JSON.parse(e))}registerClass(e,s){this.classRegistry.register(e,s)}registerSymbol(e,s){this.symbolRegistry.register(e,s)}registerCustom(e,s){this.customTransformerRegistry.register({name:s,...e})}allowErrorProps(...e){this.allowedErrorProps.push(...e)}};pe.defaultInstance=new pe;pe.serialize=pe.defaultInstance.serialize.bind(pe.defaultInstance);pe.deserialize=pe.defaultInstance.deserialize.bind(pe.defaultInstance);pe.stringify=pe.defaultInstance.stringify.bind(pe.defaultInstance);pe.parse=pe.defaultInstance.parse.bind(pe.defaultInstance);pe.registerClass=pe.defaultInstance.registerClass.bind(pe.defaultInstance);pe.registerSymbol=pe.defaultInstance.registerSymbol.bind(pe.defaultInstance);pe.registerCustom=pe.defaultInstance.registerCustom.bind(pe.defaultInstance);pe.allowErrorProps=pe.defaultInstance.allowErrorProps.bind(pe.defaultInstance);var Er=pe.serialize,Uc=pe.stringify;function Fc(e){return e.state.fetchStatus==="fetching"?"fetching":e.getObserversCount()?e.state.fetchStatus==="paused"?"paused":e.isStale()?"stale":"fresh":"inactive"}function qc(e,s){return`${e}${s.charAt(0).toUpperCase()+s.slice(1)}`}function zc({queryState:e,observerCount:s,isStale:n}){return e.fetchStatus==="fetching"?"blue":s?e.fetchStatus==="paused"?"purple":n?"yellow":"green":"gray"}function Vc({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 Kc=(e,s=!1)=>{const{json:n}=Er(e);return JSON.stringify(n,null,s?2:void 0)},ps=e=>e.state.fetchStatus!=="idle"?0:e.getObserversCount()?e.isStale()?2:1:3,Hc=(e,s)=>e.queryHash.localeCompare(s.queryHash),Nr=(e,s)=>e.state.dataUpdatedAt<s.state.dataUpdatedAt?1:-1,Qc=(e,s)=>ps(e)===ps(s)?Nr(e,s):ps(e)>ps(s)?1:-1,Wc={status:Qc,"query hash":Hc,"last updated":Nr},ys=e=>e.state.isPaused?0:e.state.status==="error"?2:e.state.status==="pending"?1:3,Cr=(e,s)=>e.state.submittedAt<s.state.submittedAt?1:-1,Jc=(e,s)=>ys(e)===ys(s)?Cr(e,s):ys(e)>ys(s)?1:-1,Yc={status:Jc,"last updated":Cr},Xc=e=>e*parseFloat(getComputedStyle(document.documentElement).fontSize),Zc=()=>{const[e,s]=ve("dark");return Ka(()=>{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),Pt(()=>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},Mt=(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,Mt(n.get(a),r)),n}if(e instanceof Set){const n=Mt(Array.from(e),s);return new Set(n)}if(Array.isArray(e)){const n=[...e];if(s.length===1)return n.filter((i,o)=>o.toString()!==s[0]);const[a,...r]=s;return n[a]=Mt(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]=Mt(n[a],r),n}return e},Tr=(e,s)=>{if(!e||document.querySelector("#_goober")||(s==null?void 0:s.querySelector("#_goober")))return;const a=document.createElement("style"),r=document.createTextNode("");a.appendChild(r),a.id="_goober",a.setAttribute("nonce",e),s?s.appendChild(a):document.head.appendChild(a)},ft,Qt,Wt,Jt,rt,Yt,gt,xt,pt,yt,vt,Xt,jt,Zt,ea,eu=(ea=class{constructor(e){ge(this,ft);ge(this,Qt);ge(this,Wt);ge(this,Jt);ge(this,rt,!1);ge(this,Yt);ge(this,gt);ge(this,xt);ge(this,pt);ge(this,yt);ge(this,vt);ge(this,Xt);ge(this,jt);ge(this,Zt);const{client:s,queryFlavor:n,version:a,onlineManager:r,buttonPosition:i,position:o,initialIsOpen:l,errorTypes:u,styleNonce:d,shadowDOMTarget:h,hideDisabledQueries:m}=e;he(this,ft,ve(s)),he(this,Wt,n),he(this,Jt,a),he(this,Qt,r),he(this,Yt,d),he(this,gt,h),he(this,xt,ve(i)),he(this,pt,ve(o)),he(this,yt,ve(l)),he(this,vt,ve(u)),he(this,Xt,ve(m))}setButtonPosition(e){te(this,xt)[1](e)}setPosition(e){te(this,pt)[1](e)}setInitialIsOpen(e){te(this,yt)[1](e)}setErrorTypes(e){te(this,vt)[1](e)}setClient(e){te(this,ft)[1](e)}mount(e){if(te(this,rt))throw new Error("Devtools is already mounted");const s=sr(()=>{const n=this,[a]=te(this,xt),[r]=te(this,pt),[i]=te(this,yt),[o]=te(this,vt),[l]=te(this,Xt),[u]=te(this,ft);let d;return te(this,jt)?d=te(this,jt):(d=er(()=>Promise.resolve().then(()=>require("./NCMVHL6D-B6lv7Umq.cjs"))),he(this,jt,d)),Tr(te(this,Yt),te(this,gt)),Tn(d,An({get queryFlavor(){return te(n,Wt)},get version(){return te(n,Jt)},get onlineManager(){return te(n,Qt)},get shadowDOMTarget(){return te(n,gt)}},{get client(){return u()},get buttonPosition(){return a()},get position(){return r()},get initialIsOpen(){return i()},get errorTypes(){return o()},get hideDisabledQueries(){return l()}}))},e);he(this,rt,!0),he(this,Zt,s)}unmount(){var e;if(!te(this,rt))throw new Error("Devtools is not mounted");(e=te(this,Zt))==null||e.call(this),he(this,rt,!1)}},ft=new WeakMap,Qt=new WeakMap,Wt=new WeakMap,Jt=new WeakMap,rt=new WeakMap,Yt=new WeakMap,gt=new WeakMap,xt=new WeakMap,pt=new WeakMap,yt=new WeakMap,vt=new WeakMap,Xt=new WeakMap,jt=new WeakMap,Zt=new WeakMap,ea),bt,es,ts,ss,it,ns,St,wt,Et,Nt,Ct,as,Tt,At,rs,ta,tu=(ta=class{constructor(e){ge(this,bt);ge(this,es);ge(this,ts);ge(this,ss);ge(this,it,!1);ge(this,ns);ge(this,St);ge(this,wt);ge(this,Et);ge(this,Nt);ge(this,Ct);ge(this,as);ge(this,Tt);ge(this,At);ge(this,rs);const{client:s,queryFlavor:n,version:a,onlineManager:r,buttonPosition:i,position:o,initialIsOpen:l,errorTypes:u,styleNonce:d,shadowDOMTarget:h,onClose:m,hideDisabledQueries:v}=e;he(this,bt,ve(s)),he(this,ts,n),he(this,ss,a),he(this,es,r),he(this,ns,d),he(this,St,h),he(this,wt,ve(i)),he(this,Et,ve(o)),he(this,Nt,ve(l)),he(this,Ct,ve(u)),he(this,as,ve(v)),he(this,Tt,ve(m))}setButtonPosition(e){te(this,wt)[1](e)}setPosition(e){te(this,Et)[1](e)}setInitialIsOpen(e){te(this,Nt)[1](e)}setErrorTypes(e){te(this,Ct)[1](e)}setClient(e){te(this,bt)[1](e)}setOnClose(e){te(this,Tt)[1](()=>e)}mount(e){if(te(this,it))throw new Error("Devtools is already mounted");const s=sr(()=>{const n=this,[a]=te(this,wt),[r]=te(this,Et),[i]=te(this,Nt),[o]=te(this,Ct),[l]=te(this,as),[u]=te(this,bt),[d]=te(this,Tt);let h;return te(this,At)?h=te(this,At):(h=er(()=>Promise.resolve().then(()=>require("./2AITGKQY-DpAgk_u8.cjs"))),he(this,At,h)),Tr(te(this,ns),te(this,St)),Tn(h,An({get queryFlavor(){return te(n,ts)},get version(){return te(n,ss)},get onlineManager(){return te(n,es)},get shadowDOMTarget(){return te(n,St)}},{get client(){return u()},get buttonPosition(){return a()},get position(){return r()},get initialIsOpen(){return i()},get errorTypes(){return o()},get hideDisabledQueries(){return l()},get onClose(){return d()}}))},e);he(this,it,!0),he(this,rs,s)}unmount(){var e;if(!te(this,it))throw new Error("Devtools is not mounted");(e=te(this,rs))==null||e.call(this),he(this,it,!1)}},bt=new WeakMap,es=new WeakMap,ts=new WeakMap,ss=new WeakMap,it=new WeakMap,ns=new WeakMap,St=new WeakMap,wt=new WeakMap,Et=new WeakMap,Nt=new WeakMap,Ct=new WeakMap,as=new WeakMap,Tt=new WeakMap,At=new WeakMap,rs=new WeakMap,ta);function su(e){const s=G.useQueryClient(e.client),n=be.useRef(null),{buttonPosition:a,position:r,initialIsOpen:i,errorTypes:o,styleNonce:l,shadowDOMTarget:u,hideDisabledQueries:d}=e,[h]=be.useState(new eu({client:s,queryFlavor:"React Query",version:"5",onlineManager:G.onlineManager,buttonPosition:a,position:r,initialIsOpen:i,errorTypes:o,styleNonce:l,shadowDOMTarget:u,hideDisabledQueries:d}));return be.useEffect(()=>{h.setClient(s)},[s,h]),be.useEffect(()=>{a&&h.setButtonPosition(a)},[a,h]),be.useEffect(()=>{r&&h.setPosition(r)},[r,h]),be.useEffect(()=>{h.setInitialIsOpen(i||!1)},[i,h]),be.useEffect(()=>{h.setErrorTypes(o||[])},[o,h]),be.useEffect(()=>(n.current&&h.mount(n.current),()=>{h.unmount()}),[h]),t.jsx("div",{dir:"ltr",className:"tsqd-parent-container",ref:n})}function nu(e){const s=G.useQueryClient(e.client),n=be.useRef(null),{errorTypes:a,styleNonce:r,shadowDOMTarget:i,hideDisabledQueries:o}=e,[l]=be.useState(new tu({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,hideDisabledQueries:o}));return be.useEffect(()=>{l.setClient(s)},[s,l]),be.useEffect(()=>{l.setOnClose(e.onClose??(()=>{}))},[e.onClose,l]),be.useEffect(()=>{l.setErrorTypes(a||[])},[a,l]),be.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 Wn=process.env.NODE_ENV!=="development"?function(){return null}:su;process.env.NODE_ENV;const au=()=>{V.registerChaiFeatureFlag("dynamic-page-selector",{description:"Dynamic page selector"}),V.registerChaiFeatureFlag("enable-add-page-dropdown",{description:"Enable add page dropdown"}),V.registerChaiFeatureFlag("enable-page-revisions-compare",{description:"Page revisions compare"})},ru=()=>{const e=oe(),s=se();return G.useQuery({queryKey:[_.GET_COLLECTIONS],initialData:[],queryFn:async()=>s(e,{action:_.GET_COLLECTIONS})})},iu=()=>{const{data:e}=ke(),{data:s}=Qe(),{data:n}=$e(),a=oe(),r=se(),i=f.useMemo(()=>(n==null?void 0:n.fallbackLang)||"en",[n==null?void 0:n.fallbackLang]);return G.useMutation({mutationFn:async({block:o})=>r(a,{action:_.GET_BLOCK_ASYNC_PROPS,data:{block:o,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}}})})},Ar=()=>{const e=jn();return f.useCallback(({pageId:s})=>{e(s)},[e])},Jn={},Ss=(e,s)=>{g.has(Jn,e)&&console.warn(`Site setting ${e} already registered. Overriding...`),g.set(Jn,e,{id:e,...s})},lu=f.createContext(null),Xs={didCatch:!1,error:null};class ou extends f.Component{constructor(s){super(s),this.resetErrorBoundary=this.resetErrorBoundary.bind(this),this.state=Xs}static getDerivedStateFromError(s){return{didCatch:!0,error:s}}resetErrorBoundary(){const{error:s}=this.state;if(s!==null){for(var n,a,r=arguments.length,i=new Array(r),o=0;o<r;o++)i[o]=arguments[o];(n=(a=this.props).onReset)===null||n===void 0||n.call(a,{args:i,reason:"imperative-api"}),this.setState(Xs)}}componentDidCatch(s,n){var a,r;(a=(r=this.props).onError)===null||a===void 0||a.call(r,s,n)}componentDidUpdate(s,n){const{didCatch:a}=this.state,{resetKeys:r}=this.props;if(a&&n.error!==null&&cu(s.resetKeys,r)){var i,o;(i=(o=this.props).onReset)===null||i===void 0||i.call(o,{next:r,prev:s.resetKeys,reason:"keys"}),this.setState(Xs)}}render(){const{children:s,fallbackRender:n,FallbackComponent:a,fallback:r}=this.props,{didCatch:i,error:o}=this.state;let l=s;if(i){const u={error:o,resetErrorBoundary:this.resetErrorBoundary};if(typeof n=="function")l=n(u);else if(a)l=f.createElement(a,u);else if(r!==void 0)l=r;else throw o}return f.createElement(lu.Provider,{value:{didCatch:i,error:o,resetErrorBoundary:this.resetErrorBoundary}},l)}}function cu(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[];return e.length!==s.length||e.some((n,a)=>!Object.is(n,s[a]))}const uu=()=>{const e=is(),s=G.useQueryClient(),n=se();return G.useMutation({mutationFn:async a=>{const r=a.map(async o=>n(e,{action:_.UPLOAD_ASSET,data:o}));return await Promise.all(r)},onSuccess:a=>{var r;if(a!=null&&a.some(i=>i.error))throw new Error(((r=a==null?void 0:a.find(i=>i.error))==null?void 0:r.error)||"Failed to upload asset");{s.invalidateQueries({queryKey:[_.GET_ASSETS]});const i=a==null?void 0:a.length;Q.toast.success(`${i===1?"Asset":i+" Assets"} uploaded successfully`)}},onError:()=>{Q.toast.error("Failed to upload asset")}})},du=()=>{const e=is(),s=G.useQueryClient(),n=se();return G.useMutation({mutationFn:async a=>n(e,{action:_.DELETE_ASSET,data:{id:a}}),onSuccess:a=>{if(a!=null&&a.error)throw new Error(a==null?void 0:a.error);s.invalidateQueries({queryKey:[_.GET_ASSETS]}),Q.toast.success("Asset deleted successfully")},onError:()=>{Q.toast.error("Failed to delete asset")}})},hu=()=>{const e=is(),s=G.useQueryClient(),n=se();return G.useMutation({mutationFn:async a=>n(e,{action:_.UPDATE_ASSET,data:a}),onSuccess:a=>{if(a!=null&&a.error)throw new Error(a==null?void 0:a.error);s.invalidateQueries({queryKey:[_.GET_ASSETS]}),Q.toast.success("Asset updated successfully")},onError:()=>{Q.toast.error("Failed to update asset")}})};function mu({currentPage:e,totalPages:s,onPageChange:n,pageRangeDisplayed:a=3,showPageInput:r=!0,className:i=""}){const[o,l]=f.useState(String(e)),u=f.useMemo(()=>{const y=Math.floor(a/2);let j=Math.max(1,e-y),x=Math.min(s,e+y);x-j+1<a&&(j===1?x=Math.min(s,j+a-1):x===s&&(j=Math.max(1,x-a+1)));const b=[];j>1&&(b.push(1),j>2&&b.push("..."));for(let E=j;E<=x;E++)b.push(E);return x<s&&(x<s-1&&b.push("..."),b.push(s)),b},[e,s,a]),d=y=>{y!==e&&y>=1&&y<=s&&(n(y),l(String(y)))},h=()=>{e>1&&d(e-1)},m=()=>{e<s&&d(e+1)},v=()=>{const y=Number(o);!isNaN(y)&&y>=1&&y<=s&&d(y)},p=y=>{y.key==="Enter"&&v()};return s<=1?null:t.jsxs("div",{className:`flex flex-wrap items-center justify-center gap-3 ${i}`,children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsxs(c.Button,{variant:"outline",size:"sm",onClick:h,disabled:e===1,className:"px-2 py-1 text-sm hover:bg-gray-50",children:[t.jsx(N.ChevronLeft,{className:" h-4 w-4"}),"Previous"]}),t.jsx("div",{className:"flex items-center gap-2",children:u.map((y,j)=>{if(y==="...")return t.jsx("span",{className:"px-2 text-muted-foreground",children:"..."},`ellipsis-${j}`);const x=y,b=x===e;return t.jsx(c.Button,{variant:b?"default":"outline",size:"sm",onClick:()=>d(x),className:b?"border-blue-600 bg-blue-600 px-3 py-1 text-sm text-white":"border px-3 py-1 text-sm hover:bg-gray-50 hover:text-black",children:x},x)})}),t.jsxs(c.Button,{variant:"outline",size:"sm",onClick:m,disabled:e===s,className:"px-2 py-1 text-sm hover:bg-gray-50",children:["Next",t.jsx(N.ChevronRight,{className:" h-4 w-4"})]})]}),r&&t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("span",{className:"text-sm text-muted-foreground",children:"Go to"}),t.jsx(c.Input,{type:"number",min:1,max:s,value:o,onChange:y=>{const j=y.target.value.replace(/[^\d]/g,"");l(j)},onKeyDown:p,className:"h-8 w-16 px-2 py-1"}),t.jsx(c.Button,{variant:"outline",size:"sm",onClick:v,disabled:o===""||Number(o)<1||Number(o)>s,children:"Go"})]})]})}const fu=(e={})=>{const s=is(),n=se(),{search:a,page:r=1,limit:i=30}=e;return G.useQuery({queryKey:[_.GET_ASSETS,a,r,i],queryFn:async()=>{const o=await n(s,{action:_.GET_ASSETS,data:{search:a,page:r,limit:i}});return o.page=r,o.limit=i,o},staleTime:1e3*60*5,retry:1})},gu=e=>{const s=is(),n=se();return G.useQuery({queryKey:[_.GET_ASSET,e],queryFn:async()=>e?await n(s,{action:_.GET_ASSET,data:{id:e}}):null,staleTime:1e3*60*5,retry:1})};function xu(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 Yn(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 Xn(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 pu=({assetId:e,onBack:s,onEdit:n,onSave:a,isSaving:r})=>{var m,v,p;const{data:i,isLoading:o,isError:l}=gu(e||""),[u,d]=f.useState(""),h=async(y,j)=>{try{await navigator.clipboard.writeText(y),Q.toast.success(`${j} copied to clipboard`)}catch(x){Q.toast.error(`Failed to copy ${j}`,{description:x==null?void 0:x.message})}};return f.useEffect(()=>{i!=null&&i.description&&d(i.description)},[i]),o?t.jsx("div",{className:"flex-1 flex items-center justify-center",children:t.jsx(N.Loader,{className:"h-8 w-8 animate-spin"})}):l||!(i!=null&&i.id)?t.jsx("div",{className:"flex-1 flex items-center justify-center",children:t.jsxs("div",{className:"text-center max-w-md mx-auto p-6",children:[t.jsx("div",{className:"flex justify-center mb-4",children:t.jsx(N.AlertCircle,{className:"h-12 w-12 text-gray-400"})}),t.jsx("h3",{className:"text-lg font-medium text-gray-900 mb-2",children:"No Asset Found"}),t.jsx("p",{className:"text-sm text-gray-500 mb-6",children:l?"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"}),l&&t.jsx(c.Button,{variant:"default",onClick:()=>window.location.reload(),children:"Try Again"})]})]})}):t.jsxs("div",{className:"flex-1 flex flex-col gap-y-4 overflow-hidden",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsxs(c.Button,{variant:"outline",size:"sm",onClick:s,disabled:r,children:[t.jsx(N.ChevronLeft,{className:"h-4 w-4"}),"Back to Assets"]}),t.jsxs("div",{className:"flex gap-2",children:[t.jsx(c.Button,{variant:"outline",onClick:s,disabled:r,children:"Cancel"}),t.jsxs(c.Button,{variant:"outline",onClick:()=>h(i.url,"Asset URL"),disabled:r,children:[t.jsx(N.Copy,{className:"h-4 w-4 mr-2"}),"Copy URL"]}),t.jsxs(c.Button,{variant:"default",onClick:()=>n(i),disabled:r,children:[t.jsx(N.Pencil,{className:"h-4 w-4"}),"Edit Image"]})]})]}),t.jsxs("div",{className:"grid grid-cols-2 items-start gap-6 flex-1 overflow-hidden",children:[t.jsx("div",{className:"relative h-[calc(80vh-200px)] w-full flex items-start justify-center",children:t.jsx("img",{src:`${i.url}?v=${((m=i.metadata)==null?void 0:m.updatedAt)||i.createdAt}`,alt:i.name,className:"w-full h-full object-contain rounded-lg max-h-max max-w-max"})}),t.jsxs("div",{className:"space-y-6",children:[t.jsxs("div",{className:"grid gap-3 border rounded-md pt-2 bg-gray-100",children:[t.jsx(c.Label,{className:"w-full text-center",children:"Details"}),t.jsx("div",{className:"grid grid-cols-1 gap-2 text-sm border rounded-md p-2 bg-white",children:[{label:"File Name",value:i.name},{label:"Type",value:i.type,capitalize:!0},{label:"Format",value:((v=i.metadata)==null?void 0:v.format)||i.type,capitalize:!0},{label:"Size",value:xu(i.size)},{label:"Dimensions",value:`${i.width||0} × ${i.height||0}`},{label:"Created",value:Yn(i.createdAt)},{label:"Updated",value:Yn(((p=i.metadata)==null?void 0:p.updatedAt)||i.createdAt)},{label:"URL",value:i.url,copyable:!0}].map(y=>t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(c.Label,{className:"w-max text-left px-2 w-1/4 font-normal text-gray-700",children:y.label}),":",t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("div",{className:"w-max text-left font-medium text-gray-900"+(y.capitalize?" capitalize":""),children:y.value}),y.copyable&&t.jsx(c.Button,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>h(y.value,y.label),children:t.jsx(N.Link,{className:"h-3 w-3"})})]})]},y.label))})]}),i.usedOn&&i.usedOn.length>0&&t.jsxs("div",{className:"grid gap-3",children:[t.jsx(c.Label,{children:"Used On"}),t.jsx("div",{className:"grid grid-cols-1 gap-2 text-sm border rounded-md p-2",children:i.usedOn.map((y,j)=>t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("div",{className:"w-max text-left font-medium text-gray-900",children:y.name}),t.jsxs("div",{className:"text-gray-500",children:["(",y.slug,")"]})]},j))})]}),t.jsxs("div",{className:"grid gap-3 border rounded-md pt-2 bg-gray-100 relative",children:[t.jsx(c.Label,{className:"w-full text-center",children:"Description"}),t.jsx(c.Textarea,{id:"description",value:u,placeholder:"Enter a description for the asset",onChange:y=>d(y.target.value),rows:3,disabled:r,className:"hover:border-black/40 bg-white"}),t.jsx("div",{className:"flex justify-end items-start absolute top-1.5 right-2",children:t.jsx("button",{type:"button",onClick:()=>a(u),disabled:r||!Xn(u,i),className:`py-0 bg-blue-500 text-white px-3 py-0.5 rounded-md text-sm ${r||!Xn(u,i)?"opacity-50 cursor-not-allowed":""}`,children:r?t.jsxs(t.Fragment,{children:[t.jsx(N.Loader,{className:"h-4 w-4 mr-2 animate-spin"}),"Saving..."]}):"Save"})})]})]})]})]})},yu=f.lazy(()=>Promise.resolve().then(()=>require("./image-editor-BWLJT1mr.cjs"))),vu=25*1024*1024,ju=({isUpdatingAsset:e,allowedTypes:s,uploadAssets:n,isUploadingAsset:a,onUploaded:r})=>{const[i,o]=f.useState(()=>{const p=localStorage.getItem("chai_optimize_images");return p!==null?p==="true":!0});f.useEffect(()=>{localStorage.setItem("chai_optimize_images",i.toString())},[i]);const l=e||a,u=f.useCallback(async p=>{try{const y=p;if(!y.every(E=>E.type.startsWith("image/")))return Q.toast.error("Invalid file type. Please upload a valid file."),Promise.reject(new Error("Invalid file type"));const j=y.map(async E=>{let P=E;return E.type.startsWith("image/")&&(P=await pa(E)),new Promise((U,L)=>{const F=new FileReader;F.readAsDataURL(P),F.onload=async()=>{U({file:F.result,folderId:void 0,name:E.name,optimize:i})},F.onerror=()=>L(null)})}),x=await Promise.all(j),b=await n(x);return(b==null?void 0:b.length)===1&&r(b[0]),b}catch(y){return Promise.reject(y)}},[n,i,r]),d=p=>{const y=[];let j=0;return p.forEach(x=>{x.size>vu?j++:y.push(x)}),j>0&&Q.toast.error(`${j===1&&p.length===1?"File":j+(j===1?" file":" files")} exceed the maximum size limit of 10MB.`),g.isEmpty(y)?[]:u(y)},{getRootProps:h,getInputProps:m,isDragActive:v}=Or.useDropzone({onDrop:d,accept:{"image/*":s.includes("image")?[]:[]},disabled:e||a,multiple:!0});return t.jsx("div",{className:`flex h-[60px] w-full flex-col items-center justify-center rounded-lg border-2 border-dashed border-slate-300 p-0 py-2 hover:border-black/50 ${l?"pointer-events-none bg-gray-100 opacity-90":"bg-gray-100 hover:border-black/50 hover:bg-gray-100"}`,children:t.jsxs("div",{...h(),className:V.mergeClasses("flex h-max w-full cursor-pointer flex-col justify-center rounded-lg text-center",l?"items-start":"items-center",v?"border-primary bg-primary/5":"border-muted-foreground/20"),children:[t.jsx("input",{...m()}),l?t.jsx("div",{className:"flex flex-col items-center px-6",children:t.jsxs("div",{className:"flex items-center justify-center gap-2 leading-tight",children:[t.jsx("div",{className:"flex items-center justify-center rounded-full bg-indigo-100 p-2",children:t.jsx(N.Loader,{className:"h-4 w-4 animate-spin text-indigo-500"})}),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 font-light text-muted-foreground",children:["Please wait while we ",e?"update":"upload"," your file..."]})]})]})}):t.jsxs("div",{className:"flex w-full items-center justify-between px-6",children:[t.jsx("div",{className:"flex flex-col items-center",children:t.jsxs("div",{className:"flex items-center justify-between gap-2 leading-tight",children:[t.jsx("div",{className:"flex items-center justify-center rounded-full border border-indigo-500 bg-indigo-100 p-2",children:t.jsx(N.Upload,{className:"h-4 w-4 text-indigo-500"})}),t.jsxs("div",{className:"text-left",children:[t.jsxs("div",{className:"font-medium",children:["Drop your file here or"," ",t.jsx("span",{className:"cursor-pointer text-indigo-500 hover:underline",children:"browse"})]}),t.jsx("div",{className:"text-xs font-light text-muted-foreground",children:t.jsxs("span",{className:"",children:["Accepted file types: ",t.jsx("span",{className:"capitalize text-indigo-400",children:s.join(", ")})]})})]})]})}),t.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsxs("span",{className:"text-xs",children:["Optimization:"," ",t.jsx("span",{className:i?"text-indigo-600":"text-gray-400",children:i?"On":"Off"})]}),t.jsx(c.Switch,{checked:i,onCheckedChange:p=>{o(p)},onClick:p=>{p.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:`flex cursor-help items-center text-amber-500 ${i?"invisible":""}`,children:t.jsx(N.AlertTriangle,{className:"mr-1 h-4 w-4"})})}),t.jsx(c.TooltipContent,{side:"top",children:t.jsxs("p",{className:"text-xs text-white",children:["Warning: Unoptimized images may affect ",t.jsx("br",{})," performance and page load times"]})})]})})]})]})]})})};function kr({close:e,onSelect:s,mode:n="image",assetId:a}){const o=f.useMemo(()=>[n],[n]),[l,u]=f.useState(null),[d,h]=f.useState(null),[m,v]=f.useState(null),[p,y]=f.useState({show:!1,file:""}),[j,x]=f.useState(!1),[b,E]=f.useState(a?"details":"grid"),[P,U]=f.useState(""),[L,F]=f.useState(""),[re,$]=f.useState(1),[k]=f.useState(30),[D,K]=f.useState([]);f.useEffect(()=>{a&&(u(a),E("details"))},[a]),f.useEffect(()=>{const A=setTimeout(()=>{U(L),$(1)},300);return()=>clearTimeout(A)},[L]);const{data:H,isLoading:X}=fu({search:P.toLowerCase().trim(),page:re,limit:k}),Y=(H==null?void 0:H.assets)||[],W=(H==null?void 0:H.total)||0,ie=Math.ceil(W/k);f.useEffect(()=>{X||ie<=0||$(A=>A>ie?ie:A<1?1:A)},[X,ie]);const je=(Y==null?void 0:Y.length)>0,{mutate:fe}=du(),{mutateAsync:Pe,isPending:w}=uu(),{mutate:S,isPending:I}=hu(),B=f.useCallback(A=>{const Z=Math.min(Math.max(1,A),Math.max(1,ie));Z!==re&&$(Z)},[ie,re]),R=A=>{F(A.target.value)},O=f.useCallback(A=>{K(Z=>g.find(Z,{id:A.id})?[]:[A])},[!1]),M=f.useCallback(()=>{K([])},[]),C=A=>{(A==null?void 0:A.length)!==0&&(s(g.pick(g.first(A||D),["id","url","width","height","description"])),e())},q=async A=>{h(A)},ne=async()=>{d&&(v(d==null?void 0:d.id),await fe(d.id,{onSuccess:()=>{v(null),h(null)},onError:()=>{v(null)}}),h(null))},z=A=>{u(A.id),E("details")},J=async(A,Z)=>{try{const Ee=localStorage.getItem("chai_optimize_images")!=="false";Z?(await Pe([{file:A,folderId:void 0,name:p.name||"",optimize:Ee}]),y({show:!1,file:""})):(await S({id:p.id||"",file:A}),y({show:!1,file:""}))}catch(Ee){console.error("Error saving edited image:",Ee)}},ce=f.useCallback(A=>{K([A])},[]),me=f.useCallback(A=>{B(A)},[B]);return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex h-[80vh] max-h-[1232px] w-[80vw] max-w-[1232px] flex-col space-y-4",children:[t.jsx("h1",{className:"text-lg font-medium",children:"Digital Asset Manager"}),b==="grid"?t.jsxs(t.Fragment,{children:[t.jsx(ju,{maxFileSize:10,allowedTypes:o,uploadAssets:Pe,isUpdatingAsset:I,isUploadingAsset:w,onUploaded:ce}),t.jsxs("div",{className:"relative flex flex-1 flex-col gap-y-3 overflow-hidden rounded-lg border p-2",children:[t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsxs("div",{className:"relative w-1/2",children:[t.jsx(N.Search,{strokeWidth:3,className:`absolute left-2 top-2.5 h-4 w-4 text-muted-foreground ${L.length>0?"text-indigo-800":""}`}),t.jsx(c.Input,{placeholder:"Search assets...",onChange:R,value:L,className:"pl-8"})]}),D.length>0?t.jsx("div",{className:"flex items-center justify-between",children:t.jsxs("div",{className:"flex items-center gap-2",children:[D.length>0&&t.jsx(t.Fragment,{children:t.jsx(c.Button,{variant:"outline",size:"sm",onClick:()=>M(),title:"Clear selection",children:"Clear"})}),t.jsx(c.Button,{size:"sm",onClick:()=>C(D),disabled:D.length===0,children:"Select Asset"})]})}):null]}),t.jsx("div",{className:"flex-1 overflow-y-auto pb-[66px]",children:X?t.jsxs("div",{className:"columns-1 gap-3 space-y-3 sm:columns-3 md:columns-5",children:[t.jsx("div",{className:"h-64 w-full animate-pulse rounded bg-gray-200"}),t.jsx("div",{className:"h-64 w-full animate-pulse rounded bg-gray-200"}),t.jsx("div",{className:"h-64 w-full animate-pulse rounded bg-gray-200"}),t.jsx("div",{className:"h-64 w-full animate-pulse rounded bg-gray-200"}),t.jsx("div",{className:"h-64 w-full animate-pulse rounded bg-gray-200"}),t.jsx("div",{className:"h-64 w-full animate-pulse rounded bg-gray-200"}),t.jsx("div",{className:"h-64 w-full animate-pulse rounded bg-gray-200"}),t.jsx("div",{className:"h-64 w-full animate-pulse rounded bg-gray-200"}),t.jsx("div",{className:"h-64 w-full animate-pulse rounded bg-gray-200"}),t.jsx("div",{className:"h-64 w-full animate-pulse rounded bg-gray-200"})]}):!X&&!je?t.jsxs("div",{className:"flex h-full flex-col items-center justify-center rounded-lg border",children:[t.jsx("div",{className:"text-muted-foreground",children:t.jsx(N.Archive,{className:"h-9 w-9 text-indigo-500"})}),t.jsx("div",{className:"text-lg text-muted-foreground",children:"No assets found"}),t.jsx("div",{className:"text-sm text-muted-foreground",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:Y==null?void 0:Y.map(A=>t.jsxs("div",{className:V.mergeClasses("group relative flex max-h-[180px] max-w-[180px] cursor-pointer flex-col justify-between overflow-hidden rounded-lg border-2 transition-all",D.some(Z=>Z.id===A.id)?"border-blue-500":"hover:border-black/90",m&&(d==null?void 0:d.id)===A.id?"pointer-events-none opacity-50":"",m===A.id?"pointer-events-none opacity-50":""),onClick:()=>O(A),onDoubleClick:()=>C([A]),children:[t.jsxs("div",{className:"aspect-square relative overflow-hidden",children:[m===A.id?t.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/50",children:t.jsx(N.Loader,{className:"h-8 w-8 animate-spin text-white"})}):null,A.type==="image"?t.jsx("img",{src:`${A.thumbnailUrl||"/placeholder.svg"}?v=${(A==null?void 0:A.updatedAt)||A.createdAt}`,alt:A.name,className:`h-full min-h-[80px] w-full object-contain ${D.some(Z=>Z.id===A.id)?"":"group-hover:blur group-hover:contrast-50"}`}):t.jsxs("div",{className:"flex h-full items-center justify-center",children:[t.jsx(N.Film,{className:"h-12 w-12 text-muted-foreground"}),A.thumbnailUrl&&t.jsx("img",{src:`${A.thumbnailUrl||"/placeholder.svg"}?v=${(A==null?void 0:A.updatedAt)||A.createdAt}`,alt:A.name,className:"absolute inset-0 h-full w-full object-cover"})]})]}),t.jsxs("div",{className:"flex items-end justify-between border-t-[1px] border-black/10 bg-white px-2 py-1",children:[t.jsx("div",{className:"truncate text-xs leading-tight",title:A.name,children:A.name}),t.jsx("div",{className:"flex items-center justify-between whitespace-nowrap text-[9px] font-light text-muted-foreground",children:t.jsx("span",{children:Zs((A==null?void 0:A.size)||0)})})]}),!D.some(Z=>Z.id===A.id)&&t.jsx("div",{className:"absolute inset-0 flex items-center justify-center opacity-0 transition-opacity group-hover:opacity-100",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:Z=>{Z.stopPropagation(),z(A)},children:t.jsx(N.ImageIcon,{className:"h-4 w-4"})})}),t.jsx(c.TooltipContent,{children:t.jsx("p",{children:"View Details"})})]})}),t.jsx(c.TooltipProvider,{children:t.jsxs(c.Tooltip,{children:[t.jsx(c.TooltipTrigger,{asChild:!0,children:t.jsx(c.Button,{variant:"secondary",size:"icon",className:"h-8 w-8 rounded-full",onClick:Z=>{Z.stopPropagation(),navigator.clipboard.writeText(A.url),Q.toast.success("Asset URL copied to clipboard")},children:t.jsx(N.Copy,{className:"h-4 w-4"})})}),t.jsx(c.TooltipContent,{children:t.jsx("p",{children:"Copy URL"})})]})}),t.jsx(c.TooltipProvider,{children:t.jsxs(c.Tooltip,{children:[t.jsx(c.TooltipTrigger,{asChild:!0,children:t.jsx(c.Button,{variant:"secondary",size:"icon",className:"h-8 w-8 rounded-full",onClick:Z=>{Z.stopPropagation(),y({id:A.id,show:!0,file:A.url,name:A.name})},children:t.jsx(N.Edit,{className:"h-4 w-4"})})}),t.jsx(c.TooltipContent,{children:t.jsx("p",{children:"Edit Image"})})]})}),t.jsx(c.TooltipProvider,{children:t.jsxs(c.Tooltip,{children:[t.jsx(c.TooltipTrigger,{asChild:!0,children:t.jsx(c.Button,{variant:"destructive",size:"icon",className:"h-8 w-8 rounded-full",onClick:Z=>{Z.stopPropagation(),q(A)},children:t.jsx(N.Trash2,{className:"h-4 w-4"})})}),t.jsx(c.TooltipContent,{children:t.jsx("p",{children:"Delete Asset"})})]})})]})}),D.some(Z=>Z.id===A.id)&&t.jsx("div",{className:"absolute right-1 top-1 h-max rounded-full border border-white bg-blue-500 p-1",children:t.jsx(N.Check,{className:"h-3 w-3 text-white",strokeWidth:5})})]},A.id))})}),ie>1&&t.jsx("div",{className:"absolute bottom-0 left-0 right-0 border-t bg-white p-4",children:t.jsx(ou,{fallback:t.jsx("div",{className:"text-red-500",children:"Error loading pagination"}),children:t.jsx(mu,{currentPage:re,totalPages:ie,onPageChange:me,pageRangeDisplayed:3,showPageInput:!0})})})]})]}):t.jsx(pu,{assetId:l||a||"",onBack:()=>{E("grid"),u(null)},onEdit:A=>{y({id:A.id,show:!0,file:A.url,name:A.name})},onSave:async A=>{if(l){x(!0);try{const Z=Y.find(Ee=>Ee.id===l);Z&&await S(g.merge(Z,{description:A}))}finally{x(!1)}}},isSaving:j})]}),p.show&&t.jsx(f.Suspense,{fallback:t.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:t.jsx(N.Loader,{className:"h-8 w-8 animate-spin"})}),children:t.jsx(yu,{imageUrl:p.file,onSave:J,onClose:()=>y({show:!1,file:""}),defaultSavedImageName:p.name,isEditing:!!p.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:ne,children:"Delete"})]})]})})]})}const bu=Object.freeze(Object.defineProperty({__proto__:null,default:kr},Symbol.toStringTag,{value:"Module"})),Ls=({assetId:e,assetUrl:s,onChange:n,className:a="",placeholder:r="Select an image",disabled:i=!1})=>{const[o,l]=f.useState(!1),u=()=>{i||l(!0)},d=()=>{l(!1)},h=p=>{const y=Array.isArray(p)?p[0]:p;y!=null&&y.url&&n(g.pick(y,["url","id"])),l(!1)},m=()=>{n({url:"",id:""})},v=(s==null?void 0:s.startsWith("{{"))&&(s==null?void 0:s.endsWith("}}"));return t.jsxs("div",{className:`w-full ${a}`,children:[s?t.jsxs("div",{className:"relative overflow-hidden rounded-md border",children:[v?t.jsx("div",{className:"flex h-12 items-center bg-gray-100 px-4",children:t.jsx("p",{className:"text-xs text-gray-500",children:s})}):t.jsx("img",{onClick:u,src:s,alt:"Selected image",className:"h-auto max-h-[100px] w-full bg-gray-100 object-contain"}),t.jsxs("div",{className:"absolute right-2 top-2 flex gap-2",children:[t.jsx(c.Button,{type:"button",variant:"outline",size:"icon",className:"h-8 w-8 rounded-full bg-white text-red-500",onClick:m,disabled:i,children:v?t.jsx(N.X,{className:"h-4 w-4"}):t.jsx(N.Trash2,{className:"h-4 w-4"})}),!v&&t.jsx(c.Button,{type:"button",variant:"outline",size:"icon",className:"h-8 w-8 rounded-full bg-white/80 hover:bg-white/90",onClick:u,disabled:i,children:t.jsx(N.ImageIcon,{className:"h-4 w-4"})})]})]}):t.jsx("div",{className:`flex cursor-pointer items-center justify-center rounded-md border border-dashed p-6 ${i?"cursor-not-allowed opacity-50":"hover:border-gray-400"}`,onClick:u,children:t.jsxs("div",{className:"flex flex-col items-center gap-2",children:[t.jsx(N.ImageIcon,{className:"h-10 w-10 text-gray-400"}),t.jsx("p",{className:"text-sm text-gray-500",children:r})]})}),t.jsx(c.Dialog,{open:o,onOpenChange:l,children:t.jsxs(c.DialogContent,{className:"h-fit w-full max-w-7xl overflow-hidden p-0",children:[t.jsxs(c.DialogHeader,{className:"hidden border-b px-4 py-2",children:[t.jsx(c.DialogTitle,{children:"Select Image"}),t.jsx(c.Button,{type:"button",variant:"ghost",size:"icon",className:"absolute right-4 top-2",onClick:d,children:t.jsx(N.X,{className:"h-4 w-4"})})]}),t.jsx("div",{className:"h-full flex-1 p-4",children:t.jsx(kr,{close:d,onSelect:h,mode:"image",assetId:e})})]})})]})},Su=({isActive:e,onClick:s})=>t.jsx(c.Button,{variant:e?"default":"ghost",className:"w-full justify-start text-left",onClick:s,children:"Branding"}),wu=()=>{const[e,s]=f.useState({logoUrl:"",logoId:"",faviconUrl:"",faviconId:""}),[n,a]=f.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(Ls,{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(Ls,{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"})})]})]})},Eu=({isActive:e,onClick:s})=>t.jsx(c.Button,{variant:e?"default":"ghost",className:"w-full justify-start text-left",onClick:s,children:"Contact & Social"}),Nu=()=>{const[e,s]=f.useState({contactEmail:"",contactPhone:"",contactAddress:""}),[n,a]=f.useState([]),[r,i]=f.useState({isOpen:!1,platform:"",url:"",customName:""}),[o,l]=f.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=j=>s(x=>({...x,[j.target.name]:j.target.value})),h=()=>{const{platform:j,url:x,customName:b}=r;if(!x.trim()||!j)return;const E=j==="other"?b:j;E.trim()&&(a(P=>[...P,{platform:E,url:x,isCustom:j==="other"}]),i({isOpen:!1,platform:"",url:"",customName:""}))},m=j=>a(x=>x.filter((b,E)=>E!==j)),v=()=>i({isOpen:!1,platform:"",url:"",customName:""}),p=()=>{l(!0);const j={};n.forEach(b=>{j[b.platform.toLowerCase().replace(/\s+/g,"_")]=b.url});const x={...e,socialLinks:j};setTimeout(()=>{l(!1),console.log("Contact & Social settings saved:",x),s({contactEmail:"",contactPhone:"",contactAddress:""}),a([]),i({isOpen:!1,platform:"",url:"",customName:""})},1e3)},y=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(j=>({...j,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:j=>i(x=>({...x,platform:j.target.value})),className:"input-border w-full rounded px-3 py-1 text-sm",children:[t.jsx("option",{value:"",children:"Select platform"}),u.map(j=>t.jsx("option",{value:j.value,children:j.label},j.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:j=>i(x=>({...x,customName:j.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:j=>i(x=>({...x,url:j.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:v,className:"flex-1",children:"Cancel"})]})]}),n.length>0&&t.jsx("div",{className:"space-y-2",children:n.map((j,x)=>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:j.platform}),t.jsx("p",{className:"max-w-xs truncate text-xs text-gray-500",children:j.url})]}),t.jsx(c.Button,{type:"button",variant:"outline",size:"sm",onClick:()=>m(x),className:"text-red-600 hover:bg-red-50 hover:text-red-700",children:"Remove"})]},x))})]}),t.jsx("div",{className:"pt-3",children:t.jsx(c.Button,{onClick:p,disabled:!y||o,className:"w-full",children:o?"Saving...":"Save Contact & Social Settings"})})]})]})},Cu=({isActive:e,onClick:s})=>t.jsx(c.Button,{variant:e?"default":"ghost",className:"w-full justify-start text-left",onClick:s,children:"Analytics & Tracking"}),Tu=()=>{const[e,s]=f.useState({googleAnalyticsId:"",googleTagManagerId:"",metaPixelId:""}),[n,a]=f.useState([]),[r,i]=f.useState(""),[o,l]=f.useState(!1),u=p=>{const{name:y,value:j}=p.target;s(x=>({...x,[y]:j}))},d=()=>{r.trim()&&(a(p=>[...p,{id:Date.now().toString(),content:r}]),i(""))},h=p=>{a(y=>y.filter(j=>j.id!==p))},m=()=>{l(!0);const p={...e,customTrackingScripts:n.map(y=>y.content)};setTimeout(()=>{l(!1),console.log("Analytics & Tracking settings saved:",p),s({googleAnalyticsId:"",googleTagManagerId:"",metaPixelId:""}),a([])},1e3)},v=Object.values(e).some(p=>p.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:p=>i(p.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(p=>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:p.content.length>100?`${p.content.substring(0,100)}...`:p.content})}),t.jsx(c.Button,{variant:"ghost",size:"sm",className:"text-destructive hover:text-destructive",onClick:()=>h(p.id),children:"Remove"})]},p.id))}),t.jsx("div",{className:"pt-3",children:t.jsx(c.Button,{onClick:m,disabled:!v||o,className:"w-full",children:o?"Saving...":"Save Settings"})})]})]})},Au=()=>{Ss("branding",{label:"Branding",button:Su,panel:wu}),Ss("contact-social",{label:"Contact & Social",button:Eu,panel:Nu}),Ss("analytics-tracking",{label:"Analytics & Tracking",button:Cu,panel:Tu})},ku=f.lazy(()=>Promise.resolve().then(()=>bu));au();Mr.loadWebBlocks();V.registerChaiTopBar(Ol);mo();Au();V.registerChaiMediaManager(ku);V.registerChaiSaveToLibrary(bi);const Zn=e=>{const s=f.useRef([]),[n]=_e(),a=n.get("page"),{data:r}=ke(),{data:i={role:"",permissions:null}}=Da();Fl(),li();const{data:o,isFetching:l}=Ul(),{blocks:u}=Rl(o),{data:d}=Ae(),{mutateAsync:h}=oa(),m=Ml(),{onSave:v}=ql(),{getPartialBlocks:p,getPartialBlockBlocks:y}=zl(),{mutateAsync:j}=wi(),[x,b]=f.useState(!1),{data:E}=$e(),P=We(),{data:U}=wn(),{data:L}=ru(),{mutateAsync:F}=iu(),re=Ar();Jr(),f.useEffect(()=>{const Y=()=>{document.hidden?b(!0):b(!1)};return window.addEventListener("visibilitychange",Y),()=>window.removeEventListener("visibilitychange",Y)},[]),s.current=u;const $=f.useMemo(()=>{const Y={};return i&&(Y.permissions=g.get(i,"permissions",null),Y.role=g.get(i,"role","user")),Y},[i]),k=f.useCallback(async(Y,W)=>await j({pageType:Y,query:W}),[j]),D=f.useMemo(()=>g.get(E,"theme",{})||{},[E]),{lockingStatus:K,pageLock:H}=st(),X=g.isEmpty(K)&&(H==null?void 0:H.status)==="editing";return t.jsxs(t.Fragment,{children:[l&&t.jsx(kt,{children:t.jsx(N.Loader,{className:"h-5 w-5 animate-spin text-primary"})}),t.jsx(V.ChaiBuilderEditor,{gotoPage:re,collections:L??[],getBlockAsyncProps:F,pageExternalData:U,themePresets:e.themePresets??[],pageId:r==null?void 0:r.id,loading:l,fallbackLang:P,languages:(E==null?void 0:E.languages)||[],brandingOptions:(E==null?void 0:E.theme)||{},translations:e.translations||{},locale:e.locale||"en",htmlDir:e.htmlDir||"ltr",autoSave:!x&&X&&(e.autoSave??!0),autoSaveInterval:e.autoSaveInterval??15,onError:e.onError||console.error,getPartialBlockBlocks:y,getPartialBlocks:p,blocks:l?[]:u,theme:g.cloneDeep(D),pageTypes:d,searchPageTypeItems:k,askAiCallBack:m,onSave:async({blocks:Y,theme:W,needTranslations:ie})=>{if(!a)return!0;s.current=Y;const je=[...Y];return await v({page:a,blocks:je,needTranslations:ie}),s.current=je,g.isEqual(W,D)||await h({settings:{theme:W}}),!0},themePanelComponent:_i,...$}),t.jsxs("div",{children:[t.jsx(ui,{isFetchingPage:l}),t.jsx(di,{})]})]})},Pu=new G.QueryClient({defaultOptions:{queries:{refetchOnWindowFocus:!1,refetchOnReconnect:!1}}}),Iu=e=>{const{isLoggedIn:s}=Fe(),[,n]=Ds(),[a,r]=f.useState(!1);return f.useEffect(()=>(n(g.pick(e,["apiUrl","usersApiUrl","assetsApiUrl","getPreviewUrl","getLiveUrl","topLeftCorner","onLogout","getAccessToken","supabaseInstance","features"])),setTimeout(()=>{r(!0)},200),()=>{r(!1),n({})}),[e,n]),a?g.get(e,"hasReactQueryProvider",!1)===!0?t.jsxs(t.Fragment,{children:[s?t.jsx(Zn,{...e}):t.jsx(Rn,{}),t.jsx(Wn,{})]}):t.jsxs(G.QueryClientProvider,{client:Pu,children:[s?t.jsx(Zn,{...e}):t.jsx(Rn,{}),t.jsx(Wn,{})]}):t.jsx("div",{})},_u=()=>{const{savePageAsync:e}=V.useSavePage(),s=G.useQueryClient();return f.useCallback(async()=>{await e(),s.invalidateQueries({queryKey:[_.GET_DRAFT_PAGE]}),s.invalidateQueries({queryKey:[_.GET_BUILDER_PAGE_DATA]})},[e,s])},Lu=()=>{const e=G.useQueryClient();return f.useCallback(()=>{e.clear()},[e])},Du=()=>{const{logout:e}=Fe(),{getAccessToken:s}=ia();return f.useCallback(async({url:n,method:a="GET",body:r={},headers:i={}})=>{const o=await s();if(!o)throw new Error("No auth token");if(!n)throw new Error("URL is required");try{const l=await fetch(n,{method:a,headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`,...i},body:JSON.stringify(r)});if(l.status===401)return console.log("Session expired",l),await e(),window.location.reload(),null;if(l.status===400)throw new Error((await l.json()).error);return await l.json()}catch(l){throw console.log("Something went wrong",l),l}},[e,s])};if(typeof window>"u")throw new Error("@chaibuilder/pages is not available on the server");exports.$TRACK=En;exports.ACTIONS=_;exports.ChaiBuilderPages=Iu;exports.ChaiBuilderPagesRealtime=da;exports.Dynamic=uc;exports.For=Bo;exports.ImagePicker=Ls;exports.Index=Oo;exports.LanguageSwitcher=Sn;exports.Match=Ro;exports.NestedPathSelector=Ke;exports.PAGES_PERMISSIONS=Se;exports.PermissionChecker=ze;exports.Portal=oc;exports.Show=Mo;exports.SmartJsonInput=sn;exports.Switch=Go;exports.addEventListener=rr;exports.batch=yo;exports.className=ar;exports.clearDelegatedEvents=Xo;exports.convertRemToPixels=Xc;exports.createComponent=Tn;exports.createComputed=$a;exports.createContext=wo;exports.createEffect=Nn;exports.createMemo=Ne;exports.createRenderEffect=et;exports.createRoot=Ze;exports.createSignal=ve;exports.createUniqueId=Do;exports.delegateEvents=nr;exports.deleteNestedDataByPath=Mt;exports.displayValue=Kc;exports.getMutationStatusColor=Vc;exports.getPreferredColorScheme=Zc;exports.getQueryStatusColor=zc;exports.getQueryStatusColorByLabel=$c;exports.getQueryStatusLabel=Fc;exports.getSidedProp=qc;exports.insert=_s;exports.memo=Wo;exports.mergeProps=An;exports.mutationSortFns=Yc;exports.on=vo;exports.onCleanup=Pt;exports.onMount=Ka;exports.registerChaiSiteSetting=Ss;exports.registerLoginComponent=Kl;exports.serialize=Er;exports.setAttribute=Is;exports.sortFns=Wc;exports.splitProps=Za;exports.spread=ir;exports.stringify=Uc;exports.template=Yo;exports.untrack=Te;exports.updateNestedDataByPath=Ot;exports.use=lr;exports.useActivePage=Qe;exports.useApiUrl=oe;exports.useBuilderPageData=wn;exports.useChaiAuth=Fe;exports.useChaiFetch=Du;exports.useChaiUserInfo=ls;exports.useClearAll=Lu;exports.useContext=Eo;exports.useCurrentPage=ke;exports.useFallbackLang=We;exports.useFetch=se;exports.useGetPageFullSlug=fa;exports.useGotoPage=Ar;exports.useLanguagePages=Oe;exports.usePageEditInfo=Os;exports.usePageTypes=Ae;exports.useReloadPage=_u;exports.useTransition=So;exports.useUpdateActivePageMetadata=Ma;exports.useUserRoleAndPermissions=Da;exports.useWebsitePages=_t;exports.useWebsiteSetting=$e;
|