@devcabs/folio-engine 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,42 +0,0 @@
1
- (function(C,r){typeof exports=="object"&&typeof module<"u"?r(exports,require("react/jsx-runtime"),require("react"),require("react-dom")):typeof define=="function"&&define.amd?define(["exports","react/jsx-runtime","react","react-dom"],r):(C=typeof globalThis<"u"?globalThis:C||self,r(C.FolioEngine={},C.jsxRuntime,C.React,C.ReactDOM))})(this,(function(C,r,u,bs){"use strict";var Ub=Object.defineProperty;var zb=(C,r,u)=>r in C?Ub(C,r,{enumerable:!0,configurable:!0,writable:!0,value:u}):C[r]=u;var Uo=(C,r,u)=>zb(C,typeof r!="symbol"?r+"":r,u);var We=typeof document<"u"?document.currentScript:null;function ga(e){return{appId:"default-app",appNamespace:"folio",branding:{appName:"Folio Engine",tagline:"Parametric Stepped Sequence & Document AST Platform",logoText:"FOLIO",markSides:8,markWaviness:.15},nodes:[],securitySalt:void 0,expectedPinHash:void 0,features:{enableChartDrawer:!0,enableEditorMode:!0,enableHistoryLedger:!0},...e}}let ur=ga();function ys(){return ur}function hc(e){return ur=ga({...ur,...e}),ur}function Uf(){ur=ga()}function Ae(){return ur.appNamespace||"folio"}function zf(e,t){return(t||Ae())+"_"+e}const Fn={parametricShape:"_parametricShape_17iau_1",sizeSm:"_sizeSm_17iau_16",sizeMd:"_sizeMd_17iau_20",sizeLg:"_sizeLg_17iau_24",conicShape:"_conicShape_17iau_29",letter:"_letter_17iau_54"};function zo({sides:e=5,radius:t=50,waviness:n=10,roundness:s=1,strokeWidth:a=12}={}){const o=Math.max(3,Math.round(e)),i=o*2,l=[],c=n>0&&n<=1?t*n:n;for(let j=0;j<i;j++){const z=-Math.PI/2+j*Math.PI/o,U=j%2===0?t+c:t-c,Q=U*Math.cos(z),se=U*Math.sin(z),ae=-Math.sin(z),de=Math.cos(z);l.push({x:Q,y:se,tx:ae,ty:de})}let d=1/0,h=-1/0,p=1/0,f=-1/0;for(const j of l)j.x<d&&(d=j.x),j.x>h&&(h=j.x),j.y<p&&(p=j.y),j.y>f&&(f=j.y);const m=50-(d+h)/2,g=50-(p+f)/2,b=l.map(j=>({x:j.x+m,y:j.y+g,tx:j.tx,ty:j.ty}));let y=`M ${b[0].x.toFixed(2)} ${b[0].y.toFixed(2)}`;for(let j=0;j<b.length;j++){const z=b[j],O=b[(j+1)%b.length],Q=Math.hypot(O.x-z.x,O.y-z.y)*s,se=z.x+z.tx*Q,ae=z.y+z.ty*Q,de=O.x-O.tx*Q,B=O.y-O.ty*Q;y+=` C ${se.toFixed(2)} ${ae.toFixed(2)}, ${de.toFixed(2)} ${B.toFixed(2)}, ${O.x.toFixed(2)} ${O.y.toFixed(2)}`}y+=" Z";let S=1/0,v=-1/0,k=1/0,x=-1/0;for(let j=0;j<b.length;j++){const z=b[j],O=b[(j+1)%b.length],Q=Math.hypot(O.x-z.x,O.y-z.y)*s,se=z.x+z.tx*Q,ae=z.y+z.ty*Q,de=O.x-O.tx*Q,B=O.y-O.ty*Q;for(let Y=0;Y<=1;Y+=.05){const ee=1-Y,X=ee*ee*ee*z.x+3*ee*ee*Y*se+3*ee*Y*Y*de+Y*Y*Y*O.x,te=ee*ee*ee*z.y+3*ee*ee*Y*ae+3*ee*Y*Y*B+Y*Y*Y*O.y;X<S&&(S=X),X>v&&(v=X),te<k&&(k=te),te>x&&(x=te)}}const I=a/2+.5,N=S-I,_=v+I,T=k-I,w=x+I,M=N===_?100:_-N,$=T===w?100:w-T,A=Math.max(M,$),P=(N+_)/2,V=(T+w)/2,D=(P-A/2).toFixed(2),W=(V-A/2).toFixed(2),H=A.toFixed(2),q=`${D} ${W} ${H} ${H}`;return{pathData:y,viewBox:q}}function Gf(e=8,t=.15,n=24){return zo({sides:e,waviness:t,radius:n}).pathData}const _s=({sides:e=5,radius:t=50,waviness:n=10,roundness:s=1,strokeWidth:a=12,size:o="sm",letter:i,className:l,style:c,fill:d,stroke:h="none",ariaLabel:p="Parametric Brand Mark",ariaHidden:f=!0,children:m})=>{const{pathData:g,viewBox:b}=u.useMemo(()=>zo({sides:e,radius:t,waviness:n,roundness:s,strokeWidth:a}),[e,t,n,s,a]),y=typeof o=="number",S=y?void 0:o==="lg"?Fn.sizeLg:o==="md"?Fn.sizeMd:Fn.sizeSm,v=y?{...c,"--logo-size":`${o}px`}:c??{};if(d||m){const x=y?o:o==="lg"?54:o==="md"?42:36;return r.jsxs("svg",{width:x,height:x,viewBox:b,className:`${Fn.parametricShape} ${S??""} ${l??""}`.trim(),style:v,role:f?"presentation":"img","aria-label":f?void 0:p,"aria-hidden":f,children:[r.jsx("path",{d:g,fill:d||"currentColor",stroke:h,strokeWidth:a}),m]})}const k=`url("data:image/svg+xml,${encodeURIComponent(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="${b}"><path d="${g}" fill="none" stroke="black" stroke-width="${a}" stroke-linecap="round" stroke-linejoin="round"/></svg>`)}")`;return r.jsxs("div",{className:`${Fn.parametricShape} ${S??""} ${l??""}`.trim(),style:v,role:f?"presentation":"img","aria-label":f?void 0:p,"aria-hidden":f,children:[r.jsx("div",{className:Fn.conicShape,style:{WebkitMaskImage:k,maskImage:k}}),i&&r.jsx("span",{className:Fn.letter,children:i})]})},hr={},va=e=>{const t=ys();if(t.securitySalt)return t.securitySalt;if(!(typeof{url:typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:We&&We.tagName.toUpperCase()==="SCRIPT"&&We.src||new URL("folio.umd.cjs",document.baseURI).href}<"u"&&(hr!=null&&hr.VITE_DEV_SALT)))return(e||Ae())+"_dev_salt_v1"},Wf=va(),fc="73b1e1cccbe22119e026c333e9de035db2a553f8acecdb5406af95f59bf46178",Go=1800*1e3,Wo=60*1e3,fr=5,pc=e=>(e||Ae())+"_dev_unlocked_at",ba=pc(),ws=e=>(e||Ae())+"_dev_lockout_until",Hf=ws(),Ss=e=>(e||Ae())+"_dev_failed_attempts",Vf=Ss();function Ho(e){function t(p,f){return p>>>f|p<<32-f}const n=Math.pow,s=n(2,32);let a="";const o=[],i=e.length*8;let l=[];const c=[];let d=0;const h={};for(let p=2;d<64;p++)if(!h[p]){for(let f=p*p;f<312;f+=p)h[f]=!0;d<8&&(l[d]=n(p,.5)*s|0),c[d]=n(p,1/3)*s|0,d++}for(e+="€";e.length%64-56;)e+="\0";for(let p=0;p<e.length;p++){const f=e.charCodeAt(p);if(f>>8)return"";o[p>>2]|=f<<(3-p%4)*8}o[o.length]=i/s|0,o[o.length]=i|0;for(let p=0;p<o.length;){const f=o.slice(p,p+=16),m=[...l];for(let g=0;g<64;g++){const b=f[g-15],y=f[g-2],S=g<16?f[g]:(f[g]=f[g-16]+(t(b,7)^t(b,18)^b>>>3)+f[g-7]+(t(y,17)^t(y,19)^y>>>10)|0|0)|0,v=l[4]&l[5]^~l[4]&l[6],k=t(l[4],6)^t(l[4],11)^t(l[4],25),x=l[7]+k+v+c[g]+S|0,I=t(l[0],2)^t(l[0],13)^t(l[0],22),N=l[0]&l[1]^l[0]&l[2]^l[1]&l[2],_=I+N|0;l=[x+_|0,l[0],l[1],l[2],l[3]+x|0,l[4],l[5],l[6]]}for(let g=0;g<8;g++)l[g]=l[g]+m[g]|0}for(let p=0;p<8;p++)for(let f=3;f>=0;f--){const m=l[p]>>8*f&255;a+=(m<16?"0":"")+m.toString(16)}return a}async function mc(e,t){const s=`${t??va()}:${e}`,a=typeof window<"u"&&window.crypto?window.crypto:typeof globalThis<"u"&&globalThis.crypto?globalThis.crypto:null;if(a&&a.subtle&&typeof a.subtle.digest=="function")try{const i=new TextEncoder().encode(s),l=await a.subtle.digest("SHA-256",i);return Array.from(new Uint8Array(l)).map(d=>d.toString(16).padStart(2,"0")).join("")}catch{return Ho(s)}return Ho(s)}async function gc(e,t,n){if(!e||e.length!==4)return!1;const s=ys(),a=t??s.securitySalt??va(),o=n??s.expectedPinHash??(typeof{url:typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:We&&We.tagName.toUpperCase()==="SCRIPT"&&We.src||new URL("folio.umd.cjs",document.baseURI).href}<"u"&&(hr!=null&&hr.VITE_DEV_PIN_HASH)?void 0:fc);return await mc(e,a)===o}function ya(){if(typeof window>"u")return!1;const e=typeof window.matchMedia=="function"?window.matchMedia("(pointer: fine)").matches||window.matchMedia("(any-pointer: fine)").matches:!0,t=typeof window.matchMedia=="function"?window.matchMedia("(pointer: coarse)").matches&&!e:!1;return(window.innerWidth>=1024||window.innerWidth>=720&&e)&&!t}function en(){if(typeof window>"u"||!window.sessionStorage)return null;const e=sessionStorage.getItem(ba);if(!e)return null;const t=parseInt(e,10);return Number.isFinite(t)?t:null}function vc(e){typeof window>"u"||!window.sessionStorage||sessionStorage.setItem(ba,e.toString())}function Un(){typeof window>"u"||!window.sessionStorage||sessionStorage.removeItem(ba)}function zn(e,t=Date.now()){return e?t-e<Go:!1}function Vo(e,t=Date.now()){if(!e)return 0;const n=t-e,s=Math.max(0,Go-n);return Math.ceil(s/(60*1e3))}function pr(){if(typeof window>"u")return null;try{if(window.localStorage)return window.localStorage}catch{}try{if(window.sessionStorage)return window.sessionStorage}catch{}return null}function _n(){const e=pr();if(!e)return null;const t=e.getItem(ws());if(!t)return null;const n=parseInt(t,10);return Number.isFinite(n)?n:null}function qo(e){const t=pr();t&&t.setItem(ws(),e.toString())}function jo(){const e=pr();e&&e.removeItem(ws())}function _a(){const e=pr();if(!e)return 0;const t=e.getItem(Ss());if(!t)return 0;const n=parseInt(t,10);return Number.isFinite(n)?n:0}function Ko(e){const t=pr();t&&t.setItem(Ss(),e.toString())}function Yo(){const e=pr();e&&e.removeItem(Ss())}const qf="mjuwqlxdxhujqiqpkcaj";function jf(e){return e.toLowerCase().includes(qf)}function Kf(){return typeof{url:typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:We&&We.tagName.toUpperCase()==="SCRIPT"&&We.src||new URL("folio.umd.cjs",document.baseURI).href}<"u"&&!0}function Yf(e,t){const n=jf(e);return!t&&n?{ok:!1,code:"DEV_BUILD_WITH_PROD_DB",message:"Development build is pointed at the PRODUCTION database. Cloud disabled. Fix .env.development."}:t&&!n?{ok:!1,code:"PROD_BUILD_WITH_NON_PROD_DB",message:"Production build is pointed at a non-production database. Cloud disabled. Fix .env.production."}:{ok:!0}}const mr={};let bc=null;function tt(){var n,s;const e=typeof{url:typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:We&&We.tagName.toUpperCase()==="SCRIPT"&&We.src||new URL("folio.umd.cjs",document.baseURI).href}<"u"&&(mr==null?void 0:mr.VITE_SUPABASE_URL)||typeof process<"u"&&((n=process.env)==null?void 0:n.VITE_SUPABASE_URL)||"",t=typeof{url:typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:We&&We.tagName.toUpperCase()==="SCRIPT"&&We.src||new URL("folio.umd.cjs",document.baseURI).href}<"u"&&(mr==null?void 0:mr.VITE_SUPABASE_ANON_KEY)||typeof process<"u"&&((s=process.env)==null?void 0:s.VITE_SUPABASE_ANON_KEY)||"";if(e&&t&&!e.includes("your-project.supabase.co")){const a=e.replace(/\/+$/,""),o=Yf(a,Kf());return o.ok?{url:a,anonKey:t}:(bc!==o.code&&(bc=o.code,console.error(`[env-guard] ${o.code}: ${o.message}`)),null)}return null}const Gn=new Set,yc=e=>(e||Ae())+"_missing_supabase_tables",ks=yc();function wa(){try{if(typeof window<"u"&&window.sessionStorage)return window.sessionStorage;if(typeof sessionStorage<"u")return sessionStorage}catch{}return null}try{const e=wa();if(e){const t=e.getItem(ks);if(t){const n=JSON.parse(t);Array.isArray(n)&&n.filter(s=>s!=="dev_mode_session").forEach(s=>typeof s=="string"&&Gn.add(s))}}}catch{}function It(e){return e==="dev_mode_session"?!0:!Gn.has(e)}function Ot(e){if(e!=="dev_mode_session"){Gn.add(e);try{const t=wa();t&&t.setItem(ks,JSON.stringify(Array.from(Gn)))}catch{}}}function _c(e){Gn.delete(e);try{const t=wa();t&&t.setItem(ks,JSON.stringify(Array.from(Gn)))}catch{}}function Zf(){Gn.clear();try{const e=wa();e&&e.removeItem(ks)}catch{}}const wc=e=>(e||Ae())+"_dev_lock",Cs=wc(),gr=e=>(e||Ae())+"_dev_session_id",Sc=gr(),kc=3e4,Sa=6e4;let xs=null;const Ns=typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():`tab-${Date.now()}-${Math.random().toString(36).substring(2,9)}`;let Zo=null;function Cc(){if(typeof window>"u"||typeof BroadcastChannel>"u")return null;if(!Zo)try{Zo=new BroadcastChannel(Ae()+"_tab_session_dedup")}catch{}return Zo}function xc(){const e=typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():`session-${Date.now()}-${Math.random().toString(36).substring(2,9)}`;if(xs=e,typeof window<"u"&&window.sessionStorage)try{window.sessionStorage.setItem(gr(),e)}catch{}return e}function ka(){if(typeof window<"u"&&window.sessionStorage)try{const e=window.sessionStorage.getItem(gr());if(e&&e.trim().length>0)return e;const t=typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():`session-${Date.now()}-${Math.random().toString(36).substring(2,9)}`;return window.sessionStorage.setItem(gr(),t),t}catch{}return xs||(xs=typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():`session-${Date.now()}-${Math.random().toString(36).substring(2,9)}`),xs}function Xf(e){if(xs=e||null,typeof window<"u"&&window.sessionStorage)try{e?window.sessionStorage.setItem(gr(),e):window.sessionStorage.removeItem(Sc)}catch{}}function Xo(e,t=Date.now()){if(!e.isLocked)return!0;const n=new Date(e.lastHeartbeatAt).getTime();return Number.isNaN(n)?!0:t-n>Sa}function Ts(){var e;if(typeof window>"u")return null;try{const t=(e=window.localStorage)==null?void 0:e.getItem(Cs);if(!t)return null;const n=JSON.parse(t);return n&&typeof n.isLocked=="boolean"&&n.lockedBySessionId?n:null}catch{return null}}function Ct(e){var t,n;if(!(typeof window>"u"))try{e?(n=window.localStorage)==null||n.setItem(Cs,JSON.stringify(e)):(t=window.localStorage)==null||t.removeItem(Cs)}catch{}}async function Wn(e){const t=tt();let n=null,s=!1;if(t&&It("dev_mode_session"))try{const o=new AbortController,i=setTimeout(()=>o.abort(),3500),l=await fetch(`${t.url}/rest/v1/dev_mode_session?id=eq.active_session&select=*`,{method:"GET",cache:"no-store",headers:{apikey:t.anonKey,Authorization:`Bearer ${t.anonKey}`,"Content-Type":"application/json"},signal:o.signal});if(clearTimeout(i),l.status===404)Ot("dev_mode_session");else if(l.ok){s=!0;const c=await l.json();if(c&&c.length>0&&c[0].is_locked){const d=c[0];n={id:"active_session",isLocked:d.is_locked,lockedBySessionId:d.locked_by_session_id,coordinatorLabel:d.coordinator_label||"Coordinator",lockedAt:d.locked_at,lastHeartbeatAt:d.last_heartbeat_at,expiresAt:d.expires_at},Ct(n)}else c&&c.length>0&&!c[0].is_locked&&(n=null,Ct(null))}}catch{}if(!s&&!n&&(n=Ts()),!n||Xo(n))return{canAcquire:!0,currentLock:void 0,isSelfSession:!1};const a=n.lockedBySessionId===e;return{canAcquire:a,currentLock:n,isSelfSession:a}}async function Jo(e,t="Coordinator"){const n=await Wn(e);if(!n.canAcquire&&n.currentLock&&!n.isSelfSession)return{success:!1,lock:n.currentLock,error:"Lock is currently held by another active coordinator."};const s=new Date,a=new Date(s.getTime()+Sa),o={id:"active_session",isLocked:!0,lockedBySessionId:e,coordinatorLabel:t,lockedAt:s.toISOString(),lastHeartbeatAt:s.toISOString(),expiresAt:a.toISOString()},i=tt();if(i&&It("dev_mode_session"))try{const l=s.toISOString(),c=`${i.url}/rest/v1/dev_mode_session?id=eq.active_session&or=(is_locked.eq.false,expires_at.lt.${l},locked_by_session_id.eq.${e})`,d=await fetch(c,{method:"PATCH",headers:{apikey:i.anonKey,Authorization:`Bearer ${i.anonKey}`,"Content-Type":"application/json",Prefer:"return=representation"},body:JSON.stringify({is_locked:!0,locked_by_session_id:e,coordinator_label:t,locked_at:o.lockedAt,last_heartbeat_at:o.lastHeartbeatAt,expires_at:o.expiresAt})});if(d.status===404)return Ot("dev_mode_session"),Ct(o),{success:!0,lock:o};if(d.ok){const h=await d.json();if(h&&h.length>0){const p=h[0],f={id:"active_session",isLocked:!0,lockedBySessionId:p.locked_by_session_id,coordinatorLabel:p.coordinator_label||t,lockedAt:p.locked_at,lastHeartbeatAt:p.last_heartbeat_at,expiresAt:p.expires_at};return Ct(f),{success:!0,lock:f}}else{const p=await fetch(`${i.url}/rest/v1/dev_mode_session?id=eq.active_session&select=*`,{headers:{apikey:i.anonKey,Authorization:`Bearer ${i.anonKey}`}});if(p.ok){const f=await p.json();if(f.length===0){if((await fetch(`${i.url}/rest/v1/dev_mode_session`,{method:"POST",headers:{apikey:i.anonKey,Authorization:`Bearer ${i.anonKey}`,"Content-Type":"application/json",Prefer:"return=representation"},body:JSON.stringify({id:"active_session",is_locked:!0,locked_by_session_id:e,coordinator_label:t,locked_at:o.lockedAt,last_heartbeat_at:o.lastHeartbeatAt,expires_at:o.expiresAt})})).ok)return Ct(o),{success:!0,lock:o}}else if(f[0].is_locked&&f[0].locked_by_session_id!==e){const m={id:"active_session",isLocked:!0,lockedBySessionId:f[0].locked_by_session_id,coordinatorLabel:f[0].coordinator_label||"Coordinator",lockedAt:f[0].locked_at,lastHeartbeatAt:f[0].last_heartbeat_at,expiresAt:f[0].expires_at};return Ct(m),{success:!1,lock:m,error:"Lock is currently held by another active coordinator."}}}}}else console.warn(`[devLockService] Supabase patch responded with HTTP ${d.status}`)}catch(l){console.warn("[devLockService] Supabase write error; holding local lock:",l)}return Ct(o),{success:!0,lock:o}}async function Nc(e){const t=Ts();if(t&&t.isLocked&&t.lockedBySessionId!==e&&!Xo(t))return!1;const n=new Date,s=new Date(n.getTime()+Sa),a={id:"active_session",isLocked:!0,lockedBySessionId:e,coordinatorLabel:(t==null?void 0:t.coordinatorLabel)||"Coordinator",lockedAt:(t==null?void 0:t.lockedAt)||n.toISOString(),lastHeartbeatAt:n.toISOString(),expiresAt:s.toISOString()},o=tt();if(o&&It("dev_mode_session"))try{const i=await fetch(`${o.url}/rest/v1/dev_mode_session?id=eq.active_session&locked_by_session_id=eq.${e}`,{method:"PATCH",headers:{apikey:o.anonKey,Authorization:`Bearer ${o.anonKey}`,"Content-Type":"application/json",Prefer:"return=representation"},body:JSON.stringify({is_locked:!0,last_heartbeat_at:a.lastHeartbeatAt,expires_at:a.expiresAt})});if(i.status===404)return Ot("dev_mode_session"),Ct(a),!0;if(i.ok){const l=await i.json();return l&&l.length>0?(Ct(a),!0):!1}return!1}catch{return!0}return Ct(a),!0}async function Qo(e){const t=Ts();t&&t.lockedBySessionId===e&&Ct(null);const n=tt();if(n&&It("dev_mode_session"))try{const s=await fetch(`${n.url}/rest/v1/dev_mode_session?id=eq.active_session&locked_by_session_id=eq.${e}`,{method:"PATCH",headers:{apikey:n.anonKey,Authorization:`Bearer ${n.anonKey}`,"Content-Type":"application/json"},body:JSON.stringify({is_locked:!1})});return s.status===404?(Ot("dev_mode_session"),!0):s.ok}catch{return!0}return!0}function Tc(e){const t=Ts();t&&t.lockedBySessionId===e&&Ct(null);const n=tt();if(!n||!It("dev_mode_session"))return;const s=`${n.url}/rest/v1/dev_mode_session?id=eq.active_session&locked_by_session_id=eq.${e}`,a=JSON.stringify({is_locked:!1});try{if(typeof navigator<"u"&&navigator.sendBeacon){const o=new Blob([a],{type:"application/json"});if(navigator.sendBeacon(s,o))return}}catch{}try{typeof fetch<"u"&&fetch(s,{method:"PATCH",headers:{apikey:n.anonKey,Authorization:`Bearer ${n.anonKey}`,"Content-Type":"application/json"},body:a,keepalive:!0}).catch(()=>{})}catch{}}function Ac(e){if(typeof window>"u")return()=>{};const t=n=>{if(n.key===Cs)try{const s=n.newValue?JSON.parse(n.newValue):null;e(s)}catch{e(null)}};return window.addEventListener("storage",t),()=>window.removeEventListener("storage",t)}function Vt(e){const t=Date.now().toString(36),n=Math.random().toString(36).substring(2,7);return`${e}-${t}-${n}`}function Jf(e){const t=Vt("subsection");return{id:t,type:"subsection",title:"Subsection Title",titlePointId:e?`node.${e}.subsection.${t}.title`:void 0,subtitle:"Subsection details and source",subtitlePointId:e?`node.${e}.subsection.${t}.subtitle`:void 0,elements:[]}}function Ro(e,t){const n=Vt("section");return{id:n,type:"section",number:String(e+1).padStart(2,"0"),isNumbered:!0,title:"Section Title",titlePointId:t?`node.${t}.section.${n}.title`:void 0,subtitle:"Strategic initiatives and source of progress",subtitlePointId:t?`node.${t}.section.${n}.subtitle`:void 0,elements:[]}}function Ca(e){return{nodeId:e,version:2,sections:[],updatedAt:new Date().toISOString()}}const Ic=e=>(e||Ae())+"_portal_db",Qf=1,vr="history_store";function $c(){return typeof window>"u"||!window.indexedDB?Promise.resolve(null):new Promise(e=>{try{const t=window.indexedDB.open(Ic(),Qf);t.onupgradeneeded=()=>{const n=t.result;n.objectStoreNames.contains(vr)||n.createObjectStore(vr)},t.onsuccess=()=>{e(t.result)},t.onerror=()=>{console.warn("[historyStorage] IndexedDB open error:",t.error),e(null)}}catch(t){console.warn("[historyStorage] IndexedDB initialization error:",t),e(null)}})}async function Ec(e,t){const n=await $c();return n?new Promise(s=>{try{const i=n.transaction(vr,"readwrite").objectStore(vr).put(t,e);i.onsuccess=()=>s(!0),i.onerror=()=>{console.warn("[historyStorage] Save to IndexedDB failed:",i.error),s(!1)}}catch(a){console.warn("[historyStorage] IndexedDB transaction error:",a),s(!1)}}):!1}async function Lc(e){const t=await $c();return t?new Promise(n=>{try{const o=t.transaction(vr,"readonly").objectStore(vr).get(e);o.onsuccess=()=>{n(o.result??null)},o.onerror=()=>{console.warn("[historyStorage] Read from IndexedDB failed:",o.error),n(null)}}catch(s){console.warn("[historyStorage] IndexedDB read error:",s),n(null)}}):null}function Ee(){if(typeof window>"u")return null;try{if(window.localStorage)return window.localStorage}catch{}try{if(window.sessionStorage)return window.sessionStorage}catch{}return null}function Mc(){const e=Ee();if(e)try{const t=[],n=typeof Object.keys=="function"?Object.keys(e):[];for(const a of n)(a.includes("_draft_canvas_")||a.includes("_canvas_")||a.includes("_live_canvas_")||a.includes("_content_overrides"))&&t.push(a);const s=e.length||0;for(let a=0;a<s;a++){const o=e.key(a);o&&(o.includes("_draft_canvas_")||o.includes("_canvas_")||o.includes("_live_canvas_")||o.includes("_content_overrides"))&&!t.includes(o)&&t.push(o)}for(const a of t)e.removeItem(a)}catch{}}try{Mc()}catch{}const As=e=>(e||Ae())+"_live_content_overrides",xa=As(),Is=e=>(e||Ae())+"_draft_content_overrides",ei=Is(),Na=e=>(e||Ae())+"_content_overrides",Dc=Na(),Rf=xa,Ta="engine-live-content-change",$s="engine-draft-content-change";let st=null,ot=null,Bc=null,Oc=null;const ti=new Map,ni=new Map;function tn(){const e=Ae();if(Bc!==e&&(st=null,Bc=e),st!==null)return st;const t=Ee();if(!t)return st=ti.get(e)||{},st;try{let n=t.getItem(As());n||(n=t.getItem(Na())),st=n?JSON.parse(n):{}}catch{st={}}return st}function Es(){const e=Ae();if(Oc!==e&&(ot=null,Oc=e),ot!==null)return ot;const t=Ee();if(!t)return ot=ni.get(e)||{},ot;try{const n=t.getItem(Is());ot=n?JSON.parse(n):{}}catch{ot={}}return ot}function Aa(){const e=Ae();st&&ti.set(e,{...st});const t=Ee();if(!(!t||!st))try{t.setItem(As(),JSON.stringify(st))}catch{}}function ri(){const e=Ae();ot&&ni.set(e,{...ot});const t=Ee();if(!(!t||!ot))try{t.setItem(Is(),JSON.stringify(ot)),kn(!0)}catch{}}function Pt(e,t,n=!1){if(!(typeof window>"u"))try{const s=n?$s:Ta;window.dispatchEvent(new CustomEvent(s,{detail:{key:e,value:t}}))}catch{}}function wn(e,t,n=!1){const s=n?Es():tn();if(Object.prototype.hasOwnProperty.call(s,e)&&typeof s[e]=="string")return s[e];if(n){const a=tn();if(Object.prototype.hasOwnProperty.call(a,e)&&typeof a[e]=="string")return a[e]}return t}function Pc(e,t=!1){const n=t?Es():tn();if(Object.prototype.hasOwnProperty.call(n,e))return!0;if(t){const s=tn();return Object.prototype.hasOwnProperty.call(s,e)}return!1}function nn(e,t,n=!1){if(n){const s=Es();s[e]=t,ri(),Pt(e,t,!0)}else{const s=tn();s[e]=t,Aa(),Pt(e,t,!1)}}function si(e,t,n=!1){const s=wn(e,"",n);if(!s)return t;try{const a=JSON.parse(s);if(t&&typeof t=="object"&&"src"in t){if(typeof a=="string")return{...t,src:a};if(a&&typeof a=="object")return{...t,...a}}return a}catch{return t&&typeof t=="object"&&"src"in t&&typeof s=="string"&&s.trim().length>0?{...t,src:s.trim()}:typeof t=="string"?s:t}}function ep(e,t,n=!1){const s=typeof t=="string"?t:JSON.stringify(t);nn(e,s,n)}function br(e,t=!1){if(t){const n=Es();Object.prototype.hasOwnProperty.call(n,e)&&(delete n[e],ri(),Pt(e,null,!0))}else{const n=tn();Object.prototype.hasOwnProperty.call(n,e)&&(delete n[e],Aa(),Pt(e,null,!1))}}function Ls(e=!1){return e?{...tn(),...Es()}:{...tn()}}function tp(e=!1){const t=Ee();if(e){if(ni.delete(Ae()),ot={},t)try{t.removeItem(Is())}catch{}Pt("*",null,!0)}else{if(ti.delete(Ae()),st={},t)try{t.removeItem(As()),t.removeItem(Na())}catch{}Pt("*",null,!1)}}function Ia(e,t=!1){t?(ot={...e},ri(),Pt("*",null,!0)):(st={...e},Aa(),Pt("*",null,!1))}function yr(){st=null,ot=null,Pt("*",null,!1),Pt("*",null,!0)}function np(){return{...tn()}}function $a(e){st={...e},Aa(),Pt("*",null,!1)}function ai(e,t=!1){if(typeof window>"u")return()=>{};const n=t?$s:Ta,s=o=>{const i=o;i.detail&&e(i.detail)},a=o=>{const i=t?ei:xa;(o.key===i||o.key===null)&&(t?ot=null:st=null,e({key:"*",value:null}))};return window.addEventListener(n,s),window.addEventListener("storage",a),()=>{window.removeEventListener(n,s),window.removeEventListener("storage",a)}}const _r=new Set;let Fc=!1;function rp(){if(typeof window>"u"||Fc)return;const e=s=>{const a=s.detail,o=(a==null?void 0:a.key)||"*";_r.forEach(i=>{(o==="*"||o===i.key)&&i.callback()})},t=s=>{const a=s.detail,o=(a==null?void 0:a.key)||"*";_r.forEach(i=>{i.isDevMode&&(o==="*"||o===i.key)&&i.callback()})},n=s=>{s.key===xa||s.key===Dc||s.key===null?(st=null,_r.forEach(a=>a.callback())):s.key===ei&&(ot=null,_r.forEach(a=>{a.isDevMode&&a.callback()}))};window.addEventListener(Ta,e),window.addEventListener($s,t),window.addEventListener("storage",n),Fc=!0}function Uc(e,t,n=!1){rp();const s={key:e,isDevMode:n,callback:t};return _r.add(s),()=>{_r.delete(s)}}function zc(e,t,n=!1){return wn(e,t,n)}const oi=e=>(e||Ae())+"_draft_canvas_",sp=oi(),ii=e=>(e||Ae())+"_draft_content_overrides",ap=ii(),Sn=e=>(e||Ae())+"_draft_active",Gc=Sn(),Hn=e=>(e||Ae())+"_draft_dirty",op=Hn(),Ea="engine-draft-status-change",La="engine-cloud-draft-sync-status",Wc=1500;let li=!1,ci=!1,wr=null;const qt={};let di=null,Hc="saved";function Sr(e){return`${oi()}${e}`}function Vc(e){const t=qt[e];return t?JSON.parse(JSON.stringify(t)):null}function Ma(e,t){qt[e]=JSON.parse(JSON.stringify(t))}function Da(){if(li)return!0;const e=Ee();if(!e)return!1;try{const t=e.getItem(Sn());if(!t)return!1;if(t==="true")return!0;try{const n=JSON.parse(t);return typeof n=="object"&&n!==null}catch{return!1}}catch{return!1}}function Ms(){if(wr)return wr;const e=Ee();if(!e)return null;try{const t=e.getItem(Sn());if(!t||t==="true")return null;const n=JSON.parse(t);return n&&typeof n=="object"&&"baseId"in n&&n.baseId||null}catch{return null}}function Ds(){const e=cn(),t=Ms();return{isStale:!!(t&&t!==e),baseId:t,currentActiveId:e}}function ip(){return Ds().isStale}function kr(e,t){li=e,e?t!==void 0&&(wr=t):wr=null;const n=Ee();if(n)try{if(e){const a={baseId:t!==void 0?t:Ms(),startedAt:new Date().toISOString()};n.setItem(Sn(),JSON.stringify(a))}else n.removeItem(Sn())}catch{}Cn()}function Bs(){if(ci)return!0;const e=Ee();if(!e)return!1;try{return e.getItem(Hn())==="true"}catch{return!1}}function kn(e){ci=e;const t=Ee();if(t)try{e?t.setItem(Hn(),"true"):t.removeItem(Hn())}catch{}Cn()}function Cn(){typeof window>"u"||typeof window.dispatchEvent!="function"||(window.dispatchEvent(new CustomEvent(Ea,{detail:{isActive:Da(),isDirty:Bs(),timestamp:new Date().toISOString()}})),window.dispatchEvent(new CustomEvent($s,{detail:{channel:"draft",timestamp:Date.now(),key:"*",value:null}})))}function qc(e){if(typeof window>"u")return()=>{};const t=()=>{e({isActive:Da(),isDirty:Bs()})};return window.addEventListener(Ea,t),()=>window.removeEventListener(Ea,t)}function jc(){return Hc}function Kc(e){if(typeof window>"u")return()=>{};const t=n=>{const s=n.detail;e(s)};return window.addEventListener(La,t),()=>window.removeEventListener(La,t)}function Cr(e,t){if(Hc=e,typeof window<"u"&&typeof window.dispatchEvent=="function"){const n={status:e,lastSavedAt:e==="saved"?new Date().toISOString():void 0,error:t};window.dispatchEvent(new CustomEvent(La,{detail:n}))}}function Os(){li=!1,ci=!1,wr=null;for(const t of rn)delete qt[t];const e=Ee();if(e)try{for(const t of rn)e.removeItem(Sr(t));e.removeItem(ii()),e.removeItem(Sn()),e.removeItem(Hn())}catch{}Cn()}function Yc(){if(Object.keys(qt).length>0)return!0;const e=Ee();if(!e)return!1;try{return e.getItem(Sn())!==null}catch{return!1}}async function Zc(){const e=tt();if(!e||!It("engine_drafts"))return null;try{const t=await fetch(`${e.url}/rest/v1/engine_drafts?id=eq.active_draft&select=*`,{headers:{apikey:e.anonKey,Authorization:`Bearer ${e.anonKey}`}});if(t.status===404)return Ot("engine_drafts"),null;if(!t.ok)return null;const n=await t.json();if(!Array.isArray(n)||n.length===0)return null;const s=n[0];return{id:s.id,baseSnapshotId:s.base_snapshot_id,canvases:s.canvases||{},contentOverrides:s.content_overrides||{},updatedAt:s.updated_at,updatedBySession:s.updated_by_session,lockedBySession:s.locked_by_session}}catch(t){return console.warn("[draftService] Fetch active cloud draft failed:",t),null}}function Xc(e,t){if(typeof e!="object"||e===null)return!1;const n=e;return n.nodeId===t&&typeof n.version=="number"&&Array.isArray(n.sections)}async function Jc(){var t;const e=tt();if(!e||!It("engine_drafts"))return Cr("offline"),!1;Cr("saving");try{const s={id:"active_draft",base_snapshot_id:Ms()||cn(),canvases:qt,content_overrides:Ls(!0),updated_at:new Date().toISOString(),updated_by_session:((t=en())==null?void 0:t.toString())||"unknown"},a=await fetch(`${e.url}/rest/v1/engine_drafts`,{method:"POST",headers:{apikey:e.anonKey,Authorization:`Bearer ${e.anonKey}`,"Content-Type":"application/json",Prefer:"resolution=merge-duplicates"},body:JSON.stringify(s)});if(a.status===404)return Ot("engine_drafts"),Cr("offline"),!1;if(!a.ok)throw new Error(`Cloud draft sync failed (${a.status})`);return Cr("saved"),!0}catch(n){return console.warn("[draftService] Cloud draft sync error:",n),Cr("error",n instanceof Error?n.message:"Sync failed"),!1}}function Ba(){di&&clearTimeout(di),Cr("saving"),di=setTimeout(()=>{Jc().catch(()=>{})},Wc)}async function Oa(e=!1){const t=en(),n=zn(t),s=Yc();if(!e&&(n||Da())&&s&&Object.keys(qt).length>0){kr(!0);return}const a=cn();if(!e){try{const i=await Zc();if(i&&Object.keys(i.canvases).length>0){let l=!1;for(const[c,d]of Object.entries(i.canvases))Xc(d,c)&&(qt[c]=d,l=!0);if(l){i.contentOverrides&&Object.keys(i.contentOverrides).length>0&&Ia(i.contentOverrides,!0);const c=i.baseSnapshotId||a;kr(!0,c),Cn(),yr();return}}}catch{}const o=Ee();if(o)try{let i=!1;for(const l of rn){const c=o.getItem(Sr(l));if(c){const d=JSON.parse(c);Xc(d,l)&&(qt[l]=d,i=!0)}}if(i){kr(!0,Ms()||a),Cn(),yr();return}}catch{}}for(const o of rn){const i=Ga(o);qt[o]=JSON.parse(JSON.stringify(i))}kr(!0,a),kn(!1),Cn(),yr()}async function ui(){Os();const e=tt();if(e&&It("engine_drafts"))try{await fetch(`${e.url}/rest/v1/engine_drafts?id=eq.active_draft`,{method:"DELETE",headers:{apikey:e.anonKey,Authorization:`Bearer ${e.anonKey}`}})}catch(t){console.warn("[draftService] Discard cloud draft failed:",t)}Cn(),yr()}function Qc(e,t,n){const s=n||cn();for(const o of rn)e[o]&&(qt[o]=JSON.parse(JSON.stringify(e[o])));wr=s;const a=Ee();if(a)try{a.setItem(Gc,JSON.stringify({baseId:s,startedAt:new Date().toISOString()})),a.removeItem(Hn())}catch{}kn(!1),yr()}const Pa=e=>(e||Ae())+"_live_canvas_",xr=Pa(),hi=e=>(e||Ae())+"_draft_canvas_",lp=hi(),fi=e=>(e||Ae())+"_canvas_",cp=fi(),dp=xr,Nr="engine-live-canvas-change",Tr="engine-draft-canvas-change",Fa=2,rn=["access","equity","quality","resiliency","governance"];function Rc(e){return`${Pa()}${e}`}function ed(e){return`${hi()}${e}`}function td(){const e=Ee();if(!e)return;for(const s of rn){const a=`${fi()}${s}`,o=`${Pa()}${s}`;!e.getItem(o)&&e.getItem(a)&&e.setItem(o,e.getItem(a))}const t=Ae()+"_content_overrides",n=Ae()+"_live_content_overrides";!e.getItem(n)&&e.getItem(t)&&e.setItem(n,e.getItem(t))}function nd(e,t,n){let s=!1;if(e.type==="subsection"){const i=e,l=i.titlePointId||i.pointId;if(l&&t[l]){const c=t[l].trim();c.length>0&&(i.title=c,s=!0),n.push(l)}if(Array.isArray(i.elements))for(const c of i.elements)nd(c,t,n)&&(s=!0);return s}const a=e,o="pointId"in a?a.pointId:void 0;if(o&&t[o]){if(a.type==="photo"){try{const i=JSON.parse(t[o]),l=a;i.src&&typeof i.src=="string"&&i.src.trim().length>0&&(l.src=i.src.trim(),s=!0),i.alt&&typeof i.alt=="string"&&i.alt.trim().length>0&&(l.alt=i.alt.trim(),s=!0),i.caption&&typeof i.caption=="string"&&i.caption.trim().length>0&&(l.caption=i.caption.trim(),s=!0),i.driveUrl&&typeof i.driveUrl=="string"&&i.driveUrl.trim().length>0&&(l.driveUrl=i.driveUrl.trim(),s=!0)}catch{}n.push(o)}else if(a.type==="text"){const i=t[o].trim();i.length>0&&(a.content=i,s=!0),n.push(o)}else if(a.type==="gallery"){const i=t[o].trim();i.length>0&&(a.title=i,s=!0),n.push(o)}}if(a.type==="gallery"){const i=a;if(i.titlePointId&&i.titlePointId!==o&&t[i.titlePointId]){const l=t[i.titlePointId].trim();l.length>0&&(i.title=l,s=!0),n.push(i.titlePointId)}}return s}function rd(e,t){let n=!1;const s=[];if(!e.sections||!Array.isArray(e.sections))return{modified:!1,consumedKeys:s};for(const a of e.sections){const o=a.titlePointId||a.pointId;if(o&&t[o]){const i=t[o].trim();i.length>0&&(a.title=i,n=!0),s.push(o)}if(o){const i=`${o}.isNumbered`;t[i]&&(a.isNumbered=t[i]==="true",n=!0,s.push(i))}if(Array.isArray(a.elements))for(const i of a.elements)nd(i,t,s)&&(n=!0)}return{modified:n,consumedKeys:s}}function Ar(e){const t=Ee();if(!t)return;const n=e==="draft",s=n?Ae()+"_draft_content_overrides":Ae()+"_live_content_overrides",a=t.getItem(s);if(!a)return;let o;try{o=JSON.parse(a)}catch{return}const i=[];for(const l of rn){const c=n?Ft(l,!0):Ga(l);if(!c||(c.version??1)>=Fa)continue;const{modified:d,consumedKeys:h}=rd(c,o);i.push(...h),(d||(c.version??1)<Fa)&&(c.version=Fa,n?Ps(c,!0):Ir(c))}if(i.length>0){for(const l of i)delete o[l];t.setItem(s,JSON.stringify(o))}}if(typeof window<"u")try{td(),Ar("live"),Ar("draft")}catch{}function Ua(e,t){if(typeof e!="object"||e===null)return!1;const n=e;return n.nodeId===t&&typeof n.version=="number"&&Array.isArray(n.sections)&&(n.updatedAt===void 0||typeof n.updatedAt=="string")}function xt(e){return e.map((t,n)=>({...t,number:String(n+1).padStart(2,"0")}))}function pi(e,t,n){const s=[...e.sections];return typeof n=="number"&&n>=0&&n<=s.length?s.splice(n,0,t):s.push(t),{...e,sections:xt(s),updatedAt:new Date().toISOString()}}function mi(e,t,n,s){const a=e.sections.map(o=>{if(o.id!==t)return o;const i=[...o.elements];return typeof s=="number"&&s>=0&&s<=i.length?i.splice(s,0,n):i.push(n),{...o,elements:i}});return{...e,sections:a,updatedAt:new Date().toISOString()}}function gi(e,t,n,s,a){const o=e.sections.map(i=>{if(i.id!==t)return i;if(a){const c=i.elements.map(d=>{if(d.type!=="subsection"||d.id!==a)return d;const h=[...d.elements];return typeof s=="number"&&s>=0&&s<=h.length?h.splice(s,0,n):h.push(n),{...d,elements:h}});return{...i,elements:c}}const l=[...i.elements];return typeof s=="number"&&s>=0&&s<=l.length?l.splice(s,0,n):l.push(n),{...i,elements:l}});return{...e,sections:o,updatedAt:new Date().toISOString()}}function sd(e,t,n,s){const a=n==="up"?-1:1,o=e.sections.findIndex(h=>h.id===t);if(o!==-1&&(!s||e.sections.some(h=>h.id===s))){const h=o+a;if(h<0||h>=e.sections.length)return e;const p=[...e.sections],[f]=p.splice(o,1);return p.splice(h,0,f),{...e,sections:xt(p),updatedAt:new Date().toISOString()}}let i=-1,l=-1,c=-1,d=-1;for(let h=0;h<e.sections.length;h++){const p=e.sections[h],f=p.elements.findIndex(m=>m.id===t);if(f!==-1){i=h,l=f;break}for(let m=0;m<p.elements.length;m++){const g=p.elements[m];if(g.type==="subsection"){const b=g.elements.findIndex(y=>y.id===t);if(b!==-1){i=h,c=m,d=b;break}}}if(i!==-1)break}if(i===-1)return e;if(c!==-1&&d!==-1){const h=e.sections[i],p=h.elements[c],f=d+a;if(f>=0&&f<p.elements.length){const m=[...p.elements],[g]=m.splice(d,1);m.splice(f,0,g);const b=[...h.elements];b[c]={...p,elements:m};const y=[...e.sections];return y[i]={...h,elements:b},{...e,sections:y,updatedAt:new Date().toISOString()}}if(n==="up"&&d===0){const m=p.elements.filter((S,v)=>v!==d),g=p.elements[d],b=[...h.elements];b[c]={...p,elements:m},b.splice(c,0,g);const y=[...e.sections];return y[i]={...h,elements:b},{...e,sections:y,updatedAt:new Date().toISOString()}}if(n==="down"&&d===p.elements.length-1){const m=p.elements.filter((S,v)=>v!==d),g=p.elements[d],b=[...h.elements];b[c]={...p,elements:m},b.splice(c+1,0,g);const y=[...e.sections];return y[i]={...h,elements:b},{...e,sections:y,updatedAt:new Date().toISOString()}}return e}if(l!==-1){const h=e.sections[i],p=l+a;if(p>=0&&p<h.elements.length){const f=[...h.elements],[m]=f.splice(l,1);f.splice(p,0,m);const g=[...e.sections];return g[i]={...h,elements:f},{...e,sections:g,updatedAt:new Date().toISOString()}}if(n==="up"&&l===0){if(i>0){const f=e.sections[i-1],m=[...h.elements],[g]=m.splice(0,1),b=[...f.elements,g],y=[...e.sections];return y[i-1]={...f,elements:b},y[i]={...h,elements:m},{...e,sections:y,updatedAt:new Date().toISOString()}}return e}if(n==="down"&&l===h.elements.length-1){if(i<e.sections.length-1){const f=e.sections[i+1],m=[...h.elements],[g]=m.splice(l,1),b=[g,...f.elements],y=[...e.sections];return y[i]={...h,elements:m},y[i+1]={...f,elements:b},{...e,sections:y,updatedAt:new Date().toISOString()}}return e}}return e}function ad(e,t,n,s){let a=null,o=[];const i=e.sections.findIndex(l=>l.id===t);if(i!==-1?(o=[...e.sections],[a]=o.splice(i,1)):o=e.sections.map(l=>{const c=l.elements.findIndex(p=>p.id===t);if(c!==-1){const p=[...l.elements];return[a]=p.splice(c,1),{...l,elements:p}}let d=!1;const h=l.elements.map(p=>{if(p.type!=="subsection")return p;const f=p.elements.findIndex(m=>m.id===t);if(f!==-1){d=!0;const m=[...p.elements];return[a]=m.splice(f,1),{...p,elements:m}}return p});return d?{...l,elements:h}:l}),!a)return e;if(n===e.nodeId||n==="root"){if(a.type==="section"){const l=typeof s=="number"&&s>=0&&s<=o.length?s:o.length;o.splice(l,0,a)}else if(o.length===0){const l={id:`sec-${Date.now().toString(36)}`,type:"section",number:"01",title:"Section Title",elements:[a]};o.push(l)}else{const l=typeof s=="number"&&s>=0&&s<o.length?s:o.length-1,c=o[l],d=[...c.elements,a];o[l]={...c,elements:d}}return{...e,sections:xt(o),updatedAt:new Date().toISOString()}}return o=o.map(l=>{if(l.id===n){const d=[...l.elements],h=typeof s=="number"&&s>=0&&s<=d.length?s:d.length;return d.splice(h,0,a),{...l,elements:d}}const c=l.elements.findIndex(d=>d.type==="subsection"&&d.id===n);if(c!==-1&&a&&a.type!=="section"&&a.type!=="subsection"){const d=l.elements[c],h=[...d.elements],p=typeof s=="number"&&s>=0&&s<=h.length?s:h.length;h.splice(p,0,a);const f=[...l.elements];return f[c]={...d,elements:h},{...l,elements:f}}return l}),{...e,sections:xt(o),updatedAt:new Date().toISOString()}}function od(e,t,n){if(e.sections.some(a=>a.id===t)&&(!n||n===e.nodeId)){const a=e.sections.filter(o=>o.id!==t);return{...e,sections:xt(a),updatedAt:new Date().toISOString()}}const s=e.sections.map(a=>{const o=a.elements.filter(i=>i.id!==t).map(i=>{if(i.type!=="subsection")return i;const l=i.elements.filter(c=>c.id!==t);return l.length===i.elements.length?i:{...i,elements:l}});return{...a,elements:o}});return{...e,sections:s,updatedAt:new Date().toISOString()}}function id(e,t,n){const s=e.sections.map(a=>{if(a.id===t)return{...a,...n};const o=a.elements.map(i=>{if(i.id===t)return{...i,...n};if(i.type==="subsection"){const l=i.elements.map(c=>c.id===t?{...c,...n}:c);return{...i,elements:l}}return i});return{...a,elements:o}});return{...e,sections:s,updatedAt:new Date().toISOString()}}function za(e,t){const n=e.sections.findIndex(s=>s.id===t);if(n!==-1)return{item:e.sections[n],kind:"section",index:n,sectionId:t};for(const s of e.sections)for(let a=0;a<s.elements.length;a++){const o=s.elements[a];if(o.id===t)return{item:o,kind:o.type==="subsection"?"subsection":"leaf",index:a,sectionId:s.id};if(o.type==="subsection")for(let i=0;i<o.elements.length;i++){const l=o.elements[i];if(l.id===t)return{item:l,kind:"leaf",index:i,sectionId:s.id,subsectionId:o.id}}}return null}function Ga(e){const t=Ee(),n=`${xr}${e}`;if(t)try{const s=t.getItem(n);if(s){const a=JSON.parse(s);if(Ua(a,e))return{...a,sections:xt(a.sections)}}}catch{}return Ca(e)}function Ir(e,t){const n={...e,sections:xt(e.sections),updatedAt:new Date().toISOString()},s=Ee();let a=!0,o;if(s)try{s.setItem(`${xr}${e.nodeId}`,JSON.stringify(n))}catch(i){console.error("Storage quota exceeded while saving live canvas document:",i),a=!1,o="quota"}else a=!1,o="unknown";if(a&&!(t!=null&&t.silent)&&typeof window<"u"&&typeof window.dispatchEvent=="function"){const i={nodeId:e.nodeId,document:n};window.dispatchEvent(new CustomEvent(Nr,{detail:i}))}return{ok:a,error:o,document:n}}function Ft(e,t=!1){const n=Ee();if(t){const s=Vc(e);if(s&&Ua(s,e))return{...s,sections:xt(s.sections)};if(n)try{const a=n.getItem(Sr(e));if(a){const o=JSON.parse(a);if(Ua(o,e))return{...o,sections:xt(o.sections)}}}catch{}}return Ga(e)}function Ps(e,t=!1,n){const s={...e,sections:xt(e.sections),updatedAt:new Date().toISOString()},a=Ee();let o=!0,i;if(t)Ma(e.nodeId,s),kn(!0),Ba();else if(a)try{a.setItem(`${xr}${e.nodeId}`,JSON.stringify(s))}catch(l){console.error("Storage quota exceeded while saving canvas document:",l),o=!1,i="quota"}else o=!1,i="unknown";if(o&&!(n!=null&&n.silent)&&typeof window<"u"&&typeof window.dispatchEvent=="function"){const l=t?Tr:Nr,c={nodeId:e.nodeId,document:s};window.dispatchEvent(new CustomEvent(l,{detail:c}))}return{ok:o,error:i,document:s}}function Fs(e=!1){if(typeof window>"u"||typeof window.dispatchEvent!="function")return;const t=e?Tr:Nr;window.dispatchEvent(new CustomEvent(t,{detail:{nodeId:"*"}}))}function vi(e,t=!1){const n=Ca(e),s=Ee();if(t){if(Ma(e,n),kn(!0),Ba(),s)try{s.removeItem(Sr(e))}catch{}}else if(s)try{s.removeItem(`${xr}${e}`)}catch{}if(typeof window<"u"&&typeof window.dispatchEvent=="function"){const a=t?Tr:Nr,o={nodeId:e,document:n};window.dispatchEvent(new CustomEvent(a,{detail:o}))}return n}function bi(e,t,n=!1){if(typeof window>"u")return()=>{};const s=n?Tr:Nr,a=i=>{const l=i;if(l.detail&&(l.detail.nodeId===e||l.detail.nodeId==="*")){const c=l.detail.nodeId==="*"||!l.detail.document?Ft(e,n):l.detail.document;t(c)}},o=i=>{const l=n?ed(e):Rc(e);if((i.key===l||i.key===null)&&i.newValue)try{const c=JSON.parse(i.newValue);Ua(c,e)&&t({...c,sections:xt(c.sections)})}catch{}};return window.addEventListener(s,a),window.addEventListener("storage",o),()=>{window.removeEventListener(s,a),window.removeEventListener("storage",o)}}async function yi(e){const t=Ft(e),n=tt();if(!n)return{success:!0};if(!It("pillar_canvas"))return{success:!1,error:"Table pillar_canvas unavailable in this session"};try{const s=await fetch(`${n.url}/rest/v1/node_canvas`,{method:"POST",headers:{apikey:n.anonKey,Authorization:`Bearer ${n.anonKey}`,"Content-Type":"application/json",Prefer:"resolution=merge-duplicates,return=representation"},body:JSON.stringify({node_id:e,document:t,updated_at:t.updatedAt})});return s.status===404?(Ot("pillar_canvas"),{success:!1,error:`Cloud sync responded with status ${s.status}`}):s.ok?{success:!0}:{success:!1,error:`Cloud sync responded with status ${s.status}`}}catch(s){return{success:!1,error:s instanceof Error?s.message:String(s)}}}const up={getNodeCanvas:Ft,saveNodeCanvas:Ps,resetNodeCanvas:vi,subscribeToCanvasChange:bi,deployNodeCanvasToCloud:yi};var Le;(function(e){e.assertEqual=a=>{};function t(a){}e.assertIs=t;function n(a){throw new Error}e.assertNever=n,e.arrayToEnum=a=>{const o={};for(const i of a)o[i]=i;return o},e.getValidEnumValues=a=>{const o=e.objectKeys(a).filter(l=>typeof a[a[l]]!="number"),i={};for(const l of o)i[l]=a[l];return e.objectValues(i)},e.objectValues=a=>e.objectKeys(a).map(function(o){return a[o]}),e.objectKeys=typeof Object.keys=="function"?a=>Object.keys(a):a=>{const o=[];for(const i in a)Object.prototype.hasOwnProperty.call(a,i)&&o.push(i);return o},e.find=(a,o)=>{for(const i of a)if(o(i))return i},e.isInteger=typeof Number.isInteger=="function"?a=>Number.isInteger(a):a=>typeof a=="number"&&Number.isFinite(a)&&Math.floor(a)===a;function s(a,o=" | "){return a.map(i=>typeof i=="string"?`'${i}'`:i).join(o)}e.joinValues=s,e.jsonStringifyReplacer=(a,o)=>typeof o=="bigint"?o.toString():o})(Le||(Le={}));var ld;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(ld||(ld={}));const ge=Le.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),xn=e=>{switch(typeof e){case"undefined":return ge.undefined;case"string":return ge.string;case"number":return Number.isNaN(e)?ge.nan:ge.number;case"boolean":return ge.boolean;case"function":return ge.function;case"bigint":return ge.bigint;case"symbol":return ge.symbol;case"object":return Array.isArray(e)?ge.array:e===null?ge.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?ge.promise:typeof Map<"u"&&e instanceof Map?ge.map:typeof Set<"u"&&e instanceof Set?ge.set:typeof Date<"u"&&e instanceof Date?ge.date:ge.object;default:return ge.unknown}},ce=Le.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class sn extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=s=>{this.issues=[...this.issues,s]},this.addIssues=(s=[])=>{this.issues=[...this.issues,...s]};const n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}format(t){const n=t||function(o){return o.message},s={_errors:[]},a=o=>{for(const i of o.issues)if(i.code==="invalid_union")i.unionErrors.map(a);else if(i.code==="invalid_return_type")a(i.returnTypeError);else if(i.code==="invalid_arguments")a(i.argumentsError);else if(i.path.length===0)s._errors.push(n(i));else{let l=s,c=0;for(;c<i.path.length;){const d=i.path[c];c===i.path.length-1?(l[d]=l[d]||{_errors:[]},l[d]._errors.push(n(i))):l[d]=l[d]||{_errors:[]},l=l[d],c++}}};return a(this),s}static assert(t){if(!(t instanceof sn))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Le.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=n=>n.message){const n={},s=[];for(const a of this.issues)if(a.path.length>0){const o=a.path[0];n[o]=n[o]||[],n[o].push(t(a))}else s.push(t(a));return{formErrors:s,fieldErrors:n}}get formErrors(){return this.flatten()}}sn.create=e=>new sn(e);const _i=(e,t)=>{let n;switch(e.code){case ce.invalid_type:e.received===ge.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case ce.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,Le.jsonStringifyReplacer)}`;break;case ce.unrecognized_keys:n=`Unrecognized key(s) in object: ${Le.joinValues(e.keys,", ")}`;break;case ce.invalid_union:n="Invalid input";break;case ce.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${Le.joinValues(e.options)}`;break;case ce.invalid_enum_value:n=`Invalid enum value. Expected ${Le.joinValues(e.options)}, received '${e.received}'`;break;case ce.invalid_arguments:n="Invalid function arguments";break;case ce.invalid_return_type:n="Invalid function return type";break;case ce.invalid_date:n="Invalid date";break;case ce.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:Le.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case ce.too_small:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="bigint"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:n="Invalid input";break;case ce.too_big:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?n=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:n="Invalid input";break;case ce.custom:n="Invalid input";break;case ce.invalid_intersection_types:n="Intersection results could not be merged";break;case ce.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case ce.not_finite:n="Number must be finite";break;default:n=t.defaultError,Le.assertNever(e)}return{message:n}};let hp=_i;function fp(){return hp}const pp=e=>{const{data:t,path:n,errorMaps:s,issueData:a}=e,o=[...n,...a.path||[]],i={...a,path:o};if(a.message!==void 0)return{...a,path:o,message:a.message};let l="";const c=s.filter(d=>!!d).slice().reverse();for(const d of c)l=d(i,{data:t,defaultError:l}).message;return{...a,path:o,message:l}};function pe(e,t){const n=fp(),s=pp({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===_i?void 0:_i].filter(a=>!!a)});e.common.issues.push(s)}class gt{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){const s=[];for(const a of n){if(a.status==="aborted")return Ce;a.status==="dirty"&&t.dirty(),s.push(a.value)}return{status:t.value,value:s}}static async mergeObjectAsync(t,n){const s=[];for(const a of n){const o=await a.key,i=await a.value;s.push({key:o,value:i})}return gt.mergeObjectSync(t,s)}static mergeObjectSync(t,n){const s={};for(const a of n){const{key:o,value:i}=a;if(o.status==="aborted"||i.status==="aborted")return Ce;o.status==="dirty"&&t.dirty(),i.status==="dirty"&&t.dirty(),o.value!=="__proto__"&&(typeof i.value<"u"||a.alwaysSet)&&(s[o.value]=i.value)}return{status:t.value,value:s}}}const Ce=Object.freeze({status:"aborted"}),Us=e=>({status:"dirty",value:e}),$t=e=>({status:"valid",value:e}),cd=e=>e.status==="aborted",dd=e=>e.status==="dirty",$r=e=>e.status==="valid",Wa=e=>typeof Promise<"u"&&e instanceof Promise;var ve;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t==null?void 0:t.message})(ve||(ve={}));class jt{constructor(t,n,s,a){this._cachedPath=[],this.parent=t,this.data=n,this._path=s,this._key=a}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const ud=(e,t)=>{if($r(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const n=new sn(e.common.issues);return this._error=n,this._error}}};function Te(e){if(!e)return{};const{errorMap:t,invalid_type_error:n,required_error:s,description:a}=e;if(t&&(n||s))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:a}:{errorMap:(i,l)=>{const{message:c}=e;return i.code==="invalid_enum_value"?{message:c??l.defaultError}:typeof l.data>"u"?{message:c??s??l.defaultError}:i.code!=="invalid_type"?{message:l.defaultError}:{message:c??n??l.defaultError}},description:a}}class $e{get description(){return this._def.description}_getType(t){return xn(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:xn(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new gt,ctx:{common:t.parent.common,data:t.data,parsedType:xn(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const n=this._parse(t);if(Wa(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(t){const n=this._parse(t);return Promise.resolve(n)}parse(t,n){const s=this.safeParse(t,n);if(s.success)return s.data;throw s.error}safeParse(t,n){const s={common:{issues:[],async:(n==null?void 0:n.async)??!1,contextualErrorMap:n==null?void 0:n.errorMap},path:(n==null?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:xn(t)},a=this._parseSync({data:t,path:s.path,parent:s});return ud(s,a)}"~validate"(t){var s,a;const n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:xn(t)};if(!this["~standard"].async)try{const o=this._parseSync({data:t,path:[],parent:n});return $r(o)?{value:o.value}:{issues:n.common.issues}}catch(o){(a=(s=o==null?void 0:o.message)==null?void 0:s.toLowerCase())!=null&&a.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:n}).then(o=>$r(o)?{value:o.value}:{issues:n.common.issues})}async parseAsync(t,n){const s=await this.safeParseAsync(t,n);if(s.success)return s.data;throw s.error}async safeParseAsync(t,n){const s={common:{issues:[],contextualErrorMap:n==null?void 0:n.errorMap,async:!0},path:(n==null?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:xn(t)},a=this._parse({data:t,path:s.path,parent:s}),o=await(Wa(a)?a:Promise.resolve(a));return ud(s,o)}refine(t,n){const s=a=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(a):n;return this._refinement((a,o)=>{const i=t(a),l=()=>o.addIssue({code:ce.custom,...s(a)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(l(),!1)):i?!0:(l(),!1)})}refinement(t,n){return this._refinement((s,a)=>t(s)?!0:(a.addIssue(typeof n=="function"?n(s,a):n),!1))}_refinement(t){return new Dr({schema:this,typeName:we.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:n=>this["~validate"](n)}}optional(){return Tn.create(this,this._def)}nullable(){return Br.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Kt.create(this)}promise(){return Ka.create(this,this._def)}or(t){return Va.create([this,t],this._def)}and(t){return qa.create(this,t,this._def)}transform(t){return new Dr({...Te(this._def),schema:this,typeName:we.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const n=typeof t=="function"?t:()=>t;return new Ci({...Te(this._def),innerType:this,defaultValue:n,typeName:we.ZodDefault})}brand(){return new Pp({typeName:we.ZodBranded,type:this,...Te(this._def)})}catch(t){const n=typeof t=="function"?t:()=>t;return new xi({...Te(this._def),innerType:this,catchValue:n,typeName:we.ZodCatch})}describe(t){const n=this.constructor;return new n({...this._def,description:t})}pipe(t){return Ni.create(this,t)}readonly(){return Ti.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const mp=/^c[^\s-]{8,}$/i,gp=/^[0-9a-z]+$/,vp=/^[0-9A-HJKMNP-TV-Z]{26}$/i,bp=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,yp=/^[a-z0-9_-]{21}$/i,_p=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,wp=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Sp=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,kp="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let wi;const Cp=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,xp=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Np=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Tp=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Ap=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Ip=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,hd="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",$p=new RegExp(`^${hd}$`);function fd(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`);const n=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${n}`}function Ep(e){return new RegExp(`^${fd(e)}$`)}function Lp(e){let t=`${hd}T${fd(e)}`;const n=[];return n.push(e.local?"Z?":"Z"),e.offset&&n.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${n.join("|")})`,new RegExp(`^${t}$`)}function Mp(e,t){return!!((t==="v4"||!t)&&Cp.test(e)||(t==="v6"||!t)&&Np.test(e))}function Dp(e,t){if(!_p.test(e))return!1;try{const[n]=e.split(".");if(!n)return!1;const s=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),a=JSON.parse(atob(s));return!(typeof a!="object"||a===null||"typ"in a&&(a==null?void 0:a.typ)!=="JWT"||!a.alg||t&&a.alg!==t)}catch{return!1}}function Bp(e,t){return!!((t==="v4"||!t)&&xp.test(e)||(t==="v6"||!t)&&Tp.test(e))}class an extends $e{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==ge.string){const o=this._getOrReturnCtx(t);return pe(o,{code:ce.invalid_type,expected:ge.string,received:o.parsedType}),Ce}const s=new gt;let a;for(const o of this._def.checks)if(o.kind==="min")t.data.length<o.value&&(a=this._getOrReturnCtx(t,a),pe(a,{code:ce.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),s.dirty());else if(o.kind==="max")t.data.length>o.value&&(a=this._getOrReturnCtx(t,a),pe(a,{code:ce.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),s.dirty());else if(o.kind==="length"){const i=t.data.length>o.value,l=t.data.length<o.value;(i||l)&&(a=this._getOrReturnCtx(t,a),i?pe(a,{code:ce.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):l&&pe(a,{code:ce.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),s.dirty())}else if(o.kind==="email")Sp.test(t.data)||(a=this._getOrReturnCtx(t,a),pe(a,{validation:"email",code:ce.invalid_string,message:o.message}),s.dirty());else if(o.kind==="emoji")wi||(wi=new RegExp(kp,"u")),wi.test(t.data)||(a=this._getOrReturnCtx(t,a),pe(a,{validation:"emoji",code:ce.invalid_string,message:o.message}),s.dirty());else if(o.kind==="uuid")bp.test(t.data)||(a=this._getOrReturnCtx(t,a),pe(a,{validation:"uuid",code:ce.invalid_string,message:o.message}),s.dirty());else if(o.kind==="nanoid")yp.test(t.data)||(a=this._getOrReturnCtx(t,a),pe(a,{validation:"nanoid",code:ce.invalid_string,message:o.message}),s.dirty());else if(o.kind==="cuid")mp.test(t.data)||(a=this._getOrReturnCtx(t,a),pe(a,{validation:"cuid",code:ce.invalid_string,message:o.message}),s.dirty());else if(o.kind==="cuid2")gp.test(t.data)||(a=this._getOrReturnCtx(t,a),pe(a,{validation:"cuid2",code:ce.invalid_string,message:o.message}),s.dirty());else if(o.kind==="ulid")vp.test(t.data)||(a=this._getOrReturnCtx(t,a),pe(a,{validation:"ulid",code:ce.invalid_string,message:o.message}),s.dirty());else if(o.kind==="url")try{new URL(t.data)}catch{a=this._getOrReturnCtx(t,a),pe(a,{validation:"url",code:ce.invalid_string,message:o.message}),s.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(t.data)||(a=this._getOrReturnCtx(t,a),pe(a,{validation:"regex",code:ce.invalid_string,message:o.message}),s.dirty())):o.kind==="trim"?t.data=t.data.trim():o.kind==="includes"?t.data.includes(o.value,o.position)||(a=this._getOrReturnCtx(t,a),pe(a,{code:ce.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),s.dirty()):o.kind==="toLowerCase"?t.data=t.data.toLowerCase():o.kind==="toUpperCase"?t.data=t.data.toUpperCase():o.kind==="startsWith"?t.data.startsWith(o.value)||(a=this._getOrReturnCtx(t,a),pe(a,{code:ce.invalid_string,validation:{startsWith:o.value},message:o.message}),s.dirty()):o.kind==="endsWith"?t.data.endsWith(o.value)||(a=this._getOrReturnCtx(t,a),pe(a,{code:ce.invalid_string,validation:{endsWith:o.value},message:o.message}),s.dirty()):o.kind==="datetime"?Lp(o).test(t.data)||(a=this._getOrReturnCtx(t,a),pe(a,{code:ce.invalid_string,validation:"datetime",message:o.message}),s.dirty()):o.kind==="date"?$p.test(t.data)||(a=this._getOrReturnCtx(t,a),pe(a,{code:ce.invalid_string,validation:"date",message:o.message}),s.dirty()):o.kind==="time"?Ep(o).test(t.data)||(a=this._getOrReturnCtx(t,a),pe(a,{code:ce.invalid_string,validation:"time",message:o.message}),s.dirty()):o.kind==="duration"?wp.test(t.data)||(a=this._getOrReturnCtx(t,a),pe(a,{validation:"duration",code:ce.invalid_string,message:o.message}),s.dirty()):o.kind==="ip"?Mp(t.data,o.version)||(a=this._getOrReturnCtx(t,a),pe(a,{validation:"ip",code:ce.invalid_string,message:o.message}),s.dirty()):o.kind==="jwt"?Dp(t.data,o.alg)||(a=this._getOrReturnCtx(t,a),pe(a,{validation:"jwt",code:ce.invalid_string,message:o.message}),s.dirty()):o.kind==="cidr"?Bp(t.data,o.version)||(a=this._getOrReturnCtx(t,a),pe(a,{validation:"cidr",code:ce.invalid_string,message:o.message}),s.dirty()):o.kind==="base64"?Ap.test(t.data)||(a=this._getOrReturnCtx(t,a),pe(a,{validation:"base64",code:ce.invalid_string,message:o.message}),s.dirty()):o.kind==="base64url"?Ip.test(t.data)||(a=this._getOrReturnCtx(t,a),pe(a,{validation:"base64url",code:ce.invalid_string,message:o.message}),s.dirty()):Le.assertNever(o);return{status:s.value,value:t.data}}_regex(t,n,s){return this.refinement(a=>t.test(a),{validation:n,code:ce.invalid_string,...ve.errToObj(s)})}_addCheck(t){return new an({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...ve.errToObj(t)})}url(t){return this._addCheck({kind:"url",...ve.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...ve.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...ve.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...ve.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...ve.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...ve.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...ve.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...ve.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...ve.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...ve.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...ve.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...ve.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof(t==null?void 0:t.precision)>"u"?null:t==null?void 0:t.precision,offset:(t==null?void 0:t.offset)??!1,local:(t==null?void 0:t.local)??!1,...ve.errToObj(t==null?void 0:t.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof(t==null?void 0:t.precision)>"u"?null:t==null?void 0:t.precision,...ve.errToObj(t==null?void 0:t.message)})}duration(t){return this._addCheck({kind:"duration",...ve.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...ve.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n==null?void 0:n.position,...ve.errToObj(n==null?void 0:n.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...ve.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...ve.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...ve.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...ve.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...ve.errToObj(n)})}nonempty(t){return this.min(1,ve.errToObj(t))}trim(){return new an({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new an({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new an({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxLength(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}}an.create=e=>new an({checks:[],typeName:we.ZodString,coerce:(e==null?void 0:e.coerce)??!1,...Te(e)});function Op(e,t){const n=(e.toString().split(".")[1]||"").length,s=(t.toString().split(".")[1]||"").length,a=n>s?n:s,o=Number.parseInt(e.toFixed(a).replace(".","")),i=Number.parseInt(t.toFixed(a).replace(".",""));return o%i/10**a}class Er extends $e{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==ge.number){const o=this._getOrReturnCtx(t);return pe(o,{code:ce.invalid_type,expected:ge.number,received:o.parsedType}),Ce}let s;const a=new gt;for(const o of this._def.checks)o.kind==="int"?Le.isInteger(t.data)||(s=this._getOrReturnCtx(t,s),pe(s,{code:ce.invalid_type,expected:"integer",received:"float",message:o.message}),a.dirty()):o.kind==="min"?(o.inclusive?t.data<o.value:t.data<=o.value)&&(s=this._getOrReturnCtx(t,s),pe(s,{code:ce.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),a.dirty()):o.kind==="max"?(o.inclusive?t.data>o.value:t.data>=o.value)&&(s=this._getOrReturnCtx(t,s),pe(s,{code:ce.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),a.dirty()):o.kind==="multipleOf"?Op(t.data,o.value)!==0&&(s=this._getOrReturnCtx(t,s),pe(s,{code:ce.not_multiple_of,multipleOf:o.value,message:o.message}),a.dirty()):o.kind==="finite"?Number.isFinite(t.data)||(s=this._getOrReturnCtx(t,s),pe(s,{code:ce.not_finite,message:o.message}),a.dirty()):Le.assertNever(o);return{status:a.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,ve.toString(n))}gt(t,n){return this.setLimit("min",t,!1,ve.toString(n))}lte(t,n){return this.setLimit("max",t,!0,ve.toString(n))}lt(t,n){return this.setLimit("max",t,!1,ve.toString(n))}setLimit(t,n,s,a){return new Er({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:s,message:ve.toString(a)}]})}_addCheck(t){return new Er({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:ve.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:ve.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:ve.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:ve.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:ve.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:ve.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:ve.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:ve.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:ve.toString(t)})}get minValue(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&Le.isInteger(t.value))}get isFinite(){let t=null,n=null;for(const s of this._def.checks){if(s.kind==="finite"||s.kind==="int"||s.kind==="multipleOf")return!0;s.kind==="min"?(n===null||s.value>n)&&(n=s.value):s.kind==="max"&&(t===null||s.value<t)&&(t=s.value)}return Number.isFinite(n)&&Number.isFinite(t)}}Er.create=e=>new Er({checks:[],typeName:we.ZodNumber,coerce:(e==null?void 0:e.coerce)||!1,...Te(e)});class zs extends $e{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==ge.bigint)return this._getInvalidInput(t);let s;const a=new gt;for(const o of this._def.checks)o.kind==="min"?(o.inclusive?t.data<o.value:t.data<=o.value)&&(s=this._getOrReturnCtx(t,s),pe(s,{code:ce.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),a.dirty()):o.kind==="max"?(o.inclusive?t.data>o.value:t.data>=o.value)&&(s=this._getOrReturnCtx(t,s),pe(s,{code:ce.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),a.dirty()):o.kind==="multipleOf"?t.data%o.value!==BigInt(0)&&(s=this._getOrReturnCtx(t,s),pe(s,{code:ce.not_multiple_of,multipleOf:o.value,message:o.message}),a.dirty()):Le.assertNever(o);return{status:a.value,value:t.data}}_getInvalidInput(t){const n=this._getOrReturnCtx(t);return pe(n,{code:ce.invalid_type,expected:ge.bigint,received:n.parsedType}),Ce}gte(t,n){return this.setLimit("min",t,!0,ve.toString(n))}gt(t,n){return this.setLimit("min",t,!1,ve.toString(n))}lte(t,n){return this.setLimit("max",t,!0,ve.toString(n))}lt(t,n){return this.setLimit("max",t,!1,ve.toString(n))}setLimit(t,n,s,a){return new zs({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:s,message:ve.toString(a)}]})}_addCheck(t){return new zs({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:ve.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:ve.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:ve.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:ve.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:ve.toString(n)})}get minValue(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}}zs.create=e=>new zs({checks:[],typeName:we.ZodBigInt,coerce:(e==null?void 0:e.coerce)??!1,...Te(e)});class pd extends $e{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==ge.boolean){const s=this._getOrReturnCtx(t);return pe(s,{code:ce.invalid_type,expected:ge.boolean,received:s.parsedType}),Ce}return $t(t.data)}}pd.create=e=>new pd({typeName:we.ZodBoolean,coerce:(e==null?void 0:e.coerce)||!1,...Te(e)});class Ha extends $e{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==ge.date){const o=this._getOrReturnCtx(t);return pe(o,{code:ce.invalid_type,expected:ge.date,received:o.parsedType}),Ce}if(Number.isNaN(t.data.getTime())){const o=this._getOrReturnCtx(t);return pe(o,{code:ce.invalid_date}),Ce}const s=new gt;let a;for(const o of this._def.checks)o.kind==="min"?t.data.getTime()<o.value&&(a=this._getOrReturnCtx(t,a),pe(a,{code:ce.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),s.dirty()):o.kind==="max"?t.data.getTime()>o.value&&(a=this._getOrReturnCtx(t,a),pe(a,{code:ce.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),s.dirty()):Le.assertNever(o);return{status:s.value,value:new Date(t.data.getTime())}}_addCheck(t){return new Ha({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:ve.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:ve.toString(n)})}get minDate(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t!=null?new Date(t):null}}Ha.create=e=>new Ha({checks:[],coerce:(e==null?void 0:e.coerce)||!1,typeName:we.ZodDate,...Te(e)});class md extends $e{_parse(t){if(this._getType(t)!==ge.symbol){const s=this._getOrReturnCtx(t);return pe(s,{code:ce.invalid_type,expected:ge.symbol,received:s.parsedType}),Ce}return $t(t.data)}}md.create=e=>new md({typeName:we.ZodSymbol,...Te(e)});class gd extends $e{_parse(t){if(this._getType(t)!==ge.undefined){const s=this._getOrReturnCtx(t);return pe(s,{code:ce.invalid_type,expected:ge.undefined,received:s.parsedType}),Ce}return $t(t.data)}}gd.create=e=>new gd({typeName:we.ZodUndefined,...Te(e)});class vd extends $e{_parse(t){if(this._getType(t)!==ge.null){const s=this._getOrReturnCtx(t);return pe(s,{code:ce.invalid_type,expected:ge.null,received:s.parsedType}),Ce}return $t(t.data)}}vd.create=e=>new vd({typeName:we.ZodNull,...Te(e)});class Si extends $e{constructor(){super(...arguments),this._any=!0}_parse(t){return $t(t.data)}}Si.create=e=>new Si({typeName:we.ZodAny,...Te(e)});class bd extends $e{constructor(){super(...arguments),this._unknown=!0}_parse(t){return $t(t.data)}}bd.create=e=>new bd({typeName:we.ZodUnknown,...Te(e)});class Nn extends $e{_parse(t){const n=this._getOrReturnCtx(t);return pe(n,{code:ce.invalid_type,expected:ge.never,received:n.parsedType}),Ce}}Nn.create=e=>new Nn({typeName:we.ZodNever,...Te(e)});class yd extends $e{_parse(t){if(this._getType(t)!==ge.undefined){const s=this._getOrReturnCtx(t);return pe(s,{code:ce.invalid_type,expected:ge.void,received:s.parsedType}),Ce}return $t(t.data)}}yd.create=e=>new yd({typeName:we.ZodVoid,...Te(e)});class Kt extends $e{_parse(t){const{ctx:n,status:s}=this._processInputParams(t),a=this._def;if(n.parsedType!==ge.array)return pe(n,{code:ce.invalid_type,expected:ge.array,received:n.parsedType}),Ce;if(a.exactLength!==null){const i=n.data.length>a.exactLength.value,l=n.data.length<a.exactLength.value;(i||l)&&(pe(n,{code:i?ce.too_big:ce.too_small,minimum:l?a.exactLength.value:void 0,maximum:i?a.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:a.exactLength.message}),s.dirty())}if(a.minLength!==null&&n.data.length<a.minLength.value&&(pe(n,{code:ce.too_small,minimum:a.minLength.value,type:"array",inclusive:!0,exact:!1,message:a.minLength.message}),s.dirty()),a.maxLength!==null&&n.data.length>a.maxLength.value&&(pe(n,{code:ce.too_big,maximum:a.maxLength.value,type:"array",inclusive:!0,exact:!1,message:a.maxLength.message}),s.dirty()),n.common.async)return Promise.all([...n.data].map((i,l)=>a.type._parseAsync(new jt(n,i,n.path,l)))).then(i=>gt.mergeArray(s,i));const o=[...n.data].map((i,l)=>a.type._parseSync(new jt(n,i,n.path,l)));return gt.mergeArray(s,o)}get element(){return this._def.type}min(t,n){return new Kt({...this._def,minLength:{value:t,message:ve.toString(n)}})}max(t,n){return new Kt({...this._def,maxLength:{value:t,message:ve.toString(n)}})}length(t,n){return new Kt({...this._def,exactLength:{value:t,message:ve.toString(n)}})}nonempty(t){return this.min(1,t)}}Kt.create=(e,t)=>new Kt({type:e,minLength:null,maxLength:null,exactLength:null,typeName:we.ZodArray,...Te(t)});function Lr(e){if(e instanceof Je){const t={};for(const n in e.shape){const s=e.shape[n];t[n]=Tn.create(Lr(s))}return new Je({...e._def,shape:()=>t})}else return e instanceof Kt?new Kt({...e._def,type:Lr(e.element)}):e instanceof Tn?Tn.create(Lr(e.unwrap())):e instanceof Br?Br.create(Lr(e.unwrap())):e instanceof Vn?Vn.create(e.items.map(t=>Lr(t))):e}class Je extends $e{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const t=this._def.shape(),n=Le.objectKeys(t);return this._cached={shape:t,keys:n},this._cached}_parse(t){if(this._getType(t)!==ge.object){const d=this._getOrReturnCtx(t);return pe(d,{code:ce.invalid_type,expected:ge.object,received:d.parsedType}),Ce}const{status:s,ctx:a}=this._processInputParams(t),{shape:o,keys:i}=this._getCached(),l=[];if(!(this._def.catchall instanceof Nn&&this._def.unknownKeys==="strip"))for(const d in a.data)i.includes(d)||l.push(d);const c=[];for(const d of i){const h=o[d],p=a.data[d];c.push({key:{status:"valid",value:d},value:h._parse(new jt(a,p,a.path,d)),alwaysSet:d in a.data})}if(this._def.catchall instanceof Nn){const d=this._def.unknownKeys;if(d==="passthrough")for(const h of l)c.push({key:{status:"valid",value:h},value:{status:"valid",value:a.data[h]}});else if(d==="strict")l.length>0&&(pe(a,{code:ce.unrecognized_keys,keys:l}),s.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const d=this._def.catchall;for(const h of l){const p=a.data[h];c.push({key:{status:"valid",value:h},value:d._parse(new jt(a,p,a.path,h)),alwaysSet:h in a.data})}}return a.common.async?Promise.resolve().then(async()=>{const d=[];for(const h of c){const p=await h.key,f=await h.value;d.push({key:p,value:f,alwaysSet:h.alwaysSet})}return d}).then(d=>gt.mergeObjectSync(s,d)):gt.mergeObjectSync(s,c)}get shape(){return this._def.shape()}strict(t){return ve.errToObj,new Je({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,s)=>{var o,i;const a=((i=(o=this._def).errorMap)==null?void 0:i.call(o,n,s).message)??s.defaultError;return n.code==="unrecognized_keys"?{message:ve.errToObj(t).message??a}:{message:a}}}:{}})}strip(){return new Je({...this._def,unknownKeys:"strip"})}passthrough(){return new Je({...this._def,unknownKeys:"passthrough"})}extend(t){return new Je({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new Je({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:we.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new Je({...this._def,catchall:t})}pick(t){const n={};for(const s of Le.objectKeys(t))t[s]&&this.shape[s]&&(n[s]=this.shape[s]);return new Je({...this._def,shape:()=>n})}omit(t){const n={};for(const s of Le.objectKeys(this.shape))t[s]||(n[s]=this.shape[s]);return new Je({...this._def,shape:()=>n})}deepPartial(){return Lr(this)}partial(t){const n={};for(const s of Le.objectKeys(this.shape)){const a=this.shape[s];t&&!t[s]?n[s]=a:n[s]=a.optional()}return new Je({...this._def,shape:()=>n})}required(t){const n={};for(const s of Le.objectKeys(this.shape))if(t&&!t[s])n[s]=this.shape[s];else{let o=this.shape[s];for(;o instanceof Tn;)o=o._def.innerType;n[s]=o}return new Je({...this._def,shape:()=>n})}keyof(){return kd(Le.objectKeys(this.shape))}}Je.create=(e,t)=>new Je({shape:()=>e,unknownKeys:"strip",catchall:Nn.create(),typeName:we.ZodObject,...Te(t)}),Je.strictCreate=(e,t)=>new Je({shape:()=>e,unknownKeys:"strict",catchall:Nn.create(),typeName:we.ZodObject,...Te(t)}),Je.lazycreate=(e,t)=>new Je({shape:e,unknownKeys:"strip",catchall:Nn.create(),typeName:we.ZodObject,...Te(t)});class Va extends $e{_parse(t){const{ctx:n}=this._processInputParams(t),s=this._def.options;function a(o){for(const l of o)if(l.result.status==="valid")return l.result;for(const l of o)if(l.result.status==="dirty")return n.common.issues.push(...l.ctx.common.issues),l.result;const i=o.map(l=>new sn(l.ctx.common.issues));return pe(n,{code:ce.invalid_union,unionErrors:i}),Ce}if(n.common.async)return Promise.all(s.map(async o=>{const i={...n,common:{...n.common,issues:[]},parent:null};return{result:await o._parseAsync({data:n.data,path:n.path,parent:i}),ctx:i}})).then(a);{let o;const i=[];for(const c of s){const d={...n,common:{...n.common,issues:[]},parent:null},h=c._parseSync({data:n.data,path:n.path,parent:d});if(h.status==="valid")return h;h.status==="dirty"&&!o&&(o={result:h,ctx:d}),d.common.issues.length&&i.push(d.common.issues)}if(o)return n.common.issues.push(...o.ctx.common.issues),o.result;const l=i.map(c=>new sn(c));return pe(n,{code:ce.invalid_union,unionErrors:l}),Ce}}get options(){return this._def.options}}Va.create=(e,t)=>new Va({options:e,typeName:we.ZodUnion,...Te(t)});function ki(e,t){const n=xn(e),s=xn(t);if(e===t)return{valid:!0,data:e};if(n===ge.object&&s===ge.object){const a=Le.objectKeys(t),o=Le.objectKeys(e).filter(l=>a.indexOf(l)!==-1),i={...e,...t};for(const l of o){const c=ki(e[l],t[l]);if(!c.valid)return{valid:!1};i[l]=c.data}return{valid:!0,data:i}}else if(n===ge.array&&s===ge.array){if(e.length!==t.length)return{valid:!1};const a=[];for(let o=0;o<e.length;o++){const i=e[o],l=t[o],c=ki(i,l);if(!c.valid)return{valid:!1};a.push(c.data)}return{valid:!0,data:a}}else return n===ge.date&&s===ge.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}class qa extends $e{_parse(t){const{status:n,ctx:s}=this._processInputParams(t),a=(o,i)=>{if(cd(o)||cd(i))return Ce;const l=ki(o.value,i.value);return l.valid?((dd(o)||dd(i))&&n.dirty(),{status:n.value,value:l.data}):(pe(s,{code:ce.invalid_intersection_types}),Ce)};return s.common.async?Promise.all([this._def.left._parseAsync({data:s.data,path:s.path,parent:s}),this._def.right._parseAsync({data:s.data,path:s.path,parent:s})]).then(([o,i])=>a(o,i)):a(this._def.left._parseSync({data:s.data,path:s.path,parent:s}),this._def.right._parseSync({data:s.data,path:s.path,parent:s}))}}qa.create=(e,t,n)=>new qa({left:e,right:t,typeName:we.ZodIntersection,...Te(n)});class Vn extends $e{_parse(t){const{status:n,ctx:s}=this._processInputParams(t);if(s.parsedType!==ge.array)return pe(s,{code:ce.invalid_type,expected:ge.array,received:s.parsedType}),Ce;if(s.data.length<this._def.items.length)return pe(s,{code:ce.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Ce;!this._def.rest&&s.data.length>this._def.items.length&&(pe(s,{code:ce.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const o=[...s.data].map((i,l)=>{const c=this._def.items[l]||this._def.rest;return c?c._parse(new jt(s,i,s.path,l)):null}).filter(i=>!!i);return s.common.async?Promise.all(o).then(i=>gt.mergeArray(n,i)):gt.mergeArray(n,o)}get items(){return this._def.items}rest(t){return new Vn({...this._def,rest:t})}}Vn.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Vn({items:e,typeName:we.ZodTuple,rest:null,...Te(t)})};class ja extends $e{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:n,ctx:s}=this._processInputParams(t);if(s.parsedType!==ge.object)return pe(s,{code:ce.invalid_type,expected:ge.object,received:s.parsedType}),Ce;const a=[],o=this._def.keyType,i=this._def.valueType;for(const l in s.data)a.push({key:o._parse(new jt(s,l,s.path,l)),value:i._parse(new jt(s,s.data[l],s.path,l)),alwaysSet:l in s.data});return s.common.async?gt.mergeObjectAsync(n,a):gt.mergeObjectSync(n,a)}get element(){return this._def.valueType}static create(t,n,s){return n instanceof $e?new ja({keyType:t,valueType:n,typeName:we.ZodRecord,...Te(s)}):new ja({keyType:an.create(),valueType:t,typeName:we.ZodRecord,...Te(n)})}}class _d extends $e{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:n,ctx:s}=this._processInputParams(t);if(s.parsedType!==ge.map)return pe(s,{code:ce.invalid_type,expected:ge.map,received:s.parsedType}),Ce;const a=this._def.keyType,o=this._def.valueType,i=[...s.data.entries()].map(([l,c],d)=>({key:a._parse(new jt(s,l,s.path,[d,"key"])),value:o._parse(new jt(s,c,s.path,[d,"value"]))}));if(s.common.async){const l=new Map;return Promise.resolve().then(async()=>{for(const c of i){const d=await c.key,h=await c.value;if(d.status==="aborted"||h.status==="aborted")return Ce;(d.status==="dirty"||h.status==="dirty")&&n.dirty(),l.set(d.value,h.value)}return{status:n.value,value:l}})}else{const l=new Map;for(const c of i){const d=c.key,h=c.value;if(d.status==="aborted"||h.status==="aborted")return Ce;(d.status==="dirty"||h.status==="dirty")&&n.dirty(),l.set(d.value,h.value)}return{status:n.value,value:l}}}}_d.create=(e,t,n)=>new _d({valueType:t,keyType:e,typeName:we.ZodMap,...Te(n)});class Gs extends $e{_parse(t){const{status:n,ctx:s}=this._processInputParams(t);if(s.parsedType!==ge.set)return pe(s,{code:ce.invalid_type,expected:ge.set,received:s.parsedType}),Ce;const a=this._def;a.minSize!==null&&s.data.size<a.minSize.value&&(pe(s,{code:ce.too_small,minimum:a.minSize.value,type:"set",inclusive:!0,exact:!1,message:a.minSize.message}),n.dirty()),a.maxSize!==null&&s.data.size>a.maxSize.value&&(pe(s,{code:ce.too_big,maximum:a.maxSize.value,type:"set",inclusive:!0,exact:!1,message:a.maxSize.message}),n.dirty());const o=this._def.valueType;function i(c){const d=new Set;for(const h of c){if(h.status==="aborted")return Ce;h.status==="dirty"&&n.dirty(),d.add(h.value)}return{status:n.value,value:d}}const l=[...s.data.values()].map((c,d)=>o._parse(new jt(s,c,s.path,d)));return s.common.async?Promise.all(l).then(c=>i(c)):i(l)}min(t,n){return new Gs({...this._def,minSize:{value:t,message:ve.toString(n)}})}max(t,n){return new Gs({...this._def,maxSize:{value:t,message:ve.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}}Gs.create=(e,t)=>new Gs({valueType:e,minSize:null,maxSize:null,typeName:we.ZodSet,...Te(t)});class wd extends $e{get schema(){return this._def.getter()}_parse(t){const{ctx:n}=this._processInputParams(t);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}}wd.create=(e,t)=>new wd({getter:e,typeName:we.ZodLazy,...Te(t)});class Sd extends $e{_parse(t){if(t.data!==this._def.value){const n=this._getOrReturnCtx(t);return pe(n,{received:n.data,code:ce.invalid_literal,expected:this._def.value}),Ce}return{status:"valid",value:t.data}}get value(){return this._def.value}}Sd.create=(e,t)=>new Sd({value:e,typeName:we.ZodLiteral,...Te(t)});function kd(e,t){return new Mr({values:e,typeName:we.ZodEnum,...Te(t)})}class Mr extends $e{_parse(t){if(typeof t.data!="string"){const n=this._getOrReturnCtx(t),s=this._def.values;return pe(n,{expected:Le.joinValues(s),received:n.parsedType,code:ce.invalid_type}),Ce}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){const n=this._getOrReturnCtx(t),s=this._def.values;return pe(n,{received:n.data,code:ce.invalid_enum_value,options:s}),Ce}return $t(t.data)}get options(){return this._def.values}get enum(){const t={};for(const n of this._def.values)t[n]=n;return t}get Values(){const t={};for(const n of this._def.values)t[n]=n;return t}get Enum(){const t={};for(const n of this._def.values)t[n]=n;return t}extract(t,n=this._def){return Mr.create(t,{...this._def,...n})}exclude(t,n=this._def){return Mr.create(this.options.filter(s=>!t.includes(s)),{...this._def,...n})}}Mr.create=kd;class Cd extends $e{_parse(t){const n=Le.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(t);if(s.parsedType!==ge.string&&s.parsedType!==ge.number){const a=Le.objectValues(n);return pe(s,{expected:Le.joinValues(a),received:s.parsedType,code:ce.invalid_type}),Ce}if(this._cache||(this._cache=new Set(Le.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){const a=Le.objectValues(n);return pe(s,{received:s.data,code:ce.invalid_enum_value,options:a}),Ce}return $t(t.data)}get enum(){return this._def.values}}Cd.create=(e,t)=>new Cd({values:e,typeName:we.ZodNativeEnum,...Te(t)});class Ka extends $e{unwrap(){return this._def.type}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==ge.promise&&n.common.async===!1)return pe(n,{code:ce.invalid_type,expected:ge.promise,received:n.parsedType}),Ce;const s=n.parsedType===ge.promise?n.data:Promise.resolve(n.data);return $t(s.then(a=>this._def.type.parseAsync(a,{path:n.path,errorMap:n.common.contextualErrorMap})))}}Ka.create=(e,t)=>new Ka({type:e,typeName:we.ZodPromise,...Te(t)});class Dr extends $e{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===we.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:n,ctx:s}=this._processInputParams(t),a=this._def.effect||null,o={addIssue:i=>{pe(s,i),i.fatal?n.abort():n.dirty()},get path(){return s.path}};if(o.addIssue=o.addIssue.bind(o),a.type==="preprocess"){const i=a.transform(s.data,o);if(s.common.async)return Promise.resolve(i).then(async l=>{if(n.value==="aborted")return Ce;const c=await this._def.schema._parseAsync({data:l,path:s.path,parent:s});return c.status==="aborted"?Ce:c.status==="dirty"||n.value==="dirty"?Us(c.value):c});{if(n.value==="aborted")return Ce;const l=this._def.schema._parseSync({data:i,path:s.path,parent:s});return l.status==="aborted"?Ce:l.status==="dirty"||n.value==="dirty"?Us(l.value):l}}if(a.type==="refinement"){const i=l=>{const c=a.refinement(l,o);if(s.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return l};if(s.common.async===!1){const l=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});return l.status==="aborted"?Ce:(l.status==="dirty"&&n.dirty(),i(l.value),{status:n.value,value:l.value})}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(l=>l.status==="aborted"?Ce:(l.status==="dirty"&&n.dirty(),i(l.value).then(()=>({status:n.value,value:l.value}))))}if(a.type==="transform")if(s.common.async===!1){const i=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(!$r(i))return Ce;const l=a.transform(i.value,o);if(l instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:l}}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(i=>$r(i)?Promise.resolve(a.transform(i.value,o)).then(l=>({status:n.value,value:l})):Ce);Le.assertNever(a)}}Dr.create=(e,t,n)=>new Dr({schema:e,typeName:we.ZodEffects,effect:t,...Te(n)}),Dr.createWithPreprocess=(e,t,n)=>new Dr({schema:t,effect:{type:"preprocess",transform:e},typeName:we.ZodEffects,...Te(n)});class Tn extends $e{_parse(t){return this._getType(t)===ge.undefined?$t(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Tn.create=(e,t)=>new Tn({innerType:e,typeName:we.ZodOptional,...Te(t)});class Br extends $e{_parse(t){return this._getType(t)===ge.null?$t(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Br.create=(e,t)=>new Br({innerType:e,typeName:we.ZodNullable,...Te(t)});class Ci extends $e{_parse(t){const{ctx:n}=this._processInputParams(t);let s=n.data;return n.parsedType===ge.undefined&&(s=this._def.defaultValue()),this._def.innerType._parse({data:s,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}Ci.create=(e,t)=>new Ci({innerType:e,typeName:we.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...Te(t)});class xi extends $e{_parse(t){const{ctx:n}=this._processInputParams(t),s={...n,common:{...n.common,issues:[]}},a=this._def.innerType._parse({data:s.data,path:s.path,parent:{...s}});return Wa(a)?a.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new sn(s.common.issues)},input:s.data})})):{status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new sn(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}}xi.create=(e,t)=>new xi({innerType:e,typeName:we.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...Te(t)});class xd extends $e{_parse(t){if(this._getType(t)!==ge.nan){const s=this._getOrReturnCtx(t);return pe(s,{code:ce.invalid_type,expected:ge.nan,received:s.parsedType}),Ce}return{status:"valid",value:t.data}}}xd.create=e=>new xd({typeName:we.ZodNaN,...Te(e)});class Pp extends $e{_parse(t){const{ctx:n}=this._processInputParams(t),s=n.data;return this._def.type._parse({data:s,path:n.path,parent:n})}unwrap(){return this._def.type}}class Ni extends $e{_parse(t){const{status:n,ctx:s}=this._processInputParams(t);if(s.common.async)return(async()=>{const o=await this._def.in._parseAsync({data:s.data,path:s.path,parent:s});return o.status==="aborted"?Ce:o.status==="dirty"?(n.dirty(),Us(o.value)):this._def.out._parseAsync({data:o.value,path:s.path,parent:s})})();{const a=this._def.in._parseSync({data:s.data,path:s.path,parent:s});return a.status==="aborted"?Ce:a.status==="dirty"?(n.dirty(),{status:"dirty",value:a.value}):this._def.out._parseSync({data:a.value,path:s.path,parent:s})}}static create(t,n){return new Ni({in:t,out:n,typeName:we.ZodPipeline})}}class Ti extends $e{_parse(t){const n=this._def.innerType._parse(t),s=a=>($r(a)&&(a.value=Object.freeze(a.value)),a);return Wa(n)?n.then(a=>s(a)):s(n)}unwrap(){return this._def.innerType}}Ti.create=(e,t)=>new Ti({innerType:e,typeName:we.ZodReadonly,...Te(t)});var we;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(we||(we={}));const Ke=an.create,Ai=Er.create,Ya=Si.create;Nn.create;const Ii=Kt.create,Ws=Je.create;Va.create,qa.create,Vn.create;const Nd=ja.create;Mr.create,Ka.create,Tn.create,Br.create;const Td=["access","equity","quality","resiliency","governance"],Fp=Ws({activeSnapshotId:Ke().min(1,"activeSnapshotId is required"),publishedAt:Ke().min(1,"publishedAt is required"),nodeIds:Ii(Ke()).min(1,"nodeIds cannot be empty"),schemaVersion:Ai().int().positive()}),Up=Ws({nodeId:Ke(),version:Ai(),sections:Ii(Ya()),updatedAt:Ke()});Ws({chartId:Ke(),title:Ke(),subtitle:Ke().optional(),unit:Ke().optional(),asOfDate:Ke(),chartType:Ke(),sanitizedCsvContent:Ke().optional()}).passthrough(),Ws({pointId:Ke(),folderUrl:Ke().optional(),folderTitle:Ke().optional(),description:Ke().optional(),lastSyncedAt:Ke().optional(),items:Ii(Ya()).optional()}).passthrough();const zp=Ws({nodeId:Ke().min(1,"nodeId is required"),snapshotId:Ke().min(1,"snapshotId is required"),version:Ai().int().nonnegative(),updatedAt:Ke().min(1,"updatedAt is required"),canvas:Up,chartDatasets:Nd(Ke(),Ya()),sourceMetadata:Nd(Ke(),Ya())});function Gp(e){return e.type==="section"}function Ad(e){return e.type==="subsection"}function Wp(e){return e.type==="text"||e.type==="photo"||e.type==="gallery"||e.type==="chart"}function Hp(e){return e.type==="text"}function $i(e){return e.type==="photo"}function Vp(e){return e.type==="gallery"}function qp(e){return e.type==="chart"}const qn=[320,400,600,800,1200,1600],Ei=800,Li=/^[a-zA-Z0-9_-]{10,64}$/;function Id(e){if(typeof e!="number"||isNaN(e)||e<=0)return Ei;if(e<=qn[0])return qn[0];if(e>=qn[qn.length-1])return qn[qn.length-1];let t=Ei,n=1/0;for(const s of qn){const a=Math.abs(s-e);a<=n&&(n=a,t=s)}return t}function on(e){if(!e||typeof e!="string")return null;const t=e.trim();if(Li.test(t))return t;const n=t.match(/[?&]id=([a-zA-Z0-9_-]{10,64})/);if(n!=null&&n[1]&&Li.test(n[1]))return n[1];const s=t.match(/\/(?:d|folders)\/([a-zA-Z0-9_-]{10,64})/);return s!=null&&s[1]&&Li.test(s[1])?s[1]:null}function ln(e,t={}){const n=on(e);if(!n)return e||"";const s=Id(t.width??Ei),a=`/api/media/drive/${n}?w=${s}`;return t.format&&t.format!=="auto"?`${a}&fmt=${t.format}`:a}function Mi(e,t=[400,800,1200,1600]){const n=on(e);return n?t.map(s=>{const a=Id(s);return`${ln(n,{width:a})} ${a}w`}).join(", "):""}const Di=[{chartId:"chart-access-enrolment",title:"Cluster Throughput & Ingestion Rate",subtitle:"Real-time telemetry distribution across processing nodes (ops/sec)",unit:"ops/s",asOfDate:"2026-Q1",chartType:"bar",nodeId:"access",visualConfig:{unit:"ops/s",excludeSummaryRows:!0,yMin:0,orientation:"vertical",barOrientation:"vertical"},categories:["Cluster Alpha","Cluster Beta","Cluster Gamma","Cluster Delta","Cluster Epsilon","Cluster Zeta"],series:[{name:"Ingress Stream",data:[420,510,630,590,710,680],color:"#0284c7"},{name:"Egress Sync",data:[390,480,580,560,670,640],color:"#38bdf8"}],sanitizedCsvContent:`# Title: Cluster Throughput & Ingestion Rate (ops/s)
2
- Category,Ingress Stream,Egress Sync
3
- Cluster Alpha,420,390
4
- Cluster Beta,510,480
5
- Cluster Gamma,630,580
6
- Cluster Delta,590,560
7
- Cluster Epsilon,710,670
8
- Cluster Zeta,680,640`},{chartId:"chart-equity-assistance",title:"Compute & Memory Allocation Ratios",subtitle:"Resource distribution percentage across core engine subsystems",unit:"%",asOfDate:"2026-Q1",chartType:"donut",nodeId:"equity",visualConfig:{unit:"%",excludeSummaryRows:!0,donutVariant:"donut"},categories:["AST Parser","Bézier Coordinate Engine","Vector Chart Studio","Storage & Cache Tier","Coordinator Chrome"],series:[{name:"Allocation",data:[32,26,20,14,8],color:"#881337"}],sanitizedCsvContent:`# Title: Compute & Memory Allocation Ratios (%)
9
- Category,Allocation
10
- AST Parser,32
11
- Bézier Coordinate Engine,26
12
- Vector Chart Studio,20
13
- Storage & Cache Tier,14
14
- Coordinator Chrome,8`},{chartId:"chart-quality-mps",title:"Response Latency Benchmarks (P95 vs P99)",subtitle:"Query execution time across quarterly release versions",unit:"ms",asOfDate:"2026-Q1",chartType:"line",nodeId:"quality",visualConfig:{unit:"ms",excludeSummaryRows:!0,yMin:0,curveInterpolation:"smooth",showAreaFill:!0},categories:["v2.0","v2.1","v2.2","v2.3","v2.4"],series:[{name:"P95 Latency",data:[48,41,33,26,19],color:"#f59e0b"},{name:"P99 Latency",data:[82,69,54,42,31],color:"#b45309"}],sanitizedCsvContent:`# Title: Response Latency Benchmarks (ms)
15
- Version,P95 Latency,P99 Latency
16
- v2.0,48,82
17
- v2.1,41,69
18
- v2.2,33,54
19
- v2.3,26,42
20
- v2.4,19,31`},{chartId:"chart-resiliency-drrm",title:"Failover Recovery Switchover Durations",subtitle:"Distribution of automated cluster recovery durations under partition",unit:"ms",asOfDate:"2026-Q1",chartType:"bar",nodeId:"resiliency",visualConfig:{unit:"ms",excludeSummaryRows:!0,yMin:0},categories:["0-10ms","10-20ms","20-30ms","30-40ms","40-50ms",">50ms"],series:[{name:"Failover Incidents",data:[142,89,45,12,4,1],color:"#15803d"}],sanitizedCsvContent:`# Title: Failover Recovery Switchover Durations (ms)
21
- Bucket,Failover Incidents
22
- 0-10ms,142
23
- 10-20ms,89
24
- 20-30ms,45
25
- 30-40ms,12
26
- 40-50ms,4
27
- >50ms,1`},{chartId:"chart-governance-mooe",title:"Audit Trail Events & Edge Publication Volume",subtitle:"Verified configuration commits and cryptographic publications per week",unit:"events",asOfDate:"2026-Q1",chartType:"bar",nodeId:"governance",visualConfig:{unit:"events",excludeSummaryRows:!0,yMin:0},categories:["Week 1","Week 2","Week 3","Week 4","Week 5","Week 6"],series:[{name:"Audit Events",data:[120,145,160,185,210,230],color:"#d97706"},{name:"Edge Publications",data:[18,22,28,31,35,42],color:"#b45309"}],sanitizedCsvContent:`# Title: Audit Trail Events & Edge Publication Volume (events)
28
- Week,Audit Events,Edge Publications
29
- Week 1,120,18
30
- Week 2,145,22
31
- Week 3,160,28
32
- Week 4,185,31
33
- Week 5,210,35
34
- Week 6,230,42`}],Bi={},jp=[400,800,1600],Kp="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 800px",Yp="16/9";function An(e){if(typeof process<"u"&&(process!=null&&process.env))return process.env[e]}function Zp(e){if(!e||!Array.isArray(e.sections))return e;const t=JSON.parse(JSON.stringify(e));return t.sections=t.sections.map(n=>{if(!n||!Array.isArray(n.elements))return n;const s=n.elements.map(a=>{if(Ad(a)){const o=a;if(Array.isArray(o.elements)){const i=o.elements.map(l=>$i(l)?$d(l):l);return{...o,elements:i}}return o}return $i(a)?$d(a):a});return{...n,elements:s}}),t}function $d(e){if(!e.src||typeof e.src!="string")return e;const t=e.src.trim(),n=on(t);if(!n)return e;const s=ln(n,{width:800}),a=Mi(n,jp),o=e.sizes||Kp,i=e.aspectRatio||Yp;return{...e,src:s,srcSet:a,sizes:o,aspectRatio:i,rawDriveUrl:e.rawDriveUrl||t}}function Xp(e,t){const n={};if(Array.isArray(Di))for(const s of Di)s&&s.chartId&&(!s.nodeId||s.nodeId.toLowerCase()===e.toLowerCase())&&(n[s.chartId]=s);return n}function Jp(e,t){const n={},s=Bi;if(s&&typeof s=="object")for(const[a,o]of Object.entries(s))a.toLowerCase().includes(e.toLowerCase())&&(n[a]={pointId:a,folderUrl:o.folderUrl,folderTitle:o.folderTitle,description:o.description,lastSyncedAt:o.lastVerified});return n}function Qp(e,t,n){var c;const s=((c=t.canvases)==null?void 0:c[e])||{nodeId:e,version:t.schemaVersion||1,sections:[],updatedAt:t.createdAt},a=Zp(s),o=Xp(e),i=Jp(e),l={nodeId:e,snapshotId:t.id,version:t.schemaVersion||1,updatedAt:t.createdAt,canvas:a,chartDatasets:o,sourceMetadata:i};return zp.parse(l),l}function Rp(e,t){const n=t&&t.length>0?t:e.canvases&&Object.keys(e.canvases).length>0?Object.keys(e.canvases):[...Td],s={activeSnapshotId:e.id,publishedAt:e.createdAt,nodeIds:n,schemaVersion:e.schemaVersion||1};return Fp.parse(s),s}async function em(e,t){const n=An("CLOUDFLARE_ACCOUNT_ID")||An("CF_ACCOUNT_ID"),s=An("CLOUDFLARE_KV_NAMESPACE_ID")||An("CF_KV_NAMESPACE_ID")||An("KV_ENGINE_PUBLIC_ID")||An("KV_PUBLIC_ID"),a=An("CLOUDFLARE_API_TOKEN")||An("CF_API_TOKEN");if(!n||!s||!a)return{success:!0,deployedCount:0,warning:`Cloudflare KV credentials (${[!n&&"account ID",!s&&"KV namespace ID",!a&&"API token"].filter(Boolean).join(", ")}) not configured. Skipped remote edge deployment (local fallback mode).`};const o=`https://api.cloudflare.com/client/v4/accounts/${n}/storage/kv/namespaces/${s}/bulk`;try{const i=await fetch(o,{method:"PUT",headers:{Authorization:`Bearer ${a}`,"Content-Type":"application/json"},body:JSON.stringify(e)});if(!i.ok){const l=await i.text();return console.warn(`[edgePreBakeService] Cloudflare KV bulk API returned HTTP ${i.status}:`,l),{success:!1,deployedCount:0,error:`Cloudflare KV upload returned HTTP ${i.status}: ${l}`}}return{success:!0,deployedCount:e.length}}catch(i){const l=i instanceof Error?i.message:"Network error during Cloudflare KV bulk deployment";return console.warn("[edgePreBakeService] Cloudflare KV bulk dispatch failure:",l),{success:!1,deployedCount:0,error:l}}}async function tm(e,t){const n=[],s=[],a=e.canvases&&Object.keys(e.canvases).length>0?Object.keys(e.canvases):[...Td];for(const l of a){const c=Qp(l,e),d=JSON.stringify(c);n.push({key:`node:${l}`,value:d}),s.push(l);for(const[h,p]of Object.entries(c.chartDatasets))n.push({key:`chart:${h}`,value:JSON.stringify(p)})}const o=Rp(e,a);n.push({key:"portal:manifest",value:JSON.stringify(o)});const i=await em(n);return{success:i.success,snapshotId:e.id,transformedNodes:s,totalKvKeys:n.length,deployResult:i}}function Ut(){const e=ys();return e.nodes&&e.nodes.length>0?e.nodes.map(t=>t.id):[...rn]}const Oi=e=>(e||Ae())+"_portal_sync",nm=Oi(),Or=e=>(e||Ae())+"_history_manifest",Pi=Or(),Pr=e=>(e||Ae())+"_live_active_published_id",rm=Pr(),Fr=Ae()+"_active_published_id",sm=Fr,Za="engine-history-change",Ur=1,Ed=20,Ld=6e4;let Yt=null,Md=0;function Xa(e,t){let n=0,s=0,a=0;for(const i of Object.values(e))if(!(!i||!Array.isArray(i.sections))){n+=i.sections.length;for(const l of i.sections)if(!(!l||!Array.isArray(l.elements)))for(const c of l.elements)if(c.type==="subsection"){s+=1;const d=c;Array.isArray(d.elements)&&(a+=d.elements.length)}else a+=1}const o=Object.keys(t||{}).length;return{totalSections:n,totalSubsections:s,totalLeafElements:a,totalTextOverrides:o}}function cn(){const e=Ee();if(!e)return"snap-system-baseline";const t=e.getItem(Pr());if(t)return t;const n=e.getItem(Fr);let s;try{const o=e.getItem(Or());if(o){const i=JSON.parse(o);s=(i==null?void 0:i.activePublishedId)||(i==null?void 0:i.activeMilestoneId)}}catch{}const a=n||s||"snap-system-baseline";try{e.setItem(Pr(),a),e.removeItem(Fr)}catch{}return a}function zr(e){const t=Ee();if(t)try{t.setItem(Pr(),e),t.removeItem(Fr)}catch{}}function Ja(e=!0){const t={};for(const a of Ut())t[a]=Ca(a);const n={},s=Xa(t,n);return{id:"snap-system-baseline",schemaVersion:Ur,title:"System Baseline (Default)",description:"Original the host application 6-Year Baseline.",createdAt:"2024-01-01T00:00:00.000Z",authorSessionId:"system",isActive:e,canvases:t,contentOverrides:n,summary:s}}async function Fi(){try{const e=await Lc(Pi);if(e&&Array.isArray(e.snapshots)&&e.snapshots.length>0)return Yt=e,dn(e),e}catch{}return zt()}function zt(){const e={snapshots:[],updatedAt:new Date().toISOString()},t=Ee();if(!t)return Yt||e;try{const n=t.getItem(Or());if(!n)return Yt||e;const s=JSON.parse(n);if(s&&Array.isArray(s.snapshots)){const a={lastRestoredId:s.lastRestoredId,snapshots:s.snapshots,updatedAt:s.updatedAt||s.lastUpdated||new Date().toISOString()};return Yt=Yt||a,Yt}}catch{}return Yt||e}function dn(e){const t={...e,updatedAt:e.updatedAt||new Date().toISOString()};Yt=t,Ec(Pi,t).catch(()=>{});const n=Ee();if(n){const s={version:Ur,lastUpdated:t.updatedAt,updatedAt:t.updatedAt,snapshots:t.snapshots.map(a=>({id:a.id,title:a.title||a.label||"Snapshot",label:a.label||a.title,createdAt:a.createdAt,type:a.type,notes:a.notes,authorSessionId:a.authorSessionId||a.author,author:a.author||a.authorSessionId,summary:a.summary,metricsSummary:a.metricsSummary||a.summary}))};try{n.setItem(Or(),JSON.stringify(s))}catch{try{const a={...s,snapshots:s.snapshots.filter(o=>o.type!=="autosave")};n.setItem(Or(),JSON.stringify(a))}catch{}}}if(typeof window<"u")try{window.dispatchEvent(new CustomEvent(Za,{detail:{manifest:t}}))}catch{}}function Dd(e){if(typeof window>"u")return()=>{};const t=n=>{var a;const s=n;(a=s==null?void 0:s.detail)!=null&&a.manifest?e(s.detail.manifest):e(zt())};return window.addEventListener(Za,t),()=>window.removeEventListener(Za,t)}function Qa(e,t="",n="milestone",s){const a={};for(const d of Ut())a[d]=Ft(d);const o=Ls(),i=Xa(a,o),l=s||ka();return{id:`snap-${Date.now()}-${n}-${Math.random().toString(36).substring(2,7)}`,schemaVersion:Ur,type:n,title:e.trim(),notes:t.trim(),createdAt:new Date().toISOString(),authorSessionId:l,canvases:a,contentOverrides:o,summary:i}}function am(e,t="",n){const s=Qa(e,t,"milestone",n),a=zt();return a.snapshots=[s,...a.snapshots],dn(a),s}function Ui(e){let t=0;return e.filter(n=>n.type!=="autosave"?!0:(t+=1,t<=Ed))}function om(e,t=!1){const n=Date.now();if(!t&&n-Md<Ld)return null;Md=n;const s=Qa("Auto-Save Checkpoint","","autosave",e),a=zt(),o=Ui([s,...a.snapshots]);return a.snapshots=o,dn(a),s}async function im(e){const t=zt(),n=t.snapshots.find(a=>a.id===e);if(!n)return{success:!1,error:`Snapshot ${e} not found`};const s=Qa("Pre-Restore Safety Backup",`Automatic safety backup before restoring "${n.title||n.id}"`,"safety_backup");for(const a of Ut()){const o=n.canvases[a];o&&Ps(o)}return Ia(n.contentOverrides||{}),Ar("live"),t.snapshots=[s,...t.snapshots],zr(n.id),dn(t),{success:!0,safetySnapshotId:s.id}}function lm(e){const t=zt(),n=t.snapshots.length;return t.snapshots=t.snapshots.filter(s=>s.id!==e),t.snapshots.length!==n?(dn(t),!0):!1}function cm(){Yt={snapshots:[],updatedAt:new Date().toISOString()},dn(Yt)}function dm(){const e=zt(),t={};for(const s of Ut())t[s]=Ft(s);const n={engineBackupVersion:Ur,exportedAt:new Date().toISOString(),tenant:"the host application",manifest:e,activeState:{canvases:t,contentOverrides:Ls()}};return JSON.stringify(n,null,2)}function um(e){try{const t=JSON.parse(e);let n=[];if(t&&Array.isArray(t.snapshots))n=t.snapshots;else if(t&&t.manifest&&Array.isArray(t.manifest.snapshots))n=t.manifest.snapshots;else return{success:!1,importedCount:0,error:"Invalid backup structure: missing snapshots array"};const s=n.filter(c=>c&&typeof c.id=="string"&&typeof c.title=="string"&&typeof c.type=="string"&&c.canvases&&typeof c.canvases=="object");if(s.length===0)return{success:!1,importedCount:0,error:"No valid snapshots found in backup file"};const a=zt(),o=new Set(a.snapshots.map(c=>c.id));let i=0;const l=[];for(const c of s)o.has(c.id)||(l.push(c),o.add(c.id),i+=1);return a.snapshots=Ui([...l,...a.snapshots]),dn(a),{success:!0,importedCount:i}}catch(t){return{success:!1,importedCount:0,error:`JSON parse error: ${t instanceof Error?t.message:"Invalid JSON file"}`}}}function zi(e){var t;try{kr(!0,e.id);const n=new Date().toISOString();for(const s of Ut()){const a=((t=e.canvases)==null?void 0:t[s])||Ca(s),o={...JSON.parse(JSON.stringify(a)),nodeId:s,sections:xt(a.sections||[]),updatedAt:n};Ma(s,o);const i=Ee();if(i)try{i.setItem(Sr(s),JSON.stringify(o))}catch{}}if(Ia(e.contentOverrides||{},!0),Ar("draft"),typeof window<"u"){for(const s of Ut()){const a=Ft(s,!0),o={nodeId:s,document:a};window.dispatchEvent(new CustomEvent(Tr,{detail:o}))}Fs(!0)}return kn(!0),Ba(),!0}catch(n){return console.warn("[historyService] Failed to restore snapshot to draft:",n),!1}}function In(){const e=zt(),t=cn(),n=e.snapshots.map(s=>{const a=s,o=typeof a.description=="string"?a.description:s.notes||"",i=s.id===t;return{id:s.id,schemaVersion:s.schemaVersion||1,title:s.title,description:o,createdAt:s.createdAt,authorSessionId:s.authorSessionId,isActive:i,canvases:s.canvases,contentOverrides:s.contentOverrides,summary:s.summary}});if(!n.some(s=>s.id==="snap-system-baseline")){const s=n.some(a=>a.isActive);n.push(Ja(!s))}if(!n.some(s=>s.isActive)&&n.length>0){const s=n.find(a=>a.id==="snap-system-baseline");s?s.isActive=!0:n[0].isActive=!0}return n}async function Bd(){const e=tt();if(!e||!It("engine_history"))return In();try{const t=await fetch(`${e.url}/rest/v1/engine_history?order=created_at.desc&select=*`,{method:"GET",headers:{apikey:e.anonKey,Authorization:`Bearer ${e.anonKey}`,"Content-Type":"application/json"}});if(t.status===404)return Ot("engine_history"),In();if(!t.ok)return console.warn(`[historyService] Supabase cloud fetch returned HTTP ${t.status}. Falling back to persistent local storage.`),In();const n=await t.json();if(!Array.isArray(n)||n.length===0)return In();const s=n.map(o=>{var i,l;return{id:o.id,schemaVersion:o.schema_version??1,title:o.title||"Published Version",description:o.description||"",createdAt:o.created_at||new Date().toISOString(),authorSessionId:o.author_session_id||"unknown",isActive:!!o.is_active,canvases:((i=o.snapshot_data)==null?void 0:i.canvases)||{},contentOverrides:((l=o.snapshot_data)==null?void 0:l.contentOverrides)||{},summary:o.summary||{totalSections:0,totalSubsections:0,totalLeafElements:0,totalTextOverrides:0}}});if(!s.some(o=>o.id==="snap-system-baseline")){const o=s.some(i=>i.isActive);s.push(Ja(!o))}const a=s.find(o=>o.isActive);return a&&zr(a.id),s}catch(t){return console.warn("[historyService] Cloud fetch error:",t),In()}}async function Od(){var t,n;const e=tt();if(!e||!It("engine_history"))return null;try{const s=await fetch(`${e.url}/rest/v1/engine_history?is_active=eq.true&order=created_at.desc&limit=1&select=*`,{method:"GET",headers:{apikey:e.anonKey,Authorization:`Bearer ${e.anonKey}`,"Content-Type":"application/json"}});if(s.status===404)return Ot("engine_history"),null;if(!s.ok)return null;const a=await s.json();if(!Array.isArray(a)||a.length===0)return null;const o=a[0];return{id:o.id,schemaVersion:o.schema_version??1,title:o.title||"Published Version",description:o.description||"",createdAt:o.created_at||new Date().toISOString(),authorSessionId:o.author_session_id||"unknown",isActive:!!o.is_active,canvases:((t=o.snapshot_data)==null?void 0:t.canvases)||{},contentOverrides:((n=o.snapshot_data)==null?void 0:n.contentOverrides)||{},summary:o.summary||{totalSections:0,totalSubsections:0,totalLeafElements:0,totalTextOverrides:0}}}catch(s){return console.warn("[historyService] Fetch active version error:",s),null}}function hm(e=!1){const t=Ds();return t.isStale&&!e?{canPublish:!1,reason:"DRAFT_STALE",staleness:t}:{canPublish:!0,staleness:t}}async function Pd(e,t="Published Revision",n,s){const a=typeof s=="boolean"?s:!!(s!=null&&s.forcePublish),o=Ds();if(o.isStale&&!a)return{success:!1,snapshot:null,cloudSynced:!1,error:`Draft is stale. Active published snapshot is ${o.currentActiveId}, but draft was created from ${o.baseId||"baseline"}. Force publish required.`};const i=e?e.trim():"";if(i.length<4)return{success:!1,snapshot:null,cloudSynced:!1,error:"Changelog description must be at least 4 characters long."};const l=en();if(l!==null&&!zn(l))return{success:!1,snapshot:null,cloudSynced:!1,error:"Session expired. Please unlock Developer Mode again."};const c=n||ka(),d={};for(const I of Ut())d[I]=Ft(I,!0);const h=Ls(!0),p=Xa(d,h),f=`pub-${Date.now()}-${Math.random().toString(36).substring(2,7)}`,m=t.trim()||"Published Revision",g=new Date().toISOString(),b={id:f,schemaVersion:Ur,title:m,description:i,createdAt:g,authorSessionId:c,isActive:!0,canvases:d,contentOverrides:h,summary:p};for(const I of Ut())Ir(d[I],{silent:!0});Fs(!1),$a(h);const y=zt(),S={id:b.id,schemaVersion:b.schemaVersion,type:"milestone",title:b.title,notes:b.description,createdAt:b.createdAt,authorSessionId:b.authorSessionId,canvases:b.canvases,contentOverrides:b.contentOverrides,summary:b.summary};y.snapshots=[S,...y.snapshots],y.activeMilestoneId=b.id,y.activePublishedId=b.id,zr(b.id),dn(y),Qc(d),Fd({type:"MASID_PUBLISH_BROADCAST",snapshotId:b.id,timestamp:b.createdAt,canvases:b.canvases,contentOverrides:b.contentOverrides,activePublishedId:b.id});let v=!1,k;const x=tt();if(x)try{const I={id:b.id,schema_version:b.schemaVersion,title:b.title,description:b.description,snapshot_data:{canvases:b.canvases,contentOverrides:b.contentOverrides},summary:b.summary,is_active:!0,author_session_id:b.authorSessionId,created_at:b.createdAt},N=await fetch(`${x.url}/rest/v1/engine_history`,{method:"POST",headers:{apikey:x.anonKey,Authorization:`Bearer ${x.anonKey}`,"Content-Type":"application/json",Prefer:"return=representation"},body:JSON.stringify(I)});if(N.status===404&&Ot("engine_history"),N.ok){v=!0,_c("engine_history");try{await fetch(`${x.url}/rest/v1/engine_history?is_active=eq.true&id=neq.${b.id}`,{method:"PATCH",headers:{apikey:x.anonKey,Authorization:`Bearer ${x.anonKey}`,"Content-Type":"application/json",Prefer:"return=minimal"},body:JSON.stringify({is_active:!1})})}catch(_){console.warn("[historyService] Failed to demote previous active snapshots in Supabase:",_)}}else k=`Cloud sync failed with HTTP ${N.status}`}catch(I){k=I instanceof Error?I.message:"Network error during cloud publish"}try{tm(b).catch(I=>{console.warn("[historyService] Non-blocking Edge KV pre-bake warning:",I)})}catch(I){console.warn("[historyService] Edge KV pre-bake dispatch error:",I)}return{success:!0,snapshot:b,cloudSynced:v,error:k}}let $n=null;function Gi(){if(typeof BroadcastChannel>"u")return null;if(!$n)try{$n=new BroadcastChannel(Oi()),$n.onmessage=e=>{Ud(e.data)}}catch(e){console.warn("[historyService] Failed to initialize BroadcastChannel:",e),$n=null}return $n}function fm(){if($n){try{$n.close()}catch{}$n=null}}function Fd(e){const t=Gi();if(t)try{t.postMessage(e)}catch(n){console.warn("[historyService] Failed to postMessage on sync BroadcastChannel:",n)}}function Ud(e){if(!(!e||e.type!=="MASID_PUBLISH_BROADCAST")){if(e.canvases){for(const t of Ut())e.canvases[t]&&Ir(e.canvases[t],{silent:!0});Fs(!1)}e.contentOverrides&&$a(e.contentOverrides),e.activePublishedId&&zr(e.activePublishedId)}}if(typeof window<"u")try{Gi()}catch{}let jn=!1,Gr=!1;const Wi=new Set;function Hi(){return!1}function pm(){return jn}function zd(e){return Wi.add(e),()=>{Wi.delete(e)}}function Vi(e){jn=e,Wi.forEach(t=>{try{t(e)}catch(n){console.warn("[historyService] Hydration listener error:",n)}})}function mm(){const e=Ee(),t=e?e.getItem(Pr())||e.getItem(Fr):null;return{isHydrating:jn,hasConfirmedData:!!t||Gr,source:t?"cache":Gr?"cloud":"baseline",activePublishedId:t}}function gm(){jn=!1,Gr=!1}let Hs=null;function Gd(){return Hs||(Hs=(async()=>{const e=Hi();try{const t=await Od();if(!t)return Gr=!0,(e||jn)&&Vi(!1),!1;zr(t.id);for(const n of Ut())t.canvases[n]&&Ir(t.canvases[n],{silent:!0});return Fs(!1),t.contentOverrides&&$a(t.contentOverrides),Ar("live"),Gr=!0,(e||jn)&&Vi(!1),!0}catch(t){return console.warn("[historyService] Hydrate active version error:",t),Gr=!0,jn&&Vi(!1),!1}finally{Hs=null}})(),Hs)}const dt={toastPortal:"_toastPortal_f8wvm_7",toastSuccess:"_toastSuccess_f8wvm_49",toastError:"_toastError_f8wvm_54",toastInfo:"_toastInfo_f8wvm_59",iconWrapper:"_iconWrapper_f8wvm_64",successIcon:"_successIcon_f8wvm_74",errorIcon:"_errorIcon_f8wvm_79",infoIcon:"_infoIcon_f8wvm_84",svgIcon:"_svgIcon_f8wvm_89",message:"_message_f8wvm_94",dismissButton:"_dismissButton_f8wvm_101",actionButton:"_actionButton_f8wvm_136"};function vm(e="success"){try{const t=window.AudioContext||window.webkitAudioContext;if(!t)return;const n=new t;n.state==="suspended"&&n.resume();const s=n.currentTime,a=n.createGain();if(a.connect(n.destination),e==="success"){const o=n.createOscillator(),i=n.createOscillator();o.type="sine",i.type="sine",o.frequency.setValueAtTime(587.33,s),i.frequency.setValueAtTime(880,s+.06),a.gain.setValueAtTime(.05,s),a.gain.exponentialRampToValueAtTime(.07,s+.06),a.gain.exponentialRampToValueAtTime(1e-4,s+.26),o.connect(a),i.connect(a),o.start(s),o.stop(s+.06),i.start(s+.06),i.stop(s+.26)}else if(e==="error"){const o=n.createOscillator();o.type="triangle",o.frequency.setValueAtTime(329.63,s),o.frequency.setValueAtTime(261.63,s+.07),a.gain.setValueAtTime(.06,s),a.gain.exponentialRampToValueAtTime(1e-4,s+.2),o.connect(a),o.start(s),o.stop(s+.2)}else{const o=n.createOscillator();o.type="sine",o.frequency.setValueAtTime(659.25,s),a.gain.setValueAtTime(.04,s),a.gain.exponentialRampToValueAtTime(1e-4,s+.18),o.connect(a),o.start(s),o.stop(s+.18)}setTimeout(()=>{try{n.close()}catch{}},320)}catch{}}const bm=r.jsx("svg",{className:dt.svgIcon,viewBox:"0 0 20 20",fill:"currentColor","aria-hidden":"true",children:r.jsx("path",{fillRule:"evenodd",d:"M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z",clipRule:"evenodd"})}),ym=r.jsx("svg",{className:dt.svgIcon,viewBox:"0 0 20 20",fill:"currentColor","aria-hidden":"true",children:r.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"})}),_m=r.jsx("svg",{className:dt.svgIcon,viewBox:"0 0 20 20",fill:"currentColor","aria-hidden":"true",children:r.jsx("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z",clipRule:"evenodd"})}),Zt=({message:e,type:t="success",durationMs:n=3500,onDismiss:s,actionLabel:a,onAction:o,playAudio:i=!0})=>{const[l,c]=u.useState(!1);if(u.useEffect(()=>{c(!0),i&&vm(t)},[t,i]),u.useEffect(()=>{if(n<=0)return;const f=setTimeout(()=>{s()},n);return()=>clearTimeout(f)},[n,s]),!l||typeof document>"u")return null;const d=t==="success"?r.jsx("span",{className:`${dt.iconWrapper} ${dt.successIcon}`,children:bm}):t==="error"?r.jsx("span",{className:`${dt.iconWrapper} ${dt.errorIcon}`,children:ym}):r.jsx("span",{className:`${dt.iconWrapper} ${dt.infoIcon}`,children:_m}),h=t==="error"?dt.toastError:t==="info"?dt.toastInfo:dt.toastSuccess,p=r.jsxs("div",{role:"status","aria-live":"polite",className:`${dt.toastPortal} ${h}`,children:[d,r.jsx("span",{className:dt.message,children:e}),a&&o&&r.jsx("button",{type:"button",className:dt.actionButton,onClick:()=>{o(),s()},children:a}),r.jsx("button",{type:"button",className:dt.dismissButton,onClick:s,"aria-label":"Dismiss notification",children:"✕"})]});return bs.createPortal(p,document.body)},Vs=new Set;function Wd(e,t){t?Vs.add(e):Vs.delete(e)}function qi(e){Vs.delete(e)}function wm(){Vs.clear()}function Hd(){return Vs.size>0?!0:Bs()}function ji(e){if(Hd())return e.preventDefault(),e.returnValue="",""}const Vd=u.createContext(null),qd=({children:e,securitySalt:t,expectedPinHash:n})=>{const[s,a]=u.useState(()=>ya()),[o,i]=u.useState(()=>{if(!ya())return!1;const F=en();return zn(F)}),[l,c]=u.useState(!1),[d,h]=u.useState(!1),[p,f]=u.useState(()=>{const F=_n();return F&&Date.now()<F?"locked_out":"idle"}),[m,g]=u.useState(()=>ka()),[b,y]=u.useState(!1),[S,v]=u.useState(null),[k,x]=u.useState(!1),[I,N]=u.useState(()=>Math.max(0,fr-_a())),[_,T]=u.useState(()=>{const F=_n();return F&&Date.now()<F?Math.ceil((F-Date.now())/1e3):0}),[w,M]=u.useState(()=>Vo(en())),[$,A]=u.useState(()=>Bs()),[P,V]=u.useState(null),D=u.useRef(null),W=u.useRef(null),H=u.useRef(null),q=u.useRef(b),j=u.useRef(l),z=u.useRef(d);u.useEffect(()=>{q.current=b},[b]),u.useEffect(()=>{j.current=l},[l]),u.useEffect(()=>{z.current=d},[d]),u.useEffect(()=>{const F=Cc();if(!F)return;const L=G=>{if(!(!G.data||typeof G.data!="object")){if(G.data.type==="PING_SESSION"&&G.data.sessionId===m)G.data.tabInstanceId!==Ns&&F.postMessage({type:"SESSION_OWNED",sessionId:m,ownerTabInstanceId:Ns});else if(G.data.type==="SESSION_OWNED"&&G.data.sessionId===m&&G.data.ownerTabInstanceId!==Ns){console.warn("[DeveloperModeContext] Cloned tab detected! Disengaging inherited Dev Mode."),Un();const le=xc();g(le),i(!1),j.current=!1,c(!1),y(!0),q.current=!0,Wn(le).then(ue=>{v(ue.currentLock||null)})}}};return F.addEventListener("message",L),F.postMessage({type:"PING_SESSION",sessionId:m,tabInstanceId:Ns}),()=>{F.removeEventListener("message",L)}},[m]),u.useEffect(()=>qc(L=>{A(L.isDirty)}),[]);const[O,U]=u.useState(()=>Hi());u.useEffect(()=>zd(L=>{U(L)}),[]);const[Q,se]=u.useState(()=>jc());u.useEffect(()=>Kc(L=>{se(L.status)}),[]),u.useEffect(()=>{Gd().catch(()=>{})},[]),u.useEffect(()=>{o&&Oa(!1).catch(F=>{console.error("Draft initialization failed:",F),V({message:"Draft Initialization Failed: Could not initialize draft workspace.",type:"error"}),i(!1)})},[o]),u.useEffect(()=>{const F=()=>{const L=ya();a(L),L||(i(!1),c(!1),h(!1))};return window.addEventListener("resize",F),()=>window.removeEventListener("resize",F)},[]),u.useEffect(()=>{const F=()=>{const L=_n();if(L){const G=L-Date.now();if(G>0){T(Math.ceil(G/1e3)),f("locked_out");return}else jo(),Yo(),N(fr),T(0),f("idle")}else T(0)};return F(),W.current=window.setInterval(F,1e3),()=>{W.current&&clearInterval(W.current)}},[]),u.useEffect(()=>{if(!o){D.current&&clearInterval(D.current);return}const F=()=>{const L=en();zn(L)?M(Vo(L)):(x(!0),c(!0),M(0))};return F(),D.current=window.setInterval(F,5e3),()=>{D.current&&clearInterval(D.current)}},[o]),u.useEffect(()=>{if(!o){H.current&&(clearInterval(H.current),H.current=null);return}Jo(m);const F=()=>{Nc(m).then(async le=>{if(!le){console.warn("[DeveloperModeContext] Liveness heartbeat rejected: lock held by another coordinator."),i(!1),Un(),Os(),y(!0),q.current=!0;const ue=await Wn(m);v(ue.currentLock||null),V({message:"Developer Mode session ended: another coordinator is currently active.",type:"error"})}})};H.current=window.setInterval(F,kc);const L=()=>{Tc(m)},G=le=>{o&&ji(le)};return window.addEventListener("beforeunload",G),window.addEventListener("pagehide",L),()=>{H.current&&(clearInterval(H.current),H.current=null),window.removeEventListener("beforeunload",G),window.removeEventListener("pagehide",L)}},[o,m]),u.useEffect(()=>{if(!o)return;const F=async()=>{const le=await Wn(m);!le.canAcquire&&le.currentLock&&!le.isSelfSession&&(console.warn("[DeveloperModeContext] Active lock claimed by another coordinator."),i(!1),Un(),Os(),y(!0),q.current=!0,v(le.currentLock),V({message:"Developer Mode session ended: another coordinator is currently active.",type:"error"}))};F();const L=window.setInterval(F,1e4),G=()=>{F()};return window.addEventListener("focus",G),()=>{clearInterval(L),window.removeEventListener("focus",G)}},[o,m]);const ae=u.useCallback((F=!1,L=!1)=>{x(F);const G=_n();if(G&&Date.now()<G){f("locked_out"),T(Math.ceil((G-Date.now())/1e3)),q.current=!1,y(!1),v(null),j.current=!0,c(!0);return}if(L){q.current=!1,y(!1),v(null),f("idle"),j.current=!0,c(!0);return}Wn(m).then(le=>{!le.canAcquire&&le.currentLock&&!le.isSelfSession?(q.current=!0,y(!0),v(le.currentLock),j.current=!1,c(!1)):(q.current=!1,y(!1),v(null),f("idle"),j.current=!0,c(!0))}).catch(()=>{q.current=!1,y(!1),v(null),f("idle"),j.current=!0,c(!0)})},[m]),de=u.useCallback(()=>{j.current=!1,c(!1);const F=_n();if(F&&Date.now()<F?f("locked_out"):f("idle"),k){const L=en();zn(L)||(Un(),Qo(m),i(!1)),x(!1)}},[k,m]),B=u.useCallback(()=>{q.current=!1,y(!1),v(null)},[]),Y=u.useCallback(async()=>{try{const F=await Wn(m);F.canAcquire||F.isSelfSession?ae(!1,!0):F.currentLock&&(q.current=!0,y(!0),v(F.currentLock))}catch{}},[m,ae]);u.useEffect(()=>Ac(L=>{L&&L.isLocked&&L.lockedBySessionId!==m?(o&&(i(!1),Un()),j.current&&(j.current=!1,c(!1),q.current=!0,y(!0)),v(L)):(!L||!L.isLocked)&&q.current&&ae(!1,!0)}),[o,m,ae]);const ee=u.useCallback(F=>{(F==null?void 0:F.discard)===!0?ui():Os(),A(!1),Qo(m),Un(),i(!1),j.current=!1,c(!1),z.current=!1,h(!1),x(!1),q.current=!1,y(!1),v(null),M(0);try{if(typeof window<"u"){const L=new URL(window.location.href);let G=!1;L.searchParams.has("dev")&&(L.searchParams.delete("dev"),G=!0),L.searchParams.has("mode")&&(L.searchParams.delete("mode"),G=!0),L.hash.includes("dev=true")&&(L.hash=L.hash.replace(/[?&]dev=true/,""),G=!0),G&&window.history.replaceState(null,"",L.toString())}}catch{}},[m]),X=u.useCallback(()=>{o&&(h(!0),z.current=!0)},[o]),te=u.useCallback(()=>{h(!1),z.current=!1},[]),K=u.useCallback(F=>{te(),ee(F)},[te,ee]),J=u.useCallback(()=>{o?X():ae(!1)},[o,X,ae]),Z=u.useCallback(async F=>{if(_n()&&Date.now()<(_n()??0))return f("locked_out"),!1;f("verifying");try{const L=gc(F,t,n),G=new Promise((ue,he)=>setTimeout(()=>he(new Error("PIN verification timed out.")),3e3));if(await Promise.race([L,G])){const ue=await Jo(m);if(!ue.success&&ue.lock)return j.current=!1,c(!1),f("idle"),q.current=!0,y(!0),v(ue.lock),!1;const he=Date.now();vc(he),Yo(),jo(),N(fr),M(30),f("success");try{Oa(!k)}catch(oe){return console.error("Draft initialization failed:",oe),V({message:"Draft Initialization Failed: Insufficient browser storage to create draft workspace.",type:"error"}),i(!1),!1}return i(!0),x(!1),q.current=!1,y(!1),v(null),setTimeout(()=>{j.current=!1,c(!1),f("idle")},400),!0}else{const ue=_a()+1;Ko(ue);const he=Math.max(0,fr-ue);if(N(he),he===0){const oe=Date.now()+Wo;qo(oe),T(60),f("locked_out")}else f("error");return!1}}catch(L){console.warn("[DeveloperMode] Verification error caught:",L);const G=_a()+1;Ko(G);const le=Math.max(0,fr-G);if(N(le),le===0){const ue=Date.now()+Wo;qo(ue),T(60),f("locked_out")}else f("error");return!1}},[m]);u.useEffect(()=>{const F=L=>{const G=L.metaKey||L.ctrlKey,le=L.shiftKey,ue=L.key==="D"||L.key==="d"||L.code==="KeyD";G&&le&&ue&&(L.preventDefault(),J())};return window.addEventListener("keydown",F),()=>window.removeEventListener("keydown",F)},[J]),u.useEffect(()=>{try{const F=new URLSearchParams(window.location.search);if(F.get("dev")==="true"||F.get("mode")==="developer"){const G=en();zn(G)?i(!0):ae(!1),F.delete("dev"),F.get("mode")==="developer"&&F.delete("mode");const le=F.toString(),ue=window.location.pathname+(le?`?${le}`:"")+window.location.hash;window.history.replaceState(null,"",ue)}}catch{}},[ae]);const ne=u.useCallback((F,L="success")=>{V({message:F,type:L})},[]),ie={isDevMode:o,isDesktop:s,isPinModalOpen:l,pinState:p,attemptsRemaining:I,lockoutRemainingSeconds:_,sessionRemainingMinutes:w,isRenewal:k,openPinModal:ae,closePinModal:de,submitPin:Z,exitDevMode:ee,isExitConfirmOpen:d,requestExitDevMode:X,confirmExitDevMode:K,closeExitConfirmModal:te,toggleDevMode:J,sessionId:m,isLockBlocked:b,activeLockInfo:S,closeLockBlockedModal:B,refreshLockStatus:Y,hasUnpublishedChanges:$,setHasUnpublishedChanges:F=>{kn(F),A(F)},isCloudHydrating:O,cloudSyncStatus:Q,showToast:ne};return r.jsxs(Vd.Provider,{value:ie,children:[e,P&&r.jsx(Zt,{message:P.message,type:P.type,onDismiss:()=>V(null)})]})},Oe=()=>{const e=u.useContext(Vd);return e||{isDevMode:!1,isDesktop:!1,isPinModalOpen:!1,pinState:"idle",attemptsRemaining:5,lockoutRemainingSeconds:0,sessionRemainingMinutes:0,isRenewal:!1,openPinModal:()=>{},closePinModal:()=>{},submitPin:async()=>!1,exitDevMode:()=>{},isExitConfirmOpen:!1,requestExitDevMode:()=>{},confirmExitDevMode:()=>{},closeExitConfirmModal:()=>{},toggleDevMode:()=>{},sessionId:"",isLockBlocked:!1,activeLockInfo:null,closeLockBlockedModal:()=>{},refreshLockStatus:async()=>{},hasUnpublishedChanges:!1,setHasUnpublishedChanges:()=>{},isCloudHydrating:!1,cloudSyncStatus:"saved",showToast:()=>{}}},He={siteHeader:"_siteHeader_ecg07_7",skipLink:"_skipLink_ecg07_20",navCapsule:"_navCapsule_ecg07_42",brandGroup:"_brandGroup_ecg07_70",brandMeta:"_brandMeta_ecg07_108",brandTitle:"_brandTitle_ecg07_113",brandSubtitle:"_brandSubtitle_ecg07_122",navLinks:"_navLinks_ecg07_130",navLink:"_navLink_ecg07_130",navAction:"_navAction_ecg07_192",menuToggle:"_menuToggle_ecg07_232",menuIcon:"_menuIcon_ecg07_276",menuLine:"_menuLine_ecg07_286",menuLineTop:"_menuLineTop_ecg07_297",menuLineBottom:"_menuLineBottom_ecg07_301",menuLineTopOpen:"_menuLineTopOpen_ecg07_306",menuLineBottomOpen:"_menuLineBottomOpen_ecg07_310",mobileDropdown:"_mobileDropdown_ecg07_318",mobileNavLink:"_mobileNavLink_ecg07_356",itemNumber:"_itemNumber_ecg07_371",itemLabel:"_itemLabel_ecg07_379",noCta:"_noCta_ecg07_433"},Sm=[{label:"Roadmap",href:"#sequence-roadmap"},{label:"Overview",href:"#main-content"}],jd=({brandTitle:e="Portal",brandSubtitle:t,brandLetter:n,navItems:s,mobileOnlyNav:a=!1,onRoadmapClick:o,onOverviewClick:i,onBrandClick:l})=>{const[c,d]=u.useState(!1),h=u.useRef(null),p=u.useRef([]),{openPinModal:f}=Oe(),m=v=>{v.preventDefault(),v.stopPropagation();const k=Date.now();p.current=[...p.current.filter(x=>k-x<3e3),k],p.current.length>=5&&(p.current=[],f(!1))},g=s!==void 0?s:Sm,b=()=>{d(v=>!v)},y=()=>{d(!1)},S=(v,k)=>{const x=v.label.toLowerCase();if(v.href==="#sequence-roadmap"||v.href==="#roadmap"||x==="roadmap"&&!v.href.startsWith("#node")){k.preventDefault(),d(!1),o==null||o(k);return}if(v.href==="#main-content"){k.preventDefault(),d(!1),i==null||i(k);return}if(v.href.startsWith("#")){k.preventDefault(),d(!1);const I=v.id||v.href.slice(1),N=document.getElementById(I);if(N){const w=N.getBoundingClientRect().top+window.pageYOffset-100;window.scrollTo({top:Math.max(0,w),behavior:"smooth"})}return}if(x==="overview"){k.preventDefault(),d(!1),i==null||i(k);return}};return u.useEffect(()=>{const v=k=>{k.key==="Escape"&&c&&d(!1)};return window.addEventListener("keydown",v),()=>window.removeEventListener("keydown",v)},[c]),u.useEffect(()=>{const v=k=>{h.current&&!h.current.contains(k.target)&&d(!1)};return c&&document.addEventListener("mousedown",v),()=>document.removeEventListener("mousedown",v)},[c]),r.jsxs("header",{ref:h,className:He.siteHeader,role:"banner",children:[r.jsx("a",{href:"#roadmap",className:He.skipLink,children:"Skip to content"}),r.jsxs("nav",{className:`${He.navCapsule} ${He.noCta}`,"aria-label":"Main Navigation",children:[r.jsxs("a",{href:"#",className:He.brandGroup,"aria-label":`${e} Home`,onClick:v=>{l&&(v.preventDefault(),l(v))},children:[r.jsx("span",{onClick:m,style:{display:"inline-flex"},title:"Brand Mark",children:r.jsx(_s,{size:"sm",letter:n})}),r.jsxs("div",{className:He.brandMeta,children:[r.jsx("span",{className:He.brandTitle,children:e}),t&&r.jsx("span",{className:He.brandSubtitle,children:t})]})]}),!a&&g.length>0&&r.jsx("ul",{className:He.navLinks,children:g.map(v=>r.jsx("li",{children:r.jsx("a",{href:v.href,className:He.navLink,onClick:k=>S(v,k),children:v.label})},v.label))}),g.length>0&&r.jsx("div",{className:`${He.navAction} ${a?He.navActionMobileOnly:""}`,children:r.jsx("button",{type:"button",className:He.menuToggle,onClick:b,"aria-label":c?"Close navigation menu":"Open navigation menu","aria-expanded":c,"aria-controls":"app-mobile-nav",children:r.jsxs("div",{className:He.menuIcon,"aria-hidden":"true",children:[r.jsx("span",{className:`${He.menuLine} ${He.menuLineTop} ${c?He.menuLineTopOpen:""}`}),r.jsx("span",{className:`${He.menuLine} ${He.menuLineBottom} ${c?He.menuLineBottomOpen:""}`})]})})}),c&&g.length>0&&r.jsx("div",{id:"app-mobile-nav",className:He.mobileDropdown,role:"menu","aria-label":"Mobile Navigation Menu",children:g.map(v=>r.jsxs("a",{href:v.href,className:He.mobileNavLink,role:"menuitem",onClick:k=>{y(),S(v,k)},children:[v.number&&r.jsx("span",{className:He.itemNumber,children:v.number}),r.jsx("span",{className:He.itemLabel,children:v.label})]},v.id||v.href||v.label))})]})]})},Kn={pill:"_pill_1jlh1_6",icon:"_icon_1jlh1_36",label:"_label_1jlh1_43",externalIcon:"_externalIcon_1jlh1_48",sizeSm:"_sizeSm_1jlh1_56",sizeMd:"_sizeMd_1jlh1_64",white:"_white_1jlh1_75",blue:"_blue_1jlh1_90",primary:"_primary_1jlh1_97",accent:"_accent_1jlh1_104",green:"_green_1jlh1_111",amber:"_amber_1jlh1_118",neutral:"_neutral_1jlh1_125",mono:"_mono_1jlh1_134",link:"_link_1jlh1_146",interactive:"_interactive_1jlh1_173"},qs=({label:e,variant:t="neutral",size:n,icon:s,pulse:a=!1,href:o,target:i,rel:l,type:c="button",onClick:d,className:h="",ariaLabel:p,title:f,showExternalIcon:m=t==="link"})=>{const g=r.jsxs(r.Fragment,{children:[s&&r.jsx("span",{className:Kn.icon,"aria-hidden":"true",children:s}),r.jsx("span",{className:Kn.label,children:e}),m&&r.jsx("span",{className:Kn.externalIcon,"aria-hidden":"true",children:"↗"})]}),b=n==="sm"?Kn.sizeSm:n==="md"?Kn.sizeMd:"",y=`${Kn.pill} ${Kn[t]} ${b} ${h}`.trim();return o?r.jsx("a",{href:o,target:i||(t==="link"?"_blank":void 0),rel:l||(t==="link"?"noopener noreferrer":void 0),className:y,onClick:d,"aria-label":p,title:f,children:g}):d||t==="interactive"?r.jsx("button",{type:c,className:y,onClick:d,"aria-label":p,title:f,children:g}):r.jsx("span",{className:y,role:"status","aria-label":p,title:f,children:g})},ut={btn:"_btn_cfm1h_11",btnContent:"_btnContent_cfm1h_37",sizeXs:"_sizeXs_cfm1h_51",sizeSm:"_sizeSm_cfm1h_61",sizeMd:"_sizeMd_cfm1h_71",sizeLg:"_sizeLg_cfm1h_81",variantRevolvingOutline:"_variantRevolvingOutline_cfm1h_94",revolvingStopped:"_revolvingStopped_cfm1h_161",variantPrimary:"_variantPrimary_cfm1h_206",variantSecondary:"_variantSecondary_cfm1h_225",variantGhost:"_variantGhost_cfm1h_245",variantAdmin:"_variantAdmin_cfm1h_262",pulse:"_pulse_cfm1h_324"},km={"revolving-outline":ut.variantRevolvingOutline,primary:ut.variantPrimary,secondary:ut.variantSecondary,ghost:ut.variantGhost,admin:ut.variantAdmin},Cm={xs:ut.sizeXs,sm:ut.sizeSm,md:ut.sizeMd,lg:ut.sizeLg},me=({variant:e="revolving-outline",size:t="md",outlineWidth:n,revolving:s=!0,pulse:a=!1,as:o,href:i,type:l="button",onClick:c,onMouseEnter:d,onMouseLeave:h,className:p,style:f,children:m,"aria-label":g,title:b,disabled:y=!1,target:S,rel:v,id:k,tabIndex:x,"aria-hidden":I,ref:N,..._})=>{const T=o==="a"||i!==void 0&&o!=="button",w=km[e]||ut.variantRevolvingOutline,M=Cm[t]||ut.sizeMd,$=e==="revolving-outline"&&!s?ut.revolvingStopped:"",A=a?ut.pulse:"",P=`${ut.btn} ${w} ${M} ${$} ${A} ${p||""}`.trim(),V={...f,...n!==void 0?{"--outline-width":typeof n=="number"?`${n}px`:n}:{}},D=e==="revolving-outline"?String(s):void 0;return T?r.jsx("a",{id:k,href:i,onClick:c,onMouseEnter:d,onMouseLeave:h,className:P,style:V,title:b,"aria-label":g,"aria-disabled":y?"true":void 0,target:S,rel:v,tabIndex:x,"aria-hidden":I,"data-revolving":D,"data-pulse":a?"true":void 0,..._,children:r.jsx("span",{className:ut.btnContent,children:m})}):r.jsx("button",{ref:N,id:k,type:l,onClick:c,onMouseEnter:d,onMouseLeave:h,className:P,style:V,title:b,"aria-label":g,disabled:y,tabIndex:x,"aria-hidden":I,"data-revolving":D,"data-pulse":a?"true":void 0,"data-variant":e,"data-primary":e==="primary"||e==="admin"?"true":void 0,..._,children:r.jsx("span",{className:ut.btnContent,children:m})})};let js=0,Kd="",Yd="",Zd="",Xd="";function Ki(){if(!(typeof document>"u")){if(js===0){Kd=document.body.style.overflow,Yd=document.documentElement.style.overflow,Zd=document.body.style.paddingRight;const e=window.innerWidth-document.documentElement.clientWidth;e>0&&(document.body.style.paddingRight=`${e}px`),document.body.style.overflow="hidden",document.documentElement.style.overflow="hidden";const t=document.getElementById("root");t&&(Xd=t.style.pointerEvents,t.style.pointerEvents="none",t.setAttribute("inert",""),t.setAttribute("aria-hidden","true"))}js++}}function Yi(){if(!(typeof document>"u")&&(js=Math.max(0,js-1),js===0)){document.body.style.overflow=Kd,document.documentElement.style.overflow=Yd,document.body.style.paddingRight=Zd;const e=document.getElementById("root");e&&(e.style.pointerEvents=Xd,e.removeAttribute("inert"),e.removeAttribute("aria-hidden"))}}const Yn=[];function Zi(e){e&&(Yn.includes(e)||Yn.push(e))}function Xi(e){if(!e)return;const t=Yn.indexOf(e);t!==-1&&Yn.splice(t,1)}function Ji(e){return e?Yn.length===0?!0:Yn[Yn.length-1]===e:!1}function Qi(e){return e.key==="Enter"&&(e.ctrlKey||e.metaKey)}const xm=/\b(save|submit|publish|confirm|approve|next|done|add|create|continue|apply|deploy|verify|restore|exit|delete|proceed|ok|yes)\b/i,Jd=/\b(cancel|close|discard|dismiss|reset|back|keep editing|cancel & exit|no)\b/i;function Zn(e){var n;if(!e||"disabled"in e&&e.disabled||e.getAttribute("aria-disabled")==="true"||e.getAttribute("aria-hidden")==="true")return!1;if(typeof window<"u"){const s=window.getComputedStyle(e);if(s.display==="none"||s.visibility==="hidden")return!1}const t=(e.textContent||e.getAttribute("aria-label")||"").trim();return!(t==="✕"||t==="×"||Jd.test(t)||(n=e.getAttribute("aria-label"))!=null&&n.toLowerCase().includes("close"))}function Ri(e){if(!e)return null;const t=Array.from(e.querySelectorAll('[data-positive="true"], [data-action="confirm"], [data-action="save"], [data-action="submit"], [data-action="primary"]')).filter(Zn);if(t.length>0)return t[0];const n=Array.from(e.querySelectorAll('button[type="submit"], input[type="submit"]')).filter(Zn);if(n.length>0)return n[0];const s=Array.from(e.querySelectorAll('button[data-variant="primary"], button[data-variant="admin"], button[data-primary="true"], button[class*="variantPrimary"], button[class*="variantAdmin"], button[class*="modalDeleteButton"], button[class*="primaryButton"], button[class*="saveButton"]')).filter(Zn);if(s.length>0)return s[0];const o=Array.from(e.querySelectorAll("button")).filter(Zn).filter(l=>{const c=(l.textContent||l.getAttribute("aria-label")||"").trim();return xm.test(c)&&!Jd.test(c)});if(o.length>0)return o[0];const i=e.querySelector("form");return i||null}function el(e){if(!e)return!1;if(e instanceof HTMLFormElement){if(typeof e.requestSubmit=="function")return e.requestSubmit(),!0;const t=e.querySelector('button[type="submit"], input[type="submit"]');return t&&Zn(t)?(t.click(),!0):(e.dispatchEvent(new Event("submit",{cancelable:!0,bubbles:!0})),!0)}return Zn(e)?(e.click(),!0):!1}const Wr={backdrop:"_backdrop_1safl_8",modalCard:"_modalCard_1safl_27",header:"_header_1safl_44",title:"_title_1safl_51",closeButton:"_closeButton_1safl_61",absoluteCloseButton:"_absoluteCloseButton_1safl_90"},bt=({isOpen:e,onClose:t,title:n,children:s,maxWidth:a,className:o,cardClassName:i,ariaLabel:l,ariaLabelledBy:c,ariaDescribedBy:d,showCloseButton:h=!0,role:p="dialog",closeOnOutsideClick:f=!1,closeOnBackdropClick:m=!1,closeOnEscape:g=!0,onConfirm:b,enableCtrlEnter:y=!0,initialFocusRef:S})=>{const[v,k]=u.useState(!1),x=u.useRef(null),I=u.useRef(null);if(u.useEffect(()=>{k(!0)},[]),u.useEffect(()=>{if(e)return Ki(),()=>{Yi()}},[e]),u.useEffect(()=>{if(!e)return;const w=x.current;return w&&Zi(w),()=>{w&&Xi(w)}},[e]),u.useEffect(()=>{if(!e)return;I.current=document.activeElement;const w=window.setTimeout(()=>{if(!x.current)return;if(S!=null&&S.current){S.current.focus();return}const $=x.current.querySelector("[data-autofocus], [autofocus]");if($){$.focus();return}const A=x.current.querySelector('input:not([disabled]):not([type="hidden"]), textarea:not([disabled]), select:not([disabled])');if(A){A.focus();return}const P=x.current.querySelectorAll('button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])');P.length>0?P[0].focus():x.current.focus()},25),M=$=>{const A=x.current&&(x.current.contains(document.activeElement)||Ji(x.current));if(g&&$.key==="Escape"&&A){$.preventDefault(),t();return}if(y&&Qi($)&&A){if($.preventDefault(),$.stopPropagation(),b){b();return}if(x.current){const P=Ri(x.current);P&&el(P)}return}if($.key==="Tab"&&x.current){const P=Array.from(x.current.querySelectorAll('button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])'));if(P.length===0){$.preventDefault();return}const V=P[0],D=P[P.length-1];$.shiftKey?(document.activeElement===V||!x.current.contains(document.activeElement))&&($.preventDefault(),D.focus()):(document.activeElement===D||!x.current.contains(document.activeElement))&&($.preventDefault(),V.focus())}};return window.addEventListener("keydown",M),()=>{var $;window.clearTimeout(w),window.removeEventListener("keydown",M),($=I.current)==null||$.focus()}},[e,t,g,y,b,S]),!v||!e)return null;const N=f||m,_=w=>{w.stopPropagation(),w.target===w.currentTarget&&N&&t()},T=r.jsx("div",{className:`${Wr.backdrop} ${o||""}`,onClick:_,onMouseDown:w=>w.stopPropagation(),onTouchStart:w=>w.stopPropagation(),role:"presentation",children:r.jsxs("div",{ref:x,tabIndex:-1,className:`${Wr.modalCard} ${i||""}`,style:a?{maxWidth:typeof a=="number"?`${a}px`:a}:void 0,role:p,"aria-modal":"true","aria-label":l,"aria-labelledby":c,"aria-describedby":d,children:[n?r.jsxs("div",{className:Wr.header,children:[r.jsx("h2",{id:c,className:Wr.title,children:n}),h&&r.jsx("button",{type:"button",className:Wr.closeButton,onClick:t,"aria-label":"Close dialog",children:"✕"})]}):h?r.jsx("button",{type:"button",className:Wr.absoluteCloseButton,onClick:t,"aria-label":"Close dialog",children:"✕"}):null,s]})});return bs.createPortal(T,document.body)},tl={trigger:"_trigger_11pzf_1",icon:"_icon_11pzf_26",bubble:"_bubble_11pzf_32"},Nm=({className:e})=>r.jsxs("svg",{className:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[r.jsx("circle",{cx:"12",cy:"12",r:"10"}),r.jsx("line",{x1:"12",y1:"16",x2:"12",y2:"12"}),r.jsx("line",{x1:"12",y1:"8",x2:"12.01",y2:"8"})]}),Xn=u.memo(({text:e,label:t,className:n})=>{const{isDevMode:s}=Oe(),[a,o]=u.useState(!1),[i,l]=u.useState(null),c=u.useRef(null),d=u.useRef(null),h=u.useRef(null),p=u.useId();u.useEffect(()=>()=>{h.current&&clearTimeout(h.current)},[]);const f=u.useCallback(()=>{if(!c.current)return;const v=c.current.getBoundingClientRect(),k=d.current,x=k?k.offsetWidth:220,I=k?k.offsetHeight:44;let N=v.left+v.width/2-x/2;N=Math.max(12,Math.min(N,window.innerWidth-x-12));let _=v.top-I-6;_<12&&(_=v.bottom+6),l({top:_,left:N})},[]);if(u.useEffect(()=>{if(a){f();const v=requestAnimationFrame(f);return()=>cancelAnimationFrame(v)}else l(null)},[a,f]),u.useEffect(()=>{if(!a)return;const v=k=>{k.key==="Escape"&&o(!1)};return window.addEventListener("keydown",v),()=>window.removeEventListener("keydown",v)},[a]),!s)return null;const m=()=>{h.current&&clearTimeout(h.current),h.current=setTimeout(()=>{o(!0)},150)},g=()=>{h.current&&clearTimeout(h.current),o(!1)},b=()=>{o(!0)},y=()=>{o(!1)},S=v=>{v.preventDefault(),v.stopPropagation()};return r.jsxs(r.Fragment,{children:[r.jsx("span",{ref:c,role:"button",tabIndex:0,className:`${tl.trigger} ${n||""}`,"aria-label":t?`Help for ${t}`:"Help info","aria-describedby":a?p:void 0,onMouseEnter:m,onMouseLeave:g,onFocus:b,onBlur:y,onClick:S,onMouseDown:S,onKeyDown:v=>{(v.key===" "||v.key==="Enter")&&(v.preventDefault(),v.stopPropagation())},children:r.jsx(Nm,{className:tl.icon})}),a&&bs.createPortal(r.jsx("div",{id:p,ref:d,role:"tooltip",className:tl.bubble,style:{top:i?`${i.top}px`:"-9999px",left:i?`${i.left}px`:"-9999px"},children:e}),document.body)]})});Xn.displayName="DevHelpTooltip";const Ra=50;class Qd{constructor(){Uo(this,"undoStack",[]);Uo(this,"redoStack",[]);Uo(this,"executingLock",!1)}push(t){if(this.executingLock)return null;const n={...t,id:`undo_${Date.now()}_${Math.random().toString(36).substring(2,7)}`,timestamp:Date.now()};return this.undoStack.push(n),this.undoStack.length>Ra&&this.undoStack.shift(),this.redoStack=[],n}popUndo(){if(this.executingLock||this.undoStack.length===0)return null;const t=this.undoStack.pop();if(!t)return null;try{return this.executingLock=!0,t.undo(),this.redoStack.push(t),this.redoStack.length>Ra&&this.redoStack.shift(),t}finally{this.executingLock=!1}}popRedo(){if(this.executingLock||this.redoStack.length===0)return null;const t=this.redoStack.pop();if(!t)return null;try{return this.executingLock=!0,t.redo(),this.undoStack.push(t),this.undoStack.length>Ra&&this.undoStack.shift(),t}finally{this.executingLock=!1}}clear(){this.undoStack=[],this.redoStack=[],this.executingLock=!1}getState(){const t=this.undoStack[this.undoStack.length-1],n=this.redoStack[this.redoStack.length-1];return{canUndo:this.undoStack.length>0,canRedo:this.redoStack.length>0,undoCount:this.undoStack.length,redoCount:this.redoStack.length,lastActionDescription:t==null?void 0:t.description,nextRedoDescription:n==null?void 0:n.description}}isExecuting(){return this.executingLock}getStacks(){return{undo:[...this.undoStack],redo:[...this.redoStack]}}}function Rd(e){var s;if(!e||typeof HTMLElement<"u"&&!(e instanceof HTMLElement))return!1;const t=e,n=(s=t.tagName)==null?void 0:s.toUpperCase();if(n==="INPUT"){const a=(t.type||"text").toLowerCase();return!["button","submit","reset","checkbox","radio","range","color","file"].includes(a)}return!!(n==="TEXTAREA"||t.isContentEditable||typeof t.getAttribute=="function"&&t.getAttribute("role")==="textbox")}const un=new Qd,nl=u.createContext(null),eu=({children:e})=>{const[t,n]=u.useState(()=>un.getState()),[,s]=u.useTransition(),a=u.useCallback(()=>{n(un.getState())},[]),o=u.useCallback(h=>{un.push(h)&&a()},[a]),i=u.useCallback(()=>{s(()=>{un.popUndo()&&a()})},[a]),l=u.useCallback(()=>{s(()=>{un.popRedo()&&a()})},[a]),c=u.useCallback(()=>{un.clear(),a()},[a]);u.useEffect(()=>{const h=p=>{if(Rd(p.target))return;const f=typeof navigator<"u"&&/Mac|iPod|iPhone|iPad/.test(navigator.platform);if(!(f?p.metaKey:p.ctrlKey))return;const g=p.key.toLowerCase();if(g==="z"&&!p.shiftKey){un.getState().canUndo&&(p.preventDefault(),i());return}(g==="z"&&p.shiftKey||!f&&g==="y"&&!p.shiftKey)&&un.getState().canRedo&&(p.preventDefault(),l())};return window.addEventListener("keydown",h),()=>{window.removeEventListener("keydown",h)}},[i,l]);const d={...t,pushAction:o,undo:i,redo:l,clearHistory:c};return r.jsx(nl.Provider,{value:d,children:e})};function Ks(){const e=u.useContext(nl);return e||{canUndo:!1,canRedo:!1,undoCount:0,redoCount:0,pushAction:()=>{},undo:()=>{},redo:()=>{},clearHistory:()=>{}}}function eo(e,t){u.useEffect(()=>{if(Wd(t,e),!e)return()=>{qi(t)};const n=s=>{ji(s)};return window.addEventListener("beforeunload",n),()=>{qi(t),window.removeEventListener("beforeunload",n)}},[e,t])}const rl="engine-media",tu=1600,nu=.82;function ru(e){const t=e.split("."),n=(t.pop()||"png").toLowerCase().trim();return`${t.join(".").replace(/[^a-zA-Z0-9_-]/g,"_").replace(/_+/g,"_").slice(0,40)||"asset"}.${n}`}async function su(e,t){if(typeof window>"u"||typeof document>"u")return e;const n=e.type||"image/jpeg";if(!n.startsWith("image/")||n.includes("svg"))return e;const s=(t==null?void 0:t.maxDimension)||tu,a=(t==null?void 0:t.quality)||nu,o=(t==null?void 0:t.mimeType)||(n==="image/png"?"image/png":"image/jpeg");return new Promise(i=>{const l=new Image,c=URL.createObjectURL(e);l.onload=()=>{URL.revokeObjectURL(c);let{width:d,height:h}=l;(d>s||h>s)&&(d>h?(h=Math.round(h*s/d),d=s):(d=Math.round(d*s/h),h=s));const p=document.createElement("canvas");p.width=d,p.height=h;const f=p.getContext("2d");if(!f){i(e);return}f.imageSmoothingEnabled=!0,f.imageSmoothingQuality="high",f.drawImage(l,0,0,d,h),p.toBlob(m=>{m&&m.size<e.size?i(m):i(e)},o,a)},l.onerror=()=>{URL.revokeObjectURL(c),i(e)},l.src=c})}async function to(e,t="photos",n){const s=tt();if(!s)throw new Error("Supabase configuration missing");const a=n||(e instanceof File?e.name:`asset-${Date.now()}.png`),o=ru(a),i=`${t}/${Date.now()}-${o}`,l=await su(e),c=s.anonKey,d=`${s.url}/storage/v1/object/${rl}/${i}`,h=await fetch(d,{method:"POST",headers:{apikey:c,Authorization:`Bearer ${c}`,"Content-Type":l.type||e.type||"application/octet-stream","x-upsert":"true"},body:l});if(!h.ok){const p=await h.text();let f=p;try{const m=JSON.parse(p);m.message&&(m.message.includes("row-level security")||m.code==="AccessDenied"?f="Storage permission denied (RLS policy missing). Apply migration 20261021160000_create_engine_media_storage_and_drafts.sql in Supabase SQL Editor.":f=m.message)}catch{}throw new Error(`Media upload failed (${h.status}): ${f}`)}return`${s.url}/storage/v1/object/public/${rl}/${i}`}const R={container:"_container_10l68_10",panel:"_panel_10l68_17",formField:"_formField_10l68_23",fieldLabel:"_fieldLabel_10l68_29",requiredMark:"_requiredMark_10l68_38",input:"_input_10l68_43",textarea:"_textarea_10l68_70",checkboxLabel:"_checkboxLabel_10l68_99",checkbox:"_checkbox_10l68_99",segmentedControl:"_segmentedControl_10l68_153",segmentButton:"_segmentButton_10l68_161",segmentButtonActive:"_segmentButtonActive_10l68_182",imagePreviewWrapper:"_imagePreviewWrapper_10l68_189",previewThumb:"_previewThumb_10l68_200",fileRow:"_fileRow_10l68_207",fileStatus:"_fileStatus_10l68_213",hiddenFileInput:"_hiddenFileInput_10l68_219",formatPills:"_formatPills_10l68_223",formatPill:"_formatPill_10l68_223",actions:"_actions_10l68_255",actionGroupRight:"_actionGroupRight_10l68_263"},Tm=new Set(["Click Edit to add narrative text for this section.","Enter narrative text here...","Evidence photograph pending","Narrative text pending","Evidence documentation photo","Photographic proof for this strategic milestone.","Official Google Drive Folder","Evidence Folder"]);function it(e){if(!e)return"";const t=e.trim();return Tm.has(t)?"":e}function sl(e){let t="",n={url:"",label:"",openInNewTab:!1},s={src:"",alt:"",caption:"",showCaption:!1},a={name:"",url:"",reference:"",format:"pdf",size:""};if(!e)return{text:t,link:n,image:s,file:a};if(typeof e=="object"){if("src"in e){const o=e,i=!o.src||o.src.trim().length===0;s={src:o.src||"",alt:i?"":it(o.alt),caption:i?"":it(o.caption),showCaption:i?!1:!!o.showCaption},t=i?"":s.caption||s.alt||s.src}else if("name"in e||"format"in e||"reference"in e){const o=e,i=!o.url||o.url.trim().length===0;a={name:i?"":o.name||"",url:o.url||"",reference:i?"":o.reference||"",format:o.format||"pdf",size:i?"":o.size||""},t=i?"":a.name||a.reference||a.url}else if("url"in e){const o=e,i=!o.url||o.url.trim().length===0;n={url:o.url||"",label:i?"":it(o.label),openInNewTab:i?!1:!!o.openInNewTab},t=i?"":n.label||n.url}return{text:t,link:n,image:s,file:a}}if(typeof e=="string"){const o=e.trim();if(o.startsWith("{"))try{const i=JSON.parse(o);if("src"in i){const c=!i.src||String(i.src).trim().length===0;s={src:i.src||"",alt:c?"":it(i.alt),caption:c?"":it(i.caption),showCaption:c?!1:!!i.showCaption}}if("name"in i||"format"in i||"reference"in i){const c=!i.url||String(i.url).trim().length===0;a={name:c?"":i.name||"",url:i.url||"",reference:c?"":i.reference||"",format:i.format||"pdf",size:c?"":i.size||""}}if("url"in i){const c=!i.url||String(i.url).trim().length===0;n={url:i.url||"",label:c?"":it(i.label),openInNewTab:c?!1:!!i.openInNewTab}}const l=typeof i.text=="string"?i.text:o;return t=it(l),{text:t,link:n,image:s,file:a}}catch{}t=it(o),n.url=/^(https?:\/\/|#|\/)/i.test(o)?o:"",s.src=/\.(jpg|jpeg|png|webp|svg|gif)$/i.test(o)?o:"",a.url=/\.(pdf|docx?|xlsx?)$/i.test(o)?o:"",a.url&&(a.name=o.split("/").pop()||"Document")}return{text:t,link:n,image:s,file:a}}function au(e){switch(e){case"section":return"Section";case"subsection":return"Subsection";case"text":return"Text";case"photo":return"Photo";case"gallery":return"Gallery";default:return"Element"}}const Jn=({isOpen:e,onClose:t,mode:n="edit",elementType:s=null,initialData:a,onSubmit:o,onResetToDefault:i,pointId:l,type:c="text",currentValue:d,defaultValue:h,title:p,isSection:f,isNumbered:m,defaultNumbered:g,onNumberedChange:b,onSave:y,onReset:S})=>{const{isDevMode:v,isDesktop:k,setHasUnpublishedChanges:x,showToast:I}=Oe(),{pushAction:N}=Ks(),_=!!(s||o),[T,w]=u.useState(()=>a?{title:a.title||"",isNumbered:a.isNumbered!==!1,content:it(a.content),as:a.as||"p",src:a.src||"",alt:it(a.alt),caption:it(a.caption),showCaption:!!(a.showCaption||a.caption&&a.caption.trim().length>0),driveUrl:a.driveUrl||""}:{title:"",isNumbered:!0,content:"",as:"p",src:"",alt:"",caption:"",showCaption:!1,driveUrl:""}),[M,$]=u.useState(""),[A,P]=u.useState({url:"",label:"",openInNewTab:!1}),[V,D]=u.useState({src:"",alt:"",caption:"",showCaption:!1}),[W,H]=u.useState({name:"",url:"",reference:"",format:"pdf",size:""}),q=!!(f||s==="section"||l&&/(^|\.)section(\.|$)/i.test(l)&&!l.endsWith(".subtitle")),j=l?`${l}.isNumbered`:"",[z,O]=u.useState(!0),[U,Q]=u.useState("upload"),[se,ae]=u.useState(!1),[de,B]=u.useState(null),Y=u.useRef(null),ee=u.useRef(null),X=u.useRef(null);u.useEffect(()=>{e&&(!v||!k)&&t()},[e,v,k,t]),u.useEffect(()=>{if(!e)return;if(_){const G={title:(a==null?void 0:a.title)||"",isNumbered:(a==null?void 0:a.isNumbered)!==!1,content:it(a==null?void 0:a.content),as:(a==null?void 0:a.as)||"p",src:(a==null?void 0:a.src)||"",alt:it(a==null?void 0:a.alt),caption:it(a==null?void 0:a.caption),showCaption:!!(a!=null&&a.showCaption||a!=null&&a.caption&&a.caption.trim().length>0),driveUrl:(a==null?void 0:a.driveUrl)||""};w(G);const le=!!(G.src&&!G.src.startsWith("data:"));Q(le?"url":"upload")}else{const G=sl(d);$(G.text),P(G.link),D(G.image),H(G.file);const le=!!(G.image.src&&!G.image.src.startsWith("data:"));if(Q(le?"url":"upload"),q&&j){const ue=wn(j,"",v);O(ue!==""?ue==="true":m!==void 0?m:g!==void 0?g:!0)}}const L=setTimeout(()=>{var G;(G=X.current)==null||G.focus()},50);return()=>clearTimeout(L)},[e,_,a,d,q,j,m,g,v]);const te=u.useMemo(()=>{if(!e)return!1;if(_){const L=(a==null?void 0:a.title)||"",G=it(a==null?void 0:a.content),le=(a==null?void 0:a.src)||"",ue=it(a==null?void 0:a.alt),he=it(a==null?void 0:a.caption),oe=(a==null?void 0:a.driveUrl)||"",ye=(a==null?void 0:a.isNumbered)!==!1;return(T.title||"")!==L||(T.content||"")!==G||(T.src||"")!==le||(T.alt||"")!==ue||(T.caption||"")!==he||(T.driveUrl||"")!==oe||T.isNumbered!==ye}else{const L=sl(d);return M!==L.text||A.url!==L.link.url||A.label!==L.link.label||V.src!==L.image.src||V.alt!==L.image.alt||V.caption!==L.image.caption||W.url!==L.file.url||W.name!==L.file.name}},[e,_,T,a,M,A,V,W,d]);eo(e&&te,l?`universal-edit-${l}`:"universal-edit-modal");const K=u.useCallback(async L=>{var ue;const G=(ue=L.target.files)==null?void 0:ue[0];if(!G)return;const le=G.name.replace(/\.[^/.]+$/,"");ae(!0),B(null);try{const he=await to(G,"photos");_?w(oe=>({...oe,src:he,alt:oe.alt||le})):D(oe=>({...oe,src:he,alt:oe.alt||le}))}catch(he){console.error("[UniversalEditModal] Photo upload failed:",he),B(he instanceof Error?he.message:"Photo upload failed")}finally{ae(!1)}},[_]),J=u.useCallback(async L=>{var he,oe;const G=(he=L.target.files)==null?void 0:he[0];if(!G)return;const le=(oe=G.name.split(".").pop())==null?void 0:oe.toLowerCase();let ue="other";le==="pdf"?ue="pdf":le==="doc"||le==="docx"?ue="doc":(le==="xls"||le==="xlsx"||le==="csv")&&(ue="sheet"),ae(!0),B(null);try{const ye=await to(G,"documents");H(xe=>({...xe,name:G.name,url:ye,format:ue,size:`${(G.size/1024).toFixed(1)} KB`}))}catch(ye){console.error("[UniversalEditModal] Document upload failed:",ye),B(ye instanceof Error?ye.message:"Document upload failed")}finally{ae(!1)}},[]),Z=()=>{if(_&&o){o(T),x(!0),I(n==="add"?"Element added to canvas.":"Changes saved to draft successfully.","success"),t();return}let L="",G;switch(c){case"text":L=M;break;case"link":L=JSON.stringify(A),G=A;break;case"image":L=JSON.stringify(V),G=V;break;case"file":L=JSON.stringify(W),G=W;break}if(q&&j&&(nn(j,String(z),!0),b==null||b(z)),l){const le=wn(l,typeof h=="string"?h:h?JSON.stringify(h):"",!0);le!==L&&N({type:"content_text_override",description:`Edit text for ${l}`,undo:()=>{nn(l,le,!0)},redo:()=>{nn(l,L,!0)}}),nn(l,L,!0)}y&&y(L,c,G),x(!0),I("Changes saved to draft successfully.","success"),t()},ne=()=>{if(_){i&&i(),x(!0),I("Reset to default baseline.","info"),t();return}if(l){const G=wn(l,"",!0),le=typeof h=="string"?h:h?JSON.stringify(h):"";br(l,!0),G&&G!==le&&N({type:"content_text_override",description:`Reset text for ${l}`,undo:()=>{nn(l,G,!0)},redo:()=>{br(l,!0)}})}if(q&&j){br(j,!0);const G=g!==void 0?g:!0;O(G),b==null||b(G)}S&&S();const L=sl(h);$(L.text),P(L.link),D(L.image),H(L.file),x(!0),I("Reset to default baseline.","info"),t()},ie=u.useMemo(()=>{if(p)return p;if(_&&s){const L=au(s);return n==="add"?`Add ${L}`:`Edit ${L}`}return q?"Edit Section":c==="image"?"Edit Photo":c==="link"?"Edit Link":c==="file"?"Edit Document":"Edit Text"},[p,_,s,n,q,c]),F=u.useMemo(()=>_&&n==="add"?`Add ${au(s)}`:"Save Changes",[_,n,s]);return r.jsx(bt,{isOpen:e,onClose:t,onConfirm:se?void 0:Z,title:ie,maxWidth:"500px",ariaLabel:ie,children:r.jsxs("div",{className:R.container,children:[_&&s==="section"&&r.jsxs("div",{className:R.panel,children:[r.jsxs("div",{className:R.formField,children:[r.jsxs("label",{className:R.fieldLabel,htmlFor:"edit-modal-section-title",children:["Section Title ",r.jsx("span",{className:R.requiredMark,children:"*"})]}),r.jsx("input",{id:"edit-modal-section-title",ref:L=>{X.current=L},type:"text",className:R.input,value:T.title||"",onChange:L=>w(G=>({...G,title:L.target.value})),placeholder:"e.g. Strategic Academic Intervention","aria-label":"Section Title"})]}),r.jsx("div",{className:R.formField,children:r.jsxs("label",{className:R.checkboxLabel,children:[r.jsx("input",{type:"checkbox",className:R.checkbox,checked:T.isNumbered!==!1,onChange:L=>w(G=>({...G,isNumbered:L.target.checked}))}),r.jsxs("span",{children:["Numbered section",r.jsx(Xn,{text:"Adds a number before the title, like I or II.",label:"Numbered section"})]})]})})]}),_&&s==="subsection"&&r.jsx("div",{className:R.panel,children:r.jsxs("div",{className:R.formField,children:[r.jsxs("label",{className:R.fieldLabel,htmlFor:"canvas-subsection-title",children:["Subsection Title ",r.jsx("span",{className:R.requiredMark,children:"*"})]}),r.jsx("input",{id:"canvas-subsection-title",ref:L=>{X.current=L},type:"text",className:R.input,value:T.title||"",onChange:L=>w(G=>({...G,title:L.target.value})),placeholder:"e.g. Implementation Milestones","aria-label":"Subsection Title"})]})}),_&&s==="text"&&r.jsxs("div",{className:R.panel,children:[r.jsxs("div",{className:R.formField,children:[r.jsx("label",{className:R.fieldLabel,children:"Typography Style"}),r.jsxs("div",{className:R.segmentedControl,role:"radiogroup","aria-label":"Typography Style",children:[r.jsx("button",{type:"button",role:"radio","aria-checked":T.as!=="blockquote",className:`${R.segmentButton} ${T.as!=="blockquote"?R.segmentButtonActive:""}`,onClick:()=>w(L=>({...L,as:"p"})),children:"Paragraph"}),r.jsx("button",{type:"button",role:"radio","aria-checked":T.as==="blockquote",className:`${R.segmentButton} ${T.as==="blockquote"?R.segmentButtonActive:""}`,onClick:()=>w(L=>({...L,as:"blockquote"})),children:"Quote / Callout"})]})]}),r.jsxs("div",{className:R.formField,children:[r.jsxs("label",{className:R.fieldLabel,htmlFor:"canvas-text-content",children:["Narrative Text",r.jsx("span",{className:R.requiredMark,children:"*"})]}),r.jsx("textarea",{id:"canvas-text-content",ref:L=>{X.current=L},className:R.textarea,value:T.content||"",onChange:L=>w(G=>({...G,content:L.target.value})),placeholder:"Enter narrative text or editorial testimony...",rows:5,"aria-label":"Narrative Text Content"})]})]}),_&&s==="photo"&&r.jsxs("div",{className:R.panel,children:[r.jsxs("div",{className:R.formField,children:[r.jsx("label",{className:R.fieldLabel,children:"Photo Source"}),r.jsxs("div",{className:R.segmentedControl,role:"radiogroup","aria-label":"Photo Source",children:[r.jsx("button",{type:"button",role:"radio","aria-checked":U==="upload",className:`${R.segmentButton} ${U==="upload"?R.segmentButtonActive:""}`,onClick:()=>Q("upload"),children:"Upload Photo"}),r.jsx("button",{type:"button",role:"radio","aria-checked":U==="url",className:`${R.segmentButton} ${U==="url"?R.segmentButtonActive:""}`,onClick:()=>Q("url"),children:"Photo URL"})]})]}),U==="upload"?r.jsxs("div",{className:R.fileRow,children:[r.jsx(me,{type:"button",variant:"secondary",size:"sm",onClick:()=>{var L;return(L=Y.current)==null?void 0:L.click()},children:"Upload Photo"}),r.jsx("input",{ref:Y,type:"file",accept:"image/png,image/jpeg,image/webp,image/gif",className:R.hiddenFileInput,onChange:K,"aria-label":"Upload photo file"}),r.jsx("span",{className:R.fileStatus,children:T.src?"Photo selected":"No photo chosen"})]}):r.jsxs("div",{className:R.formField,children:[r.jsxs("label",{className:R.fieldLabel,htmlFor:"canvas-photo-url",children:["Photo URL ",r.jsx("span",{className:R.requiredMark,children:"*"})]}),r.jsx("input",{id:"canvas-photo-url",ref:L=>{X.current=L},type:"text",className:R.input,value:T.src||"",onChange:L=>w(G=>({...G,src:L.target.value})),placeholder:"https://.../photo.webp","aria-label":"Photo URL"})]}),T.src?r.jsx("div",{className:R.imagePreviewWrapper,children:r.jsx("img",{src:T.src,alt:T.alt||"Preview",className:R.previewThumb})}):null,r.jsxs("div",{className:R.formField,children:[r.jsx("label",{className:R.fieldLabel,htmlFor:"canvas-photo-alt",children:"Alt Text (Accessibility)"}),r.jsx("input",{id:"canvas-photo-alt",type:"text",className:R.input,value:T.alt||"",onChange:L=>w(G=>({...G,alt:L.target.value})),placeholder:"Descriptive image summary for screen readers","aria-label":"Photo Alt Text"})]}),r.jsx("div",{className:R.formField,children:r.jsxs("label",{className:R.checkboxLabel,children:[r.jsx("input",{type:"checkbox",className:R.checkbox,checked:!!T.showCaption,onChange:L=>w(G=>({...G,showCaption:L.target.checked}))}),r.jsx("span",{children:"Show caption below photo"})]})}),T.showCaption?r.jsxs("div",{className:R.formField,children:[r.jsx("label",{className:R.fieldLabel,htmlFor:"canvas-photo-caption",children:"Caption"}),r.jsx("input",{id:"canvas-photo-caption",type:"text",className:R.input,value:T.caption||"",onChange:L=>w(G=>({...G,caption:L.target.value})),placeholder:"Photo caption or description","aria-label":"Photo Caption"})]}):null]}),_&&s==="gallery"&&r.jsxs("div",{className:R.panel,children:[r.jsxs("div",{className:R.formField,children:[r.jsxs("label",{className:R.fieldLabel,htmlFor:"canvas-gallery-title",children:["Gallery Title ",r.jsx("span",{className:R.requiredMark,children:"*"})]}),r.jsx("input",{id:"canvas-gallery-title",ref:L=>{X.current=L},type:"text",className:R.input,value:T.title||"",onChange:L=>w(G=>({...G,title:L.target.value})),placeholder:"e.g. Mid-Year Assessment & Verification","aria-label":"Gallery Title"})]}),r.jsxs("div",{className:R.formField,children:[r.jsxs("label",{className:R.fieldLabel,htmlFor:"canvas-gallery-drive",children:["Google Drive Repository URL ",r.jsx("span",{className:R.requiredMark,children:"*"}),r.jsx(Xn,{text:"A link to an online folder with more photos or files.",label:"Folder Link"})]}),r.jsx("input",{id:"canvas-gallery-drive",type:"text",className:R.input,value:T.driveUrl||"",onChange:L=>w(G=>({...G,driveUrl:L.target.value})),placeholder:"https://drive.google.com/drive/folders/...","aria-label":"Google Drive URL"})]})]}),!_&&c==="text"&&r.jsx("div",{className:R.panel,children:q?r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:R.formField,children:[r.jsxs("label",{className:R.fieldLabel,htmlFor:"edit-modal-section-title",children:["Section Title",r.jsx("span",{className:R.requiredMark,children:"*"})]}),r.jsx("input",{id:"edit-modal-section-title",ref:L=>{X.current=L},type:"text",className:R.input,value:M,onChange:L=>$(L.target.value),placeholder:"e.g. Strategic Academic Intervention","aria-label":"Section Title"})]}),r.jsx("div",{className:R.formField,children:r.jsxs("label",{className:R.checkboxLabel,children:[r.jsx("input",{type:"checkbox",className:R.checkbox,checked:z,onChange:L=>O(L.target.checked)}),r.jsxs("span",{children:["Numbered section",r.jsx(Xn,{text:"Adds a number before the title, like I or II.",label:"Numbered section"})]})]})})]}):r.jsxs("div",{className:R.formField,children:[r.jsxs("label",{className:R.fieldLabel,htmlFor:"dev-modal-generic-text",children:["Content",r.jsx("span",{className:R.requiredMark,children:"*"})]}),r.jsx("textarea",{id:"dev-modal-generic-text",ref:L=>{X.current=L},className:R.textarea,value:M,onChange:L=>$(L.target.value),placeholder:"Enter text, title, or description...",rows:5,"aria-label":ie})]})}),!_&&c==="link"&&r.jsxs("div",{className:R.panel,children:[r.jsxs("div",{className:R.formField,children:[r.jsxs("label",{className:R.fieldLabel,htmlFor:"dev-modal-link-url",children:["URL ",r.jsx("span",{className:R.requiredMark,children:"*"})]}),r.jsx("input",{id:"dev-modal-link-url",ref:L=>{X.current=L},type:"text",className:R.input,value:A.url,onChange:L=>P(G=>({...G,url:L.target.value})),placeholder:"https://... or #overview","aria-label":"Link URL"})]}),r.jsxs("div",{className:R.formField,children:[r.jsx("label",{className:R.fieldLabel,htmlFor:"dev-modal-link-label",children:"Label"}),r.jsx("input",{id:"dev-modal-link-label",type:"text",className:R.input,value:A.label,onChange:L=>P(G=>({...G,label:L.target.value})),placeholder:"Button or hyperlink label","aria-label":"Link Label"})]}),r.jsx("div",{className:R.formField,children:r.jsxs("label",{className:R.checkboxLabel,children:[r.jsx("input",{type:"checkbox",className:R.checkbox,checked:!!A.openInNewTab,onChange:L=>P(G=>({...G,openInNewTab:L.target.checked}))}),r.jsx("span",{children:"Open in new tab"})]})})]}),!_&&c==="image"&&r.jsxs("div",{className:R.panel,children:[r.jsxs("div",{className:R.formField,children:[r.jsx("label",{className:R.fieldLabel,children:"Photo Source"}),r.jsxs("div",{className:R.segmentedControl,role:"radiogroup","aria-label":"Photo Source",children:[r.jsx("button",{type:"button",role:"radio","aria-checked":U==="upload",className:`${R.segmentButton} ${U==="upload"?R.segmentButtonActive:""}`,onClick:()=>Q("upload"),children:"Upload Photo"}),r.jsx("button",{type:"button",role:"radio","aria-checked":U==="url",className:`${R.segmentButton} ${U==="url"?R.segmentButtonActive:""}`,onClick:()=>Q("url"),children:"Photo URL"})]})]}),U==="upload"?r.jsxs("div",{className:R.fileRow,children:[r.jsx(me,{type:"button",variant:"secondary",size:"sm",onClick:()=>{var L;return(L=Y.current)==null?void 0:L.click()},children:"Upload Photo"}),r.jsx("input",{ref:Y,type:"file",accept:"image/png,image/jpeg,image/webp,image/gif",className:R.hiddenFileInput,onChange:K,"aria-label":"Upload photo file"}),r.jsx("span",{className:R.fileStatus,children:V.src?"Photo selected":"No photo chosen"})]}):r.jsxs("div",{className:R.formField,children:[r.jsxs("label",{className:R.fieldLabel,htmlFor:"dev-modal-image-url",children:["Photo URL ",r.jsx("span",{className:R.requiredMark,children:"*"})]}),r.jsx("input",{id:"dev-modal-image-url",ref:L=>{X.current=L},type:"text",className:R.input,value:V.src,onChange:L=>D(G=>({...G,src:L.target.value})),placeholder:"https://.../photo.webp","aria-label":"Photo URL"})]}),V.src?r.jsx("div",{className:R.imagePreviewWrapper,children:r.jsx("img",{src:V.src,alt:V.alt||"Preview",className:R.previewThumb})}):null,r.jsxs("div",{className:R.formField,children:[r.jsx("label",{className:R.fieldLabel,htmlFor:"dev-modal-image-alt",children:"Alt Text (Accessibility)"}),r.jsx("input",{id:"dev-modal-image-alt",type:"text",className:R.input,value:V.alt,onChange:L=>D(G=>({...G,alt:L.target.value})),placeholder:"Descriptive image summary for screen readers","aria-label":"Photo Alt Text"})]}),r.jsx("div",{className:R.formField,children:r.jsxs("label",{className:R.checkboxLabel,children:[r.jsx("input",{type:"checkbox",className:R.checkbox,checked:!!V.showCaption,onChange:L=>D(G=>({...G,showCaption:L.target.checked}))}),r.jsx("span",{children:"Show caption below photo"})]})}),V.showCaption?r.jsxs("div",{className:R.formField,children:[r.jsx("label",{className:R.fieldLabel,htmlFor:"dev-modal-image-caption",children:"Caption"}),r.jsx("input",{id:"dev-modal-image-caption",type:"text",className:R.input,value:V.caption,onChange:L=>D(G=>({...G,caption:L.target.value})),placeholder:"Image caption text","aria-label":"Photo Caption"})]}):null]}),!_&&c==="file"&&r.jsxs("div",{className:R.panel,children:[r.jsxs("div",{className:R.formField,children:[r.jsxs("label",{className:R.fieldLabel,htmlFor:"dev-modal-file-name",children:["Document Name ",r.jsx("span",{className:R.requiredMark,children:"*"})]}),r.jsx("input",{id:"dev-modal-file-name",ref:L=>{X.current=L},type:"text",className:R.input,value:W.name,onChange:L=>H(G=>({...G,name:L.target.value})),placeholder:"e.g. Plan 2025-2028","aria-label":"Document Name"})]}),r.jsxs("div",{className:R.formField,children:[r.jsxs("label",{className:R.fieldLabel,htmlFor:"dev-modal-file-url",children:["Document URL ",r.jsx("span",{className:R.requiredMark,children:"*"})]}),r.jsx("input",{id:"dev-modal-file-url",type:"text",className:R.input,value:W.url,onChange:L=>H(G=>({...G,url:L.target.value})),placeholder:"https://.../document.pdf or Google Drive link","aria-label":"Document URL"})]}),r.jsxs("div",{className:R.formField,children:[r.jsx("label",{className:R.fieldLabel,children:"Format"}),r.jsx("div",{className:R.formatPills,children:["pdf","doc","sheet","other"].map(L=>r.jsx("button",{type:"button",className:R.formatPill,"data-active":W.format===L?"true":"false",onClick:()=>H(G=>({...G,format:L})),children:L},L))})]}),r.jsxs("div",{className:R.fileRow,children:[r.jsx(me,{type:"button",variant:"secondary",size:"sm",onClick:()=>{var L;return(L=ee.current)==null?void 0:L.click()},children:"Upload Document"}),r.jsx("input",{ref:ee,type:"file",accept:".pdf,.doc,.docx,.xls,.xlsx,.csv",className:R.hiddenFileInput,onChange:J,"aria-label":"Upload document file"}),r.jsx("span",{className:R.fileStatus,children:W.url?W.url.startsWith("data:")?"Local file selected":"Document linked":"No file chosen"})]})]}),r.jsxs("div",{className:R.actions,children:[r.jsx("div",{children:(n==="edit"||i||S||h)&&r.jsx(me,{type:"button",variant:"ghost",size:"sm",onClick:ne,children:"Reset to default"})}),r.jsxs("div",{className:R.actionGroupRight,children:[de&&r.jsx("span",{style:{fontSize:"0.8125rem",color:"var(--color-danger, #e11d48)",marginRight:"8px"},children:de}),r.jsx(me,{type:"button",variant:"secondary",size:"sm",onClick:t,disabled:se,children:"Cancel"}),r.jsx(me,{type:"button",variant:"primary",size:"sm",onClick:Z,disabled:se,children:se?"Uploading...":F})]})]})]})})},Pe={wrapper:"_wrapper_l8ktk_7",inlineWrapper:"_inlineWrapper_l8ktk_19",textWrapper:"_textWrapper_l8ktk_32",imageWrapper:"_imageWrapper_l8ktk_33",controlsBar:"_controlsBar_l8ktk_37",indicatorSlotBadge:"_indicatorSlotBadge_l8ktk_69",driveButton:"_driveButton_l8ktk_126",textBadge:"_textBadge_l8ktk_146",textContent:"_textContent_l8ktk_166",textContentInline:"_textContentInline_l8ktk_174",imageContent:"_imageContent_l8ktk_181",highlightedTarget:"_highlightedTarget_l8ktk_190",imageBadge:"_imageBadge_l8ktk_202",indicatorBox:"_indicatorBox_l8ktk_209",emptyPlaceholder:"_emptyPlaceholder_l8ktk_245",emptyPlaceholderInline:"_emptyPlaceholderInline_l8ktk_256",emptyTextBadge:"_emptyTextBadge_l8ktk_267"},Qn=({pointId:e,type:t="text",onEditText:n,onEditSource:s,driveUrl:a,currentValue:o,defaultValue:i,onSave:l,onReset:c,children:d,className:h,inline:p=!1,isSection:f,isNumbered:m,defaultNumbered:g,onNumberedChange:b,editTriggerId:y})=>{const{isDevMode:S,isDesktop:v,setHasUnpublishedChanges:k}=Oe(),[x,I]=u.useState(!1),[N,_]=u.useState(!1);if(u.useEffect(()=>{(!S||!v)&&x&&I(!1)},[S,v,x]),!S||!v)return r.jsx(r.Fragment,{children:d});const T=o!==void 0?o:e?typeof i=="object"?si(e,i,S):wn(e,typeof i=="string"?i:"",S):"",w=i!==void 0?i:T,M=H=>{H.stopPropagation(),n?n():e&&I(!0)},$=(H,q,j)=>{l?l(H):e&&nn(e,H,!0),k(!0)},A=()=>{c?c():e&&br(e,!0),k(!0)},P=t==="image"?"image":t==="file"?"file":t==="link"||t==="source"?"link":"text";if(t==="source")return r.jsxs("div",{className:`${Pe.wrapper} ${h||""}`,children:[r.jsxs("div",{className:Pe.controlsBar,children:[r.jsx(me,{type:"button",variant:"admin",size:"xs","data-dev-edit-trigger":"true","data-canvas-edit-trigger":y,onClick:s||M,onMouseEnter:()=>_(!0),onMouseLeave:()=>_(!1),title:`Edit source for ${e||"item"}`,"aria-label":`Edit source for ${e||"item"}`,children:"✎ Edit"}),a&&r.jsx(me,{as:"a",href:a,target:"_blank",rel:"noopener noreferrer",variant:"admin",size:"xs",className:Pe.driveButton,title:"Open linked Google Drive folder",children:"Drive Folder ↗"})]}),r.jsx("div",{className:`${Pe.textContent} ${N?Pe.highlightedTarget:""}`,children:d}),e&&r.jsx(Jn,{isOpen:x,pointId:e,type:P,currentValue:T,defaultValue:w,onSave:$,onReset:A,onClose:()=>I(!1)})]});if(t==="indicator")return r.jsx("div",{className:`${Pe.wrapper} ${h||""}`,children:r.jsxs("div",{className:Pe.indicatorBox,children:[r.jsx("div",{className:Pe.controlsBar,children:r.jsx("span",{className:Pe.indicatorSlotBadge,children:"Live Slot · Awaiting Official Indicators"})}),d]})});if(t==="image")return r.jsxs("div",{className:`${Pe.imageWrapper} ${h||""}`,children:[r.jsx("div",{className:Pe.imageBadge,onClick:H=>H.stopPropagation(),children:r.jsx(me,{type:"button",variant:"admin",size:"xs","data-dev-edit-trigger":"true","data-canvas-edit-trigger":y,onClick:M,onMouseEnter:()=>_(!0),onMouseLeave:()=>_(!1),title:`Edit image for ${e||"item"}`,"aria-label":`Edit image for ${e||"item"}`,children:"✎ Edit"})}),r.jsx("div",{className:`${Pe.imageContent} ${N?Pe.highlightedTarget:""}`,children:d}),e&&r.jsx(Jn,{isOpen:x,pointId:e,type:"image",currentValue:T,defaultValue:w,onSave:$,onReset:A,onClose:()=>I(!1)})]});if(t==="file"||t==="link")return r.jsxs("div",{className:`${Pe.inlineWrapper} ${h||""}`,children:[r.jsx("span",{className:`${Pe.textContentInline} ${N?Pe.highlightedTarget:""}`,children:d}),r.jsx(me,{type:"button",variant:"admin",size:"xs","data-dev-edit-trigger":"true","data-canvas-edit-trigger":y,onClick:M,onMouseEnter:()=>_(!0),onMouseLeave:()=>_(!1),title:`Edit ${t} for ${e||"item"}`,"aria-label":`Edit ${t} for ${e||"item"}`,children:"✎ Edit"}),e&&r.jsx(Jn,{isOpen:x,pointId:e,type:P,currentValue:T,defaultValue:w,onSave:$,onReset:A,onClose:()=>I(!1)})]});const V=u.Children.toArray(d).some(H=>{if(typeof H=="string")return H.trim().length>0;if(typeof H=="number")return!0;if(u.isValidElement(H)){const q=H.props||{};return q.children&&typeof q.children=="string"?q.children.trim().length>0:!0}return!1}),D=typeof T=="string"&&(T==="Click Edit to add narrative text for this section."||T==="Enter narrative text here..."||T==="Evidence photograph pending"||T==="Narrative text pending"),W=t==="text"&&(!T||String(T).trim().length===0||D)&&(!V||D);return p?r.jsxs("span",{className:`${Pe.inlineWrapper} ${h||""}`,children:[r.jsx("span",{className:`${Pe.textContentInline} ${N?Pe.highlightedTarget:""}`,children:W?r.jsx("span",{className:Pe.emptyPlaceholderInline,children:r.jsx("span",{className:Pe.emptyTextBadge,children:"Empty"})}):d}),r.jsx(me,{type:"button",variant:"admin",size:"xs","data-dev-edit-trigger":"true","data-canvas-edit-trigger":y,onClick:M,onMouseEnter:()=>_(!0),onMouseLeave:()=>_(!1),title:`Edit ${e||"content"}`,"aria-label":`Edit ${e||"content"}`,children:"✎ Edit"}),e&&r.jsx(Jn,{isOpen:x,pointId:e,type:P,currentValue:W?"":T,defaultValue:W?"":w,isSection:f,isNumbered:m,defaultNumbered:g,onNumberedChange:b,onSave:$,onReset:A,onClose:()=>I(!1)})]}):r.jsxs("div",{className:`${Pe.textWrapper} ${h||""}`,children:[r.jsx("div",{className:Pe.textBadge,children:r.jsx(me,{type:"button",variant:"admin",size:"xs","data-dev-edit-trigger":"true","data-canvas-edit-trigger":y,onClick:M,onMouseEnter:()=>_(!0),onMouseLeave:()=>_(!1),title:`Edit ${e||"content"}`,"aria-label":`Edit ${e||"content"}`,children:"✎ Edit"})}),r.jsx("div",{className:`${Pe.textContent} ${N?Pe.highlightedTarget:""}`,children:W?r.jsx("div",{className:Pe.emptyPlaceholder,children:r.jsx("span",{className:Pe.emptyTextBadge,children:"Empty"})}):d}),e&&r.jsx(Jn,{isOpen:x,pointId:e,type:P,currentValue:W?"":T,defaultValue:W?"":w,isSection:f,isNumbered:m,defaultNumbered:g,onNumberedChange:b,onSave:$,onReset:A,onClose:()=>I(!1)})]})};function Hr(e,t,n){const{isDevMode:s}=Oe(),a=s,o=u.useCallback(p=>Uc(e,p,a),[e,a]),i=u.useCallback(()=>zc(e,t,a),[e,t,a]),l=u.useSyncExternalStore(o,i,i),c=Pc(e,a),d=u.useCallback(p=>{nn(e,p,a)},[e,a]),h=u.useCallback(()=>{br(e,a)},[e,a]);return{text:l,isModified:c,setText:d,setValue:d,resetText:h,resetValue:h}}const Ye={heroSection:"_heroSection_1f0hs_6",heroBackgroundCard:"_heroBackgroundCard_1f0hs_23",ambientMesh:"_ambientMesh_1f0hs_42",heroContainer:"_heroContainer_1f0hs_72",kickerWrap:"_kickerWrap_1f0hs_86",kickerCenter:"_kickerCenter_1f0hs_94",kickerPill:"_kickerPill_1f0hs_100",kickerPrefix:"_kickerPrefix_1f0hs_106",kickerMeaning:"_kickerMeaning_1f0hs_110",heroTitle:"_heroTitle_1f0hs_115",titleLine:"_titleLine_1f0hs_127",bukasGradient:"_bukasGradient_1f0hs_138",heroSubtitle:"_heroSubtitle_1f0hs_155",subtitleLine:"_subtitleLine_1f0hs_164",heroCtaWrap:"_heroCtaWrap_1f0hs_169",ctaButtonCenter:"_ctaButtonCenter_1f0hs_178",heroStartButton:"_heroStartButton_1f0hs_184"},ou="Folio Engine — Management, Accountability & Systematic Collection of Data",al="Responsableng estudyante na may Galing, Husay, at Talino",ol="A configurable multi-stage sequence.",il=({kickerText:e,title:t,subtitle:n,onStartJourney:s,heroCtaRef:a,heroSlotRef:o})=>{const i=Hr("hero.kicker",ou),l=Hr("hero.title",al),c=Hr("hero.subtitle",ol),d=Hr("hero.cta","Start Journey"),h=e??i.text,p=()=>{if(!h)return null;if(typeof h=="string"&&h.includes(" — ")){const g=h.indexOf(" — "),b=h.slice(0,g+3),y=h.slice(g+3);return r.jsxs(r.Fragment,{children:[r.jsx("span",{className:Ye.kickerPrefix,children:b}),r.jsx("span",{className:Ye.kickerMeaning,children:y})]})}return h},f=()=>t||(l.text===al?r.jsxs(r.Fragment,{children:[r.jsxs("span",{className:Ye.titleLine,children:["Responsableng ",r.jsx("span",{className:Ye.bukasGradient,children:"estudyante"})]}),r.jsx("span",{className:Ye.titleLine,children:"na may Galing, Husay, at Talino"})]}):r.jsx("span",{className:Ye.titleLine,children:l.text})),m=()=>n?r.jsx("span",{className:Ye.subtitleLine,children:n}):c.text===ol?r.jsxs(r.Fragment,{children:[r.jsx("span",{className:Ye.subtitleLine,children:"A configurable multi-stage sequence."}),r.jsx("span",{className:Ye.subtitleLine})]}):r.jsx("span",{className:Ye.subtitleLine,children:c.text});return r.jsxs("section",{id:"hero",className:Ye.heroSection,"aria-labelledby":"hero-title",children:[r.jsx("div",{className:Ye.heroBackgroundCard,"aria-hidden":"true",children:r.jsx("div",{className:Ye.ambientMesh})}),r.jsxs("div",{className:Ye.heroContainer,children:[h&&r.jsx("div",{className:Ye.kickerWrap,children:r.jsx(Qn,{pointId:"hero.kicker",defaultValue:ou,currentValue:i.text,children:r.jsx("div",{className:Ye.kickerCenter,children:r.jsx(qs,{label:p(),variant:"white",className:Ye.kickerPill,ariaLabel:typeof h=="string"?h:void 0})})})}),r.jsx(Qn,{pointId:"hero.title",defaultValue:al,currentValue:l.text,children:r.jsx("h1",{id:"hero-title",className:Ye.heroTitle,children:f()})}),r.jsx(Qn,{pointId:"hero.subtitle",defaultValue:ol,currentValue:c.text,children:r.jsx("p",{className:Ye.heroSubtitle,children:m()})}),r.jsx("div",{ref:o||a,className:Ye.heroCtaWrap,children:r.jsx(Qn,{pointId:"hero.cta",defaultValue:"Start Journey",currentValue:d.text,children:r.jsx("div",{className:Ye.ctaButtonCenter,children:r.jsx(me,{as:"button",type:"button",variant:"revolving-outline",outlineWidth:4,size:"lg",revolving:!0,pulse:!0,onClick:s,className:Ye.heroStartButton,"aria-label":"Start Journey through the Plan",children:d.text})})})})]})]})};let hn=null,Vr=!0;if(typeof window<"u"){const e=t=>{var n;Vr&&((n=t.target)!=null&&n.closest('button, a, [role="button"]')||no())};window.addEventListener("wheel",e,{passive:!0}),window.addEventListener("touchstart",e,{passive:!0})}function no(){hn!==null&&(cancelAnimationFrame(hn),hn=null,Vr=!0)}function Am(e){return 1-Math.pow(1-e,3)}function Ys({top:e,duration:t,onComplete:n,interruptible:s=!0}){if(typeof window>"u")return;if(Vr=s,document.documentElement.style.scrollBehavior!=="auto"&&(document.documentElement.style.scrollBehavior="auto"),window.matchMedia("(prefers-reduced-motion: reduce)").matches){window.scrollTo(0,e),Vr=!0,n==null||n();return}hn!==null&&(cancelAnimationFrame(hn),hn=null);const o=window.scrollY||window.pageYOffset,i=e-o;if(Math.abs(i)<2){Vr=!0,n==null||n();return}const l=t??Math.min(3e3,Math.max(1600,Math.round(1500+Math.sqrt(Math.abs(i))*32))),c=performance.now(),d=h=>{const p=h-c,f=Math.min(p/l,1),m=Am(f);window.scrollTo(0,Math.round(o+i*m)),f<1?hn=requestAnimationFrame(d):(hn=null,Vr=!0,n==null||n())};hn=requestAnimationFrame(d)}const iu=e=>{const t=u.useRef(0),n=u.useRef(new Set),[s,a]=u.useState(1),[o,i]=u.useState("above"),[l,c]=u.useState(!1),d=u.useRef("above"),h=u.useRef(!1),p=u.useRef(1),f=u.useRef(!1),m=u.useCallback(()=>{if(!e.current)return;const y=window.innerHeight||document.documentElement.clientHeight,S=Math.min(260,Math.max(180,Math.round(y*.26))),v=e.current.querySelectorAll("[data-node]");let k=0,x="inside",I=1;if(v.length>=2){const _=v[0],T=v[v.length-1],w=_.getBoundingClientRect().top,M=T.getBoundingClientRect().top,$=M-w;if($>0){const V=(S-w)/$;k=Math.min(Math.max(V,0),1)}const A=$/4;w>S+120?x="above":M<S-A*.75?x="below":x="inside";let P=1/0;v.forEach(V=>{const D=Number(V.dataset.node);if(!isNaN(D)){const W=V.getBoundingClientRect().top,H=Math.abs(S-W);H<P&&(P=H,I=D)}})}else{const _=e.current.getBoundingClientRect(),T=_.height-y;T>0&&(k=Math.min(Math.max((S-_.top)/T,0),1)),_.top>S?x="above":_.bottom<S&&(x="below")}t.current=k,n.current.forEach(_=>_(k)),d.current!==x&&(d.current=x,i(x));const N=x==="inside";h.current!==N&&(h.current=N,c(N)),p.current!==I&&(p.current=I,a(I))},[e]),g=u.useCallback(y=>(n.current.add(y),y(t.current),()=>{n.current.delete(y)}),[]),b=u.useCallback((y,S)=>{if(!e.current)return;const v=e.current.querySelector(`[data-node="${y}"]`);if(v){const k=v.getBoundingClientRect(),x=window.scrollY||window.pageYOffset,I=window.innerHeight,N=Math.min(260,Math.max(180,Math.round(I*.26))),_=x+k.top-N;Ys({top:Math.max(0,_),interruptible:!1,onComplete:S})}else{const k=e.current.getBoundingClientRect(),x=window.scrollY||window.pageYOffset,I=window.innerHeight,N=Math.min(260,Math.max(180,Math.round(I*.26))),_=(y-1)/4,T=x+k.top+_*(k.height-I*.5)-N;Ys({top:Math.max(0,T),interruptible:!1,onComplete:S})}},[e]);return u.useEffect(()=>{m();const y=()=>{f.current||(window.requestAnimationFrame(()=>{m(),f.current=!1}),f.current=!0)},S=()=>{m()};let v=null;return typeof ResizeObserver<"u"&&e.current&&(v=new ResizeObserver(()=>{f.current||(window.requestAnimationFrame(()=>{m(),f.current=!1}),f.current=!0)}),v.observe(e.current)),window.addEventListener("scroll",y,{passive:!0}),window.addEventListener("resize",S,{passive:!0}),window.addEventListener("orientationchange",S,{passive:!0}),()=>{v&&v.disconnect(),window.removeEventListener("scroll",y),window.removeEventListener("resize",S),window.removeEventListener("orientationchange",S)}},[m]),{progressRef:t,activeStage:s,scrollZone:o,isEngineActive:l,scrollToStage:b,subscribeProgress:g}},qr={trackContainer:"_trackContainer_5m98v_7",svgTrack:"_svgTrack_5m98v_15",foundationPath:"_foundationPath_5m98v_32",spinePath:"_spinePath_5m98v_41",progressGlow:"_progressGlow_5m98v_52",progressInk:"_progressInk_5m98v_72"};function Im(e,t,n,s,a){const o=1-a,i=o*o,l=a*a;return{x:i*o*e.x+3*i*a*t.x+3*o*l*n.x+l*a*s.x,y:i*o*e.y+3*i*a*t.y+3*o*l*n.y+l*a*s.y}}function $m(e,t,n,s,a=80){let o=0,i=e;for(let l=1;l<=a;l++){const c=Im(e,t,n,s,l/a);o+=Math.hypot(c.x-i.x,c.y-i.y),i=c}return o}function lu(e,t,n){var _,T;const s=(n==null?void 0:n.paddingRatio)??.06,a=(n==null?void 0:n.minPadding)??48,o=(n==null?void 0:n.maxPadding)??80,i=(n==null?void 0:n.trackStyle)??"conduit",l=(n==null?void 0:n.cornerFilletRadius)??36,c=Math.max(1,(n==null?void 0:n.nodeCount)??((_=n==null?void 0:n.nodes)==null?void 0:_.length)??5),d=Math.max(e,320),h=Math.max(t,480),p=Math.min(Math.max(d*s,a),o),f=p,m=d-p,g=Math.round(Math.max(160,Math.min(h*.26,240))),b=Math.round(Math.max(h,640)),y=Math.max(0,c-1)*b,S=[];for(let w=0;w<c;w++){const M=w+1,$=(T=n==null?void 0:n.nodes)==null?void 0:T[w],A=w%2===0?"left":"right",P=A==="left"?f:m,V=g+w*b,D=c>1?Number((w/(c-1)).toFixed(4)):0,W=($==null?void 0:$.id)??"P"+M,H=["var(--color-node-1)","var(--color-node-2)","var(--color-node-3)","var(--color-node-4)","var(--color-node-5)"],q=($==null?void 0:$.accentColorVar)??H[w%5],j=($==null?void 0:$.label)??"Node "+M;S.push({stage:M,id:W,x:P,y:V,threshold:D,accentColorVar:q,label:j,flank:A})}const v=S[0];let k="M "+v.x.toFixed(1)+" "+v.y.toFixed(1);const x=[0];for(let w=0;w<S.length-1;w++){const M=S[w],$=S[w+1];if(i==="curved"){const A={x:M.x,y:M.y+b*.5},P={x:$.x,y:$.y-b*.5};k+=" C "+A.x.toFixed(1)+" "+A.y.toFixed(1)+", "+P.x.toFixed(1)+" "+P.y.toFixed(1)+", "+$.x.toFixed(1)+" "+$.y.toFixed(1);const V=$m(M,A,P,$);x.push(x[x.length-1]+V)}else{const A=$.x>M.x?1:-1,P=Math.abs($.x-M.x),V=Math.min(l,P*.4,b*.15),D=Math.max(8,V),H=$.y-D-24,q=H-D;k+=" L "+M.x.toFixed(1)+" "+q.toFixed(1);const j=M.x+A*D;k+=" Q "+M.x.toFixed(1)+" "+H.toFixed(1)+", "+j.toFixed(1)+" "+H.toFixed(1);const z=$.x-A*D;k+=" L "+z.toFixed(1)+" "+H.toFixed(1);const O=H+D;k+=" Q "+$.x.toFixed(1)+" "+H.toFixed(1)+", "+$.x.toFixed(1)+" "+O.toFixed(1),k+=" L "+$.x.toFixed(1)+" "+$.y.toFixed(1);const U=(1+Math.log(1+Math.SQRT2)/Math.SQRT2)*D,Q=q-M.y,se=Math.abs(z-j),ae=$.y-O,de=Q+U+se+U+ae;x.push(x[x.length-1]+de)}}const I=x[x.length-1],N=g+y+b;return{pathData:k,totalLength:I,cumLengths:x,points:S,totalHeight:N,y0:g,travelY:y}}function cu(e,t){const n=Math.min(Math.max(e,0),1);if(n<=0)return 0;if(n>=1)return t[t.length-1]??0;const s=t.length-1;if(s<=0)return 0;const a=1/s,o=Math.min(Math.floor(n/a),s-1),i=(n-o*a)/a,l=t[o]??0,c=t[o+1]??l;return l+i*(c-l)}const lt={stationWrapper:"_stationWrapper_mu6kf_11",stationDormant:"_stationDormant_mu6kf_54",stationActive:"_stationActive_mu6kf_73",portalRing:"_portalRing_mu6kf_81",ringCore:"_ringCore_mu6kf_128",stationNumber:"_stationNumber_mu6kf_160",stationBody:"_stationBody_mu6kf_222",left:"_left_mu6kf_231",right:"_right_mu6kf_236",contentBlock:"_contentBlock_mu6kf_241",depedBadge:"_depedBadge_mu6kf_262",displayTitle:"_displayTitle_mu6kf_289",summary:"_summary_mu6kf_300",actionWrapper:"_actionWrapper_mu6kf_313",exploreLink:"_exploreLink_mu6kf_326",exploreArrow:"_exploreArrow_mu6kf_353",photoDockSlot:"_photoDockSlot_mu6kf_378"},du=1024,ll=u.memo(({page:e,x:t,y:n,trackWidth:s,flank:a,isActive:o,isSelected:i=!1,isConnected:l=!1,onExplore:c,onSelectStage:d})=>{const h=e.nodeNumber??e.index??1,p=h.toString().padStart(2,"0"),f=(e.tagline??e.title).toUpperCase(),m=e.subtitle??e.title,g=e.summary??e.annotation??"",b=u.useCallback(()=>{d==null||d(h)},[d,h]),y=u.useCallback(P=>{(P.key==="Enter"||P.key===" ")&&(P.preventDefault(),d==null||d(h))},[d,h]),S=u.useCallback(P=>{P.stopPropagation(),c(e.id)},[c,e.id]),v=o||i,k=a==="right"?lt.right:lt.left,x=v?lt.stationActive:lt.stationDormant,I=s??(typeof window<"u"?window.innerWidth:1200),N=I<du,_=N?52:60,T=N?16:32,w=N&&I<=768?340:440,M=N?0:Math.min(520,Math.max(320,I*.3))+48,$=s?a==="left"?s-(t+_)-T-M:t-_-T-M:w,A=Math.max(200,Math.min(w,Math.floor($)));return r.jsxs("div",{className:lt.stationWrapper+" "+x+" "+k,"data-node":h,"data-active":v?"true":"false","data-selected":i?"true":"false","data-connected":l?"true":"false",style:{left:t+"px",top:n+"px","--max-content-width":A+"px"},children:[r.jsx("button",{type:"button",className:lt.portalRing,onClick:b,onKeyDown:y,"aria-label":"Milestone Stage "+p+": "+m+" ("+e.title+") — "+(v?"Active Selected Focal Zone":l?"Connected Milestone":"Upcoming Milestone"),"aria-current":v?"step":void 0,"aria-selected":v,title:"Node "+p+": "+m,children:r.jsx("span",{className:lt.ringCore,children:r.jsx("span",{className:lt.stationNumber,children:p})})}),r.jsxs("div",{className:lt.stationBody,children:[r.jsxs("div",{className:lt.contentBlock,children:[r.jsx("span",{className:lt.depedBadge,children:r.jsx("span",{children:f})}),r.jsx("h3",{className:lt.displayTitle,children:m}),g&&r.jsx("p",{className:lt.summary,children:g}),r.jsx("div",{className:lt.actionWrapper,children:r.jsxs("div",{role:"button",tabIndex:0,className:lt.exploreLink,onClick:S,onKeyDown:P=>{(P.key==="Enter"||P.key===" ")&&(P.preventDefault(),S(P))},"aria-label":"Explore Node Details for Node "+p+": "+m,children:[r.jsx("span",{children:"Explore Node Details"}),r.jsx("span",{className:lt.exploreArrow,"aria-hidden":"true",children:"↓"})]})})]}),r.jsx("div",{className:lt.photoDockSlot,"data-photo-dock":h,"aria-hidden":"true"})]})]})});ll.displayName="RoadmapNode";const cl=u.memo(({nodes:e=[],activeStage:t,subscribeProgress:n,className:s,onNodeClick:a,onExplore:o,options:i})=>{const l=u.useRef(null),c=u.useRef(null),d=u.useRef(null),h=u.useRef(new Map),[p,f]=u.useState(()=>({width:typeof window<"u"?document.documentElement.clientWidth||window.innerWidth:1200,height:typeof window<"u"?document.documentElement.clientHeight||window.innerHeight:800})),[m,g]=u.useState(t);u.useEffect(()=>{g(t)},[t]);const b=u.useCallback(v=>{g(v),a==null||a(v)},[a]),y=u.useCallback(v=>{if(o){o(v);return}const k=document.getElementById("page-section-"+v);if(k)k.scrollIntoView({behavior:"smooth"});else{const x=document.getElementById("sequence-roadmap");if(x){const I=x.offsetTop+x.offsetHeight+10;window.scrollTo({top:I,behavior:"smooth"})}}},[o]);u.useEffect(()=>{let v=null;const k=()=>{v&&cancelAnimationFrame(v),v=requestAnimationFrame(()=>{if(!l.current)return;const I=l.current.clientWidth,N=Math.round(l.current.getBoundingClientRect().width),_=typeof document<"u"?document.documentElement.clientWidth:0,T=typeof window<"u"?window.innerWidth:0,w=Math.round(I||N||_||T||1200),M=Math.round((typeof window<"u"?window.innerHeight:0)||(typeof document<"u"?document.documentElement.clientHeight:0)||800);w<=0||f($=>Math.abs($.width-w)<2&&Math.abs($.height-M)<2?$:{width:w,height:M})})};k();let x=null;return typeof ResizeObserver<"u"&&l.current&&(x=new ResizeObserver(()=>{k()}),x.observe(l.current)),window.addEventListener("resize",k,{passive:!0}),window.addEventListener("orientationchange",k,{passive:!0}),()=>{v&&cancelAnimationFrame(v),x&&x.disconnect(),window.removeEventListener("resize",k),window.removeEventListener("orientationchange",k)}},[]);const S=u.useMemo(()=>lu(p.width,p.height,{...i,nodeCount:e.length>0?e.length:void 0,nodes:e.length>0?e.map((v,k)=>({stage:v.nodeNumber??v.index??k+1,id:v.id,accentColorVar:v.accentColor,label:v.title})):void 0}),[p.width,p.height,e,i]);return u.useEffect(()=>{if(l.current){const x=new Map;l.current.querySelectorAll("[data-node]").forEach(I=>{const N=Number(I.dataset.node);isNaN(N)||x.set(N,I)}),h.current=x}return n(x=>{const I=Math.min(Math.max(x,0),1),N=S.totalLength>0?cu(I,S.cumLengths)/S.totalLength:0,_=Math.max(0,1-N);d.current&&(d.current.style.strokeDashoffset=_.toFixed(5)),c.current&&(c.current.style.strokeDashoffset=_.toFixed(5));const T=.008;for(let w=0;w<S.points.length;w++){const M=S.points[w],$=I>=M.threshold-T,A=h.current.get(M.stage);if(A){const P=$?"true":"false";A.dataset.connected!==P&&(A.dataset.connected=P)}}})},[n,S]),r.jsxs("div",{ref:l,className:qr.trackContainer+" "+(s||""),style:{width:"100%",height:S.totalHeight+"px"},children:[r.jsx("svg",{className:qr.svgTrack,width:p.width,height:S.totalHeight,viewBox:"0 0 "+p.width+" "+S.totalHeight,preserveAspectRatio:"none",role:"presentation","aria-hidden":"true",children:r.jsxs("g",{children:[r.jsx("path",{d:S.pathData,className:qr.foundationPath}),r.jsx("path",{d:S.pathData,className:qr.spinePath}),r.jsx("path",{ref:c,d:S.pathData,className:qr.progressGlow,pathLength:1,style:{strokeDasharray:1,strokeDashoffset:1}}),r.jsx("path",{ref:d,d:S.pathData,className:qr.progressInk,pathLength:1,style:{strokeDasharray:1,strokeDashoffset:1,opacity:1}})]})}),S.points.map((v,k)=>{const x=e[k]??{id:v.id,index:v.stage,title:v.label,subtitle:v.label,accentColor:v.accentColorVar},I=m===v.stage,N=t===v.stage;return r.jsx(ll,{page:x,x:v.x,y:v.y,trackWidth:p.width,flank:v.flank,isActive:N,isSelected:I,isConnected:v.stage===1,onExplore:y,onSelectStage:b},x.id)})]})});cl.displayName="RoadmapTrack";const Em={roadmapSection:"_roadmapSection_mduuo_7"},dl=u.forwardRef(({nodes:e,options:t,onStageChange:n,onExploreNode:s,onExplorePage:a},o)=>{const i=s??a,l=u.useRef(null),c=(e==null?void 0:e.length)??5,{activeStage:d,scrollZone:h,scrollToStage:p,subscribeProgress:f}=iu(l);return u.useEffect(()=>{n==null||n(d,h)},[d,h,n]),u.useImperativeHandle(o,()=>({scrollToStage:p,nextStage:m=>{d<c&&p(d+1,m)},prevStage:m=>{d>1&&p(d-1,m)}}),[d,p,c]),r.jsx("section",{ref:l,className:Em.roadmapSection,"aria-label":"Winding Progression Roadmap",id:"sequence-roadmap",children:r.jsx(cl,{nodes:e,options:t,activeStage:d,subscribeProgress:f,onNodeClick:p,onExplore:i})})});dl.displayName="RoadmapSection";const Fe={siteFooter:"_siteFooter_y6722_11",footerContainer:"_footerContainer_y6722_19",footerGrid:"_footerGrid_y6722_33",brandColumn:"_brandColumn_y6722_40",brandGroup:"_brandGroup_y6722_45",brandName:"_brandName_y6722_53",navColumn:"_navColumn_y6722_63",columnHeading:"_columnHeading_y6722_69",columnList:"_columnList_y6722_79",footerLink:"_footerLink_y6722_88",footerBottom:"_footerBottom_y6722_118",statusBlock:"_statusBlock_y6722_129",statusIndicator:"_statusIndicator_y6722_135",statusHeader:"_statusHeader_y6722_155",statusDot:"_statusDot_y6722_162",statusTitle:"_statusTitle_y6722_172",statusSeparator:"_statusSeparator_y6722_180",statusDesc:"_statusDesc_y6722_186",legalBlock:"_legalBlock_y6722_193",copyright:"_copyright_y6722_201",legalSeparator:"_legalSeparator_y6722_209",bottomLink:"_bottomLink_y6722_214"},Lm=[{code:"access",label:"01. Access",href:"/node/access/"},{code:"equity",label:"02. Equity",href:"/node/equity/"},{code:"quality",label:"03. Quality",href:"/node/quality/"},{code:"resiliency",label:"04. Resiliency",href:"/node/resiliency/"},{code:"governance",label:"05. Governance",href:"/node/governance/"}],ro=({orgName:e="the host application",onRoadmapClick:t,onOverviewClick:n,onNodeClick:s})=>{const a=i=>{n&&(i.preventDefault(),n(i))},o=(i,l)=>{s&&(l.preventDefault(),s(i,l))};return r.jsx("footer",{className:Fe.siteFooter,role:"contentinfo","aria-label":"Portal Footer",children:r.jsxs("div",{className:Fe.footerContainer,children:[r.jsxs("nav",{className:Fe.footerGrid,"aria-label":"Portal Navigation Links",children:[r.jsx("div",{className:Fe.brandColumn,children:r.jsxs("a",{href:"/",className:Fe.brandGroup,onClick:a,"aria-label":"Portal Home",children:[r.jsx(_s,{size:"md"}),r.jsx("span",{className:Fe.brandName,children:"Portal"})]})}),r.jsxs("div",{className:Fe.navColumn,children:[r.jsx("h3",{className:Fe.columnHeading,children:"Nodes"}),r.jsx("ul",{className:Fe.columnList,children:Lm.map(i=>r.jsx("li",{children:r.jsx("a",{href:i.href,className:Fe.footerLink,onClick:l=>o(i.code,l),children:i.label})},i.code))})]}),r.jsxs("div",{className:Fe.navColumn,children:[r.jsx("h3",{className:Fe.columnHeading,children:"Portal"}),r.jsxs("ul",{className:Fe.columnList,children:[r.jsx("li",{children:r.jsx("a",{href:"/",className:Fe.footerLink,onClick:i=>{n&&(i.preventDefault(),n(i))},children:"Overview"})}),r.jsx("li",{children:r.jsx("a",{href:"/#roadmap",className:Fe.footerLink,onClick:i=>{t&&(i.preventDefault(),t(i))},children:"Winding Roadmap"})})]})]})]}),r.jsxs("div",{className:Fe.footerBottom,children:[r.jsx("div",{className:Fe.statusBlock,children:r.jsxs("div",{className:Fe.statusIndicator,role:"status","aria-label":"Folio Engine: Management, Accountability and Systematic collection of Data",children:[r.jsxs("div",{className:Fe.statusHeader,children:[r.jsx("span",{className:Fe.statusDot,"aria-hidden":"true"}),r.jsx("span",{className:Fe.statusTitle,children:"Folio Engine"})]}),r.jsx("span",{className:Fe.statusSeparator,"aria-hidden":"true",children:"—"}),r.jsx("span",{className:Fe.statusDesc,children:"Management, Accountability and Systematic collection of Data"})]})}),r.jsxs("div",{className:Fe.legalBlock,children:[r.jsxs("p",{className:Fe.copyright,children:["© ",new Date().getFullYear()," ",e]}),r.jsx("span",{className:Fe.legalSeparator,"aria-hidden":"true",children:"·"}),r.jsx("a",{href:"#privacy",className:Fe.bottomLink,children:"Data Privacy"})]})]})]})})},Xt={fabContainer:"_fabContainer_1vlq5_8",positionRight:"_positionRight_1vlq5_23",positionLeft:"_positionLeft_1vlq5_28",visible:"_visible_1vlq5_33",hidden:"_hidden_1vlq5_40",fabButton:"_fabButton_1vlq5_50",fabLabel:"_fabLabel_1vlq5_64",fabArrow:"_fabArrow_1vlq5_70",fabArrowDown:"_fabArrowDown_1vlq5_78",fabArrowUp:"_fabArrowUp_1vlq5_82"},ul=({label:e,isVisible:t,position:n="right",direction:s="down",revolving:a=!0,pulse:o,onClick:i,className:l="","aria-label":c})=>{const d=s==="up",h=n==="left",p=o!==void 0?o:!h,[f,m]=u.useState(0);u.useEffect(()=>{if(typeof window>"u"||!window.visualViewport)return;const y=()=>{const v=window.visualViewport;if(!v)return;const k=Math.max(0,window.innerHeight-(v.height+v.offsetTop));m(k)},S=window.visualViewport;return S.addEventListener("resize",y),S.addEventListener("scroll",y),()=>{S.removeEventListener("resize",y),S.removeEventListener("scroll",y)}},[]);const g=h?"Return to the previous milestone":d?"Scroll back to the top of the portal":"Advance to the next milestone",b=r.jsx("span",{className:`${Xt.fabArrow} ${d?Xt.fabArrowUp:Xt.fabArrowDown}`,"aria-hidden":"true",children:d?"↑":"↓"});return r.jsx("div",{className:`${Xt.fabContainer} ${h?Xt.positionLeft:Xt.positionRight} ${t?Xt.visible:Xt.hidden} ${l}`,style:{"--keyboard-offset":`${f}px`},"aria-hidden":!t,children:r.jsxs(me,{variant:"revolving-outline",outlineWidth:3,revolving:a,pulse:p,onClick:i,className:Xt.fabButton,"aria-label":c||g,tabIndex:t?0:-1,children:[h&&b,r.jsx("span",{className:Xt.fabLabel,children:e}),!h&&b]})})},nt={breadcrumbNav:"_breadcrumbNav_3mtf1_12",breadcrumbInner:"_breadcrumbInner_3mtf1_17",list:"_list_3mtf1_25",item:"_item_3mtf1_47",itemCurrent:"_itemCurrent_3mtf1_55",separator:"_separator_3mtf1_59",link:"_link_3mtf1_69",button:"_button_3mtf1_70",current:"_current_3mtf1_113",itemIcon:"_itemIcon_3mtf1_124",itemLabel:"_itemLabel_3mtf1_132",itemBadge:"_itemBadge_3mtf1_141",endSlot:"_endSlot_3mtf1_148"},Mm=()=>r.jsx("span",{className:nt.separator,"aria-hidden":"true",children:"/"}),hl=u.memo(({items:e,separator:t=r.jsx(Mm,{}),className:n,ariaLabel:s="Breadcrumb navigation",endSlot:a})=>!e||e.length===0?null:r.jsx("nav",{className:`${nt.breadcrumbNav} ${n||""}`,"aria-label":s,children:r.jsxs("div",{className:nt.breadcrumbInner,children:[r.jsx("ol",{className:nt.list,children:e.map((o,i)=>{const l=i===e.length-1,c=o.isCurrent??l,d=o.id||(typeof o.label=="string"?`${o.label}-${i}`:`crumb-${i}`),h=typeof o.label=="string"?o.label:void 0;return r.jsxs("li",{className:`${nt.item} ${c?nt.itemCurrent:""}`,children:[i>0&&t,c&&!o.href&&!o.onClick?r.jsxs("span",{className:nt.current,"aria-current":"page",title:h,children:[o.icon&&r.jsx("span",{className:nt.itemIcon,children:o.icon}),r.jsx("span",{className:nt.itemLabel,children:o.label}),o.badge&&r.jsx("span",{className:nt.itemBadge,children:o.badge})]}):o.href?r.jsxs("a",{href:o.href,className:nt.link,onClick:o.onClick,"aria-current":c?"page":void 0,title:h,children:[o.icon&&r.jsx("span",{className:nt.itemIcon,children:o.icon}),r.jsx("span",{className:nt.itemLabel,children:o.label}),o.badge&&r.jsx("span",{className:nt.itemBadge,children:o.badge})]}):r.jsxs("button",{type:"button",className:nt.button,onClick:o.onClick,"aria-current":c?"page":void 0,title:h,children:[o.icon&&r.jsx("span",{className:nt.itemIcon,children:o.icon}),r.jsx("span",{className:nt.itemLabel,children:o.label}),o.badge&&r.jsx("span",{className:nt.itemBadge,children:o.badge})]})]},d)})}),a&&r.jsx("div",{className:nt.endSlot,children:a})]})}));hl.displayName="Breadcrumb";const jr=({pointId:e,defaultText:t,as:n="span",className:s,wrapperClassName:a,style:o,children:i,ariaLabel:l,onSave:c,onReset:d,onEditText:h,inline:p=!1,isSection:f,isNumbered:m,defaultNumbered:g,onNumberedChange:b,editTriggerId:y})=>{const{text:S}=Hr(e,t);let v;return typeof i=="function"?v=i(S):i!=null?v=i:v=r.jsx(n,{className:s,style:o,"aria-label":l,children:S}),r.jsx(Qn,{pointId:e,type:"text",defaultValue:t,currentValue:S,onEditText:h,onSave:c,onReset:d,className:a,inline:p,isSection:f,isNumbered:m,defaultNumbered:g,onNumberedChange:b,editTriggerId:y,children:v})},En={pageHeader:"_pageHeader_fl56i_11",kicker:"_kicker_fl56i_19",title:"_title_fl56i_28",subtitle:"_subtitle_fl56i_38",extra:"_extra_fl56i_48"},fl=u.memo(({title:e,titlePointId:t,kicker:n,kickerPointId:s,subtitle:a,subtitlePointId:o,accentColor:i,className:l,children:c})=>{const{isDevMode:d,isDesktop:h}=Oe();return r.jsxs("header",{className:`${En.pageHeader} ${l||""}`,style:{"--title-accent":i},children:[n||d&&h&&s?s?r.jsx(jr,{pointId:s,defaultText:n||"",as:"div",className:En.kicker}):r.jsx("div",{className:En.kicker,children:n}):null,t?r.jsx(jr,{pointId:t,defaultText:e,as:"h1",className:En.title}):r.jsx("h1",{className:En.title,children:e}),a||d&&h&&o?o?r.jsx(jr,{pointId:o,defaultText:a||"",as:"p",className:En.subtitle}):r.jsx("p",{className:En.subtitle,children:a}):null,c&&r.jsx("div",{className:En.extra,children:c})]})});fl.displayName="PageTitle";function uu(e,t={}){const{offsetPx:n=140,defaultActiveId:s=e[0]||""}=t,[a,o]=u.useState(s),i=u.useRef(null);return u.useEffect(()=>{if(typeof window>"u"||e.length===0)return;const l=()=>{if((window.scrollY||window.pageYOffset)<=50){o(e[0]);return}const h=[];for(const f of e){const m=document.getElementById(f);m&&h.push(m)}if(h.length===0)return;let p=h[0].id;for(const f of h)if(f.getBoundingClientRect().top<=n)p=f.id;else break;o(p)},c=()=>{i.current===null&&(i.current=requestAnimationFrame(()=>{l(),i.current=null}))};return l(),window.addEventListener("scroll",c,{passive:!0}),window.addEventListener("resize",c,{passive:!0}),()=>{i.current!==null&&(cancelAnimationFrame(i.current),i.current=null),window.removeEventListener("scroll",c),window.removeEventListener("resize",c)}},[e,n]),a}const Et={sidebarContainer:"_sidebarContainer_5hq97_12",sidebarBreadcrumb:"_sidebarBreadcrumb_5hq97_23",sidebarBreadcrumbSticky:"_sidebarBreadcrumbSticky_5hq97_40",breadcrumbBackBtn:"_breadcrumbBackBtn_5hq97_47",breadcrumbArrow:"_breadcrumbArrow_5hq97_79",sidebarHeading:"_sidebarHeading_5hq97_91",navList:"_navList_5hq97_102",navItem:"_navItem_5hq97_111",navLink:"_navLink_5hq97_116",navLinkActive:"_navLinkActive_5hq97_142",itemNumber:"_itemNumber_5hq97_156",itemLabel:"_itemLabel_5hq97_164"},hu=({title:e="Contents",items:t=[],activeId:n,accentColor:s,onItemClick:a,className:o,nodeNumber:i,nodeTitle:l,onBack:c})=>{const d=u.useMemo(()=>t.map(S=>S.id||(S.href.startsWith("#")?S.href.slice(1):"")).filter(Boolean),[t]),[h,p]=u.useState(null),f=uu(d,{defaultActiveId:d[0]||"",offsetPx:140}),m=n||h||f,g=u.useCallback((S,v)=>{S.preventDefault(),a==null||a(v);const k=v.id||(v.href.startsWith("#")?v.href.slice(1):"");k&&p(k);const x=document.getElementById(k);if(x){const _=x.getBoundingClientRect().top+window.pageYOffset-100;window.scrollTo({top:Math.max(0,_),behavior:"smooth"})}},[a]);u.useEffect(()=>{if(!h)return;const S=v=>{var k;(k=v.target)!=null&&k.closest("button, a")||p(null)};return window.addEventListener("wheel",S,{passive:!0}),window.addEventListener("touchmove",S,{passive:!0}),()=>{window.removeEventListener("wheel",S),window.removeEventListener("touchmove",S)}},[h]);const[b,y]=u.useState(!1);return u.useEffect(()=>{if(typeof window>"u")return;const S=()=>{const v=window.scrollY||window.pageYOffset;y(v>40)};return S(),window.addEventListener("scroll",S,{passive:!0}),()=>window.removeEventListener("scroll",S)},[]),r.jsxs("aside",{className:`${Et.sidebarContainer} ${o||""}`,"aria-label":`${e} navigation`,style:{"--sidebar-accent":s},children:[c&&r.jsx("div",{className:`${Et.sidebarBreadcrumb} ${b?Et.sidebarBreadcrumbSticky:""}`,"aria-hidden":!b,children:r.jsxs("button",{type:"button",className:Et.breadcrumbBackBtn,onClick:c,"aria-label":"Return to Roadmap",title:"Return to Roadmap",tabIndex:b?0:-1,children:[r.jsx("svg",{className:Et.breadcrumbArrow,viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:r.jsx("path",{d:"M10 13L5 8l5-5"})}),r.jsx("span",{children:"Roadmap"})]})}),r.jsx("div",{className:Et.sidebarHeading,children:e}),r.jsx("nav",{children:r.jsx("ul",{className:Et.navList,children:t.map(S=>{const v=S.id||(S.href.startsWith("#")?S.href.slice(1):""),k=S.isActive??(!!v&&m===v);return r.jsx("li",{className:Et.navItem,children:r.jsxs("a",{href:S.href,className:`${Et.navLink} ${k?Et.navLinkActive:""}`,onClick:x=>g(x,S),"aria-current":k?"true":void 0,children:[S.number&&r.jsx("span",{className:Et.itemNumber,children:S.number}),r.jsx("span",{className:Et.itemLabel,children:S.label})]})},S.href)})})})]})},Dm=pl;function pl(e){const{isDevMode:t}=Oe(),[n,s]=u.useState(()=>Ft(e,t)),[a,o]=u.useTransition(),i=u.useRef(n);i.current=n;const l=u.useRef(null);u.useEffect(()=>{const w=Ft(e,t);return i.current=w,s(w),bi(e,$=>{$.updatedAt!==l.current&&i.current.updatedAt!==$.updatedAt&&(i.current=$,o(()=>{s($)}))},t)},[e,t]),u.useEffect(()=>{if(!t&&e){let w=!1;return fetch(`/api/public/node/${e}`).then(M=>M.ok?M.json():null).then(M=>{if(!w&&(M!=null&&M.canvas)&&Array.isArray(M.canvas.sections)&&(M.canvas.updatedAt!==i.current.updatedAt||M.canvas.sections.length!==i.current.sections.length)){i.current=M.canvas;try{Ir(M.canvas,{silent:!0})}catch{}o(()=>{s(M.canvas)})}}).catch(()=>{}),()=>{w=!0}}},[e,t]);const{pushAction:c}=Ks(),[d,h]=u.useState(null),p=u.useCallback(()=>{h(null)},[]),f=u.useCallback(w=>{const M=w(i.current),$=Ps(M,t);!$.ok&&t?h("Edit not saved — browser storage full."):$.ok&&h(null);const A=$.document;l.current=A.updatedAt,i.current=A,o(()=>{s(A)})},[t]),m=u.useCallback((w,M)=>{f($=>pi($,w,M))},[f]),g=u.useCallback((w,M,$)=>{f(A=>mi(A,w,M,$))},[f]),b=u.useCallback((w,M,$,A)=>{f(P=>gi(P,w,M,$,A))},[f]),y=u.useCallback((w,M)=>{const $=za(i.current,w);if(f(A=>od(A,w,M)),$){const A="title"in $.item&&typeof $.item.title=="string"&&$.item.title?$.item.title:$.kind;c({type:$.kind==="section"?"canvas_remove_section":$.kind==="subsection"?"canvas_remove_subsection":"canvas_remove_leaf",description:`Delete ${$.kind} "${A}"`,undo:()=>{$.kind==="section"?m($.item,$.index):$.kind==="subsection"?g($.sectionId,$.item,$.index):b($.sectionId,$.item,$.index,$.subsectionId)},redo:()=>y(w,M)})}},[f,c,m,g,b]),S=u.useCallback(w=>{const M=i.current,$=Ro(M.sections.length,M.nodeId),A=typeof w=="number"?w:M.sections.length;f(P=>pi(P,$,A)),c({type:"canvas_insert_section",description:`Add section "${$.title}"`,undo:()=>y($.id),redo:()=>m($,A)})},[f,c,y,m]),v=u.useCallback((w,M)=>{const $=i.current,A=$.sections.find(D=>D.id===w),P=Jf($.nodeId),V=typeof M=="number"?M:A?A.elements.length:0;f(D=>mi(D,w,P,V)),c({type:"canvas_insert_subsection",description:`Add subsection "${P.title}"`,undo:()=>y(P.id,w),redo:()=>g(w,P,V)})},[f,c,y,g]),k=u.useCallback((w,M,$,A)=>{f(P=>gi(P,w,M,$,A)),c({type:"canvas_insert_leaf",description:`Add ${M.type} element`,undo:()=>y(M.id,A||w),redo:()=>b(w,M,$,A)})},[f,c,y,b]),x=u.useCallback((w,M,$)=>{f(A=>sd(A,w,M,$)),c({type:"canvas_move_item",description:`Move item ${M}`,undo:()=>x(w,M==="up"?"down":"up",$),redo:()=>x(w,M,$)})},[f,c]),I=u.useCallback((w,M,$)=>{const A=za(i.current,w),P=A?A.subsectionId||A.sectionId:void 0,V=A?A.index:void 0;f(D=>ad(D,w,M,$)),A&&P&&c({type:"canvas_relocate_item",description:"Relocate item",undo:()=>I(w,P,V),redo:()=>I(w,M,$)})},[f,c]),N=u.useCallback((w,M)=>{const $=za(i.current,w),A={};if($){const P=$.item;for(const V of Object.keys(M))A[V]=P[V]}f(P=>id(P,w,M)),$&&c({type:"canvas_update_item",description:`Update ${$.kind} properties`,undo:()=>N(w,A),redo:()=>N(w,M)})},[f,c]),_=u.useCallback(()=>{o(()=>{const w=vi(e,t);s(w)})},[e,t]),T=u.useCallback(async()=>(await yi(e)).success,[e]);return{document:n,isPending:a,addSection:S,addSubsection:v,addElement:k,restoreSection:m,restoreSubsection:g,restoreElement:b,moveItem:x,relocateItem:I,removeItem:y,updateItem:N,resetToDefault:_,deployToCloud:T,saveError:d,clearSaveError:p}}const Kr={sectionHeader:"_sectionHeader_1tbu5_11",sectionNumber:"_sectionNumber_1tbu5_18",sectionTitle:"_sectionTitle_1tbu5_28",extra:"_extra_1tbu5_45"},so=u.memo(({title:e,titlePointId:t,number:n,defaultNumbered:s,subtitle:a,subtitlePointId:o,as:i="h2",id:l,accentColor:c,className:d,children:h,editTriggerId:p,onEdit:f})=>{const m=i,g=s!==void 0?s:n!=null,b=t?`${t}.isNumbered`:"",{text:y}=Hr(b,g?"true":"false"),S=b?y==="true":g,v=n??1,k=S?typeof v=="number"?String(v).padStart(2,"0"):String(v):null;return r.jsxs("div",{className:`${Kr.sectionHeader} ${d||""}`,style:{"--section-accent":c},children:[k&&r.jsxs("span",{className:Kr.sectionNumber,children:["Section ",k]}),t?r.jsx(jr,{pointId:t,defaultText:e,as:m,className:Kr.sectionTitle,ariaLabel:l,isSection:!0,isNumbered:S,defaultNumbered:g,editTriggerId:p,onEditText:f,children:x=>r.jsx(m,{id:l,className:Kr.sectionTitle,children:x})}):r.jsx(m,{id:l,className:Kr.sectionTitle,children:e}),h&&r.jsx("div",{className:Kr.extra,children:h})]})});so.displayName="SectionTitle";const Zs={section:"_section_1iiq7_12",sectionBody:"_sectionBody_1iiq7_22",subsection:"_subsection_1iiq7_28",subsectionBody:"_subsectionBody_1iiq7_41",galleryWrapper:"_galleryWrapper_1iiq7_53"},ml=u.memo(({section:e,nodeId:t,nodeTitle:n,accentColor:s,isDevMode:a,className:o,computedNumber:i,children:l,onEdit:c})=>{const d=e.id.startsWith("sec-")?e.id:`sec-${e.id}`,h=e.titlePointId||`node.${t}.section.${e.id}.title`,p=i!==void 0?i!==null:e.isNumbered!==void 0?e.isNumbered:e.number!==void 0&&e.number!==null,f=e.isNumbered!==void 0?e.isNumbered:p,m=f?i!==void 0?i:e.number:null,g=e.title;return r.jsxs("section",{id:d,className:`${Zs.section} ${o||""}`.trim(),"aria-label":g,"data-toc-title":g,"data-toc-number":m||void 0,"data-toc-numbered":f?"true":"false",children:[r.jsx(so,{number:m,defaultNumbered:f,title:g,titlePointId:h,as:"h2",accentColor:s,editTriggerId:e.id,onEdit:c}),r.jsx("div",{className:Zs.sectionBody,children:l})]})});ml.displayName="CanvasSection";const gl=u.memo(({subsection:e,nodeId:t,accentColor:n,isDevMode:s,className:a,children:o,onEdit:i})=>{const l=e.id.startsWith("subsec-")?e.id:`subsec-${e.id}`,c=e.titlePointId||`node.${t}.subsec.${e.id}.title`;return r.jsxs("div",{id:l,className:`${Zs.subsection} ${a||""}`.trim(),role:"region","aria-label":e.title,children:[r.jsx(so,{title:e.title,titlePointId:c,as:"h3",accentColor:n,defaultNumbered:!1,editTriggerId:e.id,onEdit:i}),r.jsx("div",{className:Zs.subsectionBody,children:o})]})});gl.displayName="CanvasSubsection";const rt={textWrapper:"_textWrapper_hx1sj_10",bodyText:"_bodyText_hx1sj_18",quoteWrapper:"_quoteWrapper_hx1sj_26",quoteText:"_quoteText_hx1sj_32",photoCardContainer:"_photoCardContainer_hx1sj_43",photoCardBody:"_photoCardBody_hx1sj_54",photoCard:"_photoCard_hx1sj_43",photoButton:"_photoButton_hx1sj_84",photoImage:"_photoImage_hx1sj_105",photoCaption:"_photoCaption_hx1sj_118",driveContainer:"_driveContainer_hx1sj_127",driveBadge:"_driveBadge_hx1sj_135",placeholderCard:"_placeholderCard_hx1sj_161",placeholderIconWrapper:"_placeholderIconWrapper_hx1sj_175",cameraIcon:"_cameraIcon_hx1sj_187",placeholderText:"_placeholderText_hx1sj_192",chartContainer:"_chartContainer_hx1sj_198"},vl=u.memo(({element:e,accentColor:t,className:n,onEdit:s})=>{const a=e.as==="blockquote",o=a&&t?{borderLeftColor:t,color:t}:void 0;return r.jsx("div",{className:a?`${rt.quoteWrapper} ${n||""}`.trim():`${rt.textWrapper} ${n||""}`.trim(),style:o,children:r.jsx(jr,{pointId:"",defaultText:e.content,as:a?"blockquote":"p",className:a?rt.quoteText:rt.bodyText,editTriggerId:e.id,onEditText:s})})});vl.displayName="CanvasText";function fu({isOpen:e,onClose:t,hash:n="#source"}){u.useEffect(()=>{if(!e)return;const s=window.location.href;window.history.pushState({modal:"source-lightbox"},"",n);const a=()=>{t()};return window.addEventListener("popstate",a),()=>{window.removeEventListener("popstate",a),window.location.hash===n&&window.history.replaceState(null,"",s)}},[e,t,n])}function Bm(e){return!e||!e.closest?!1:!!e.closest('button, a, input, select, textarea, [role="tablist"], [data-no-swipe]')}function Om({onSwipeLeft:e,onSwipeRight:t,onSwipeDown:n,minDistance:s=45,disabled:a=!1}){const o=u.useRef(0),i=u.useRef(0),l=u.useRef(0),c=u.useRef(!1),d=u.useRef(0),h=(N,_,T)=>{if(a||Bm(T)){c.current=!1;return}o.current=N,i.current=_,l.current=Date.now(),c.current=!0},p=(N,_)=>{if(!c.current||a){c.current=!1;return}if(c.current=!1,Date.now()-d.current<350)return;const T=N-o.current,w=_-i.current,M=Date.now()-l.current,$=Math.abs(T),A=Math.abs(w),V=M<280&&($>28||A>28)?Math.min(s,30):s;if(w>V&&A>$*1.3){d.current=Date.now(),n==null||n();return}$>V&&$>A&&(d.current=Date.now(),T<0?e==null||e():t==null||t())},f=()=>{c.current=!1},m=u.useCallback(N=>{N.touches.length>0&&h(N.touches[0].clientX,N.touches[0].clientY,N.target)},[a]),g=u.useCallback(N=>{},[]),b=u.useCallback(N=>{N.changedTouches.length>0&&p(N.changedTouches[0].clientX,N.changedTouches[0].clientY)},[a,s,n,e,t]),y=u.useCallback(()=>{f()},[]),S=u.useCallback(N=>{N.pointerType==="mouse"&&N.button!==0||h(N.clientX,N.clientY,N.target)},[a]),v=u.useCallback(N=>{},[]),k=u.useCallback(N=>{N.pointerType==="mouse"&&N.button!==0||p(N.clientX,N.clientY)},[a,s,n,e,t]),x=u.useCallback(()=>{f()},[]),I=u.useCallback(()=>Date.now()-d.current<350,[]);return{onTouchStart:m,onTouchMove:g,onTouchEnd:b,onTouchCancel:y,onPointerDown:S,onPointerMove:v,onPointerUp:k,onPointerCancel:x,wasSwipeJustTriggered:I}}function Pm(e,t){const[n,s]=u.useState(e),[a,o]=u.useState(e?"loading":"idle"),[i,l]=u.useState(0);u.useEffect(()=>{s(e)},[e]),u.useEffect(()=>{if(!n){o("idle");return}let d=!0;o("loading");const h=new Image;if(h.referrerPolicy="no-referrer",h.src=n,h.complete&&h.naturalWidth>0){o("loaded");return}return h.onload=()=>{d&&o("loaded")},h.onerror=()=>{d&&(t&&n!==t?s(t):o("error"))},()=>{d=!1,h.onload=null,h.onerror=null}},[n,t,i]);const c=u.useCallback(()=>{s(e),l(d=>d+1)},[e]);return{status:a,isLoading:a==="loading",isLoaded:a==="loaded",isError:a==="error",resolvedSrc:n,retry:c}}const Ln={imageContainer:"_imageContainer_ofyas_12",skeletonShimmer:"_skeletonShimmer_ofyas_21",image:"_image_ofyas_12",imageLoaded:"_imageLoaded_ofyas_59",errorFallback:"_errorFallback_ofyas_63",errorIcon:"_errorIcon_ofyas_79",errorMessage:"_errorMessage_ofyas_84",retryButton:"_retryButton_ofyas_92"},pu=({src:e,fallbackSrc:t,srcSet:n,sizes:s,alt:a="",className:o="",imageClassName:i="",aspectRatio:l,objectFit:c="cover",showRetry:d=!0,loading:h="lazy",decoding:p="async",onLoad:f,onError:m})=>{const{status:g,isLoading:b,isLoaded:y,isError:S,resolvedSrc:v,retry:k}=Pm(e,t);u.useEffect(()=>{y&&f&&f()},[y,f]),u.useEffect(()=>{S&&m&&m()},[S,m]);const x=l?{aspectRatio:l}:{};return r.jsxs("div",{className:`${Ln.imageContainer} ${o}`,style:x,"data-status":g,children:[b&&r.jsx("div",{className:Ln.skeletonShimmer,"aria-hidden":"true"}),S&&r.jsxs("div",{className:Ln.errorFallback,role:"alert",children:[r.jsx("span",{className:Ln.errorIcon,"aria-hidden":"true",children:"⚠"}),r.jsx("p",{className:Ln.errorMessage,children:"Failed to load photo"}),d&&r.jsx("button",{type:"button",className:Ln.retryButton,onClick:I=>{I.stopPropagation(),k()},"aria-label":"Retry loading photograph",children:"Retry"})]}),v&&r.jsx("img",{src:v,srcSet:n,sizes:s,alt:a,referrerPolicy:"no-referrer",draggable:!1,className:`${Ln.image} ${y?Ln.imageLoaded:""} ${i}`,style:{objectFit:c},loading:h,decoding:p})]})},Xs={stripContainer:"_stripContainer_1rgdz_11",thumbButton:"_thumbButton_1rgdz_38",thumbActive:"_thumbActive_1rgdz_76",thumbImage:"_thumbImage_1rgdz_90",thumbFallback:"_thumbFallback_1rgdz_98"},Fm=({items:e,currentIndex:t,accentColor:n,onNavigate:s})=>{const[a,o]=u.useState({}),i=u.useRef(null),l=u.useRef(null),[c,d]=u.useState({});u.useEffect(()=>{l.current&&l.current.scrollIntoView({behavior:"smooth",block:"nearest",inline:"center"})},[t]);const h=u.useCallback((f,m)=>{m&&!c[f]?d(g=>({...g,[f]:!0})):o(g=>({...g,[f]:!0}))},[c]),p=u.useCallback((f,m)=>{f.key==="ArrowRight"?(f.preventDefault(),f.stopPropagation(),m<e.length-1&&s(m+1)):f.key==="ArrowLeft"?(f.preventDefault(),f.stopPropagation(),m>0&&s(m-1)):f.key==="Home"?(f.preventDefault(),f.stopPropagation(),s(0)):f.key==="End"&&(f.preventDefault(),f.stopPropagation(),s(e.length-1))},[e.length,s]);return e.length<=1?null:r.jsx("div",{ref:i,role:"tablist","aria-label":"Available photographs",className:Xs.stripContainer,onClick:f=>f.stopPropagation(),children:e.map((f,m)=>{var _,T,w,M;const g=m===t,b=f.driveFileId||((_=f.id)!=null&&_.startsWith("drive-")?f.id.replace(/^drive-/,""):"")||on(((T=f.photo)==null?void 0:T.src)||f.imageSrc||""),y=f.thumbnailUrl||((w=f.photo)==null?void 0:w.src)||f.imageSrc||"",S=b&&!y.includes("/api/media/drive/")?ln(b,{width:320}):y,v=b?`https://drive.google.com/thumbnail?id=${encodeURIComponent(b)}&sz=w320`:void 0,x=c[m]&&v?v:S,I=((M=f.photo)==null?void 0:M.caption)||f.title||`Photo ${m+1}`,N=a[m];return r.jsx("button",{ref:g?l:null,type:"button",role:"tab","aria-selected":g,"aria-label":`Photo ${m+1} of ${e.length}: ${I}`,className:`${Xs.thumbButton} ${g?Xs.thumbActive:""}`,onClick:$=>{$.stopPropagation(),s(m)},onKeyDown:$=>p($,m),style:g&&n?{"--lightbox-thumb-active-border":n}:void 0,children:x&&!N?r.jsx("img",{src:x,alt:"","aria-hidden":"true",loading:"lazy",decoding:"async",draggable:!1,className:Xs.thumbImage,onError:()=>h(m,v)}):r.jsx("span",{className:Xs.thumbFallback,"aria-hidden":"true",children:m+1})},f.id||`thumb-${m}`)})})},Me={backdrop:"_backdrop_3coip_12",srOnly:"_srOnly_3coip_37",headerBar:"_headerBar_3coip_53",chromeHidden:"_chromeHidden_3coip_67",counterPill:"_counterPill_3coip_73",closeButton:"_closeButton_3coip_87",closeIcon:"_closeIcon_3coip_119",stage:"_stage_3coip_128",stageZoomed:"_stageZoomed_3coip_143",imageFrame:"_imageFrame_3coip_147",imageFrameZoomed:"_imageFrameZoomed_3coip_159",lightboxImageWrapper:"_lightboxImageWrapper_3coip_163",lightboxImage:"_lightboxImage_3coip_163",navButton:"_navButton_3coip_192",navPrev:"_navPrev_3coip_221",navNext:"_navNext_3coip_225",navIcon:"_navIcon_3coip_243",footerBar:"_footerBar_3coip_272",footerHidden:"_footerHidden_3coip_286",photoStripWrapper:"_photoStripWrapper_3coip_292",footerTopRow:"_footerTopRow_3coip_299",metadataBlock:"_metadataBlock_3coip_307",titleRow:"_titleRow_3coip_313",photoTitle:"_photoTitle_3coip_320",sourceGroup:"_sourceGroup_3coip_330",driveButton:"_driveButton_3coip_336",driveIcon:"_driveIcon_3coip_369"},mu=({isOpen:e,items:t,currentIndex:n,driveFolderUrl:s,accentColor:a,onClose:o,onNavigate:i,onEditSource:l,onEditPhoto:c})=>{var Y,ee,X,te;const[d,h]=u.useState(!1),[p,f]=u.useState(!0),{isDevMode:m,isDesktop:g}=Oe(),b=m&&g,y=u.useRef(null),S=u.useRef(null),v=u.useRef(null),k=u.useRef(0);fu({isOpen:e,onClose:o});const x=t.length>0,I=Math.max(0,Math.min(n,Math.max(0,t.length-1))),N=x?t[I]:null;u.useEffect(()=>{h(!1)},[I]);const _=u.useCallback(()=>{I<t.length-1&&i(I+1)},[I,t.length,i]),T=u.useCallback(()=>{I>0&&i(I-1)},[I,i]),{onTouchStart:w,onTouchMove:M,onTouchEnd:$,onTouchCancel:A,onPointerDown:P,onPointerMove:V,onPointerUp:D,onPointerCancel:W,wasSwipeJustTriggered:H}=Om({onSwipeLeft:_,onSwipeRight:T,onSwipeDown:o,minDistance:45,disabled:d});u.useEffect(()=>{if(!e)return;y.current=document.activeElement;const K=window.innerWidth-document.documentElement.clientWidth,J=document.body.style.overflow,Z=document.body.style.paddingRight;document.body.style.overflow="hidden",K>0&&(document.body.style.paddingRight=`${K}px`);const ne=window.setTimeout(()=>{var ie;(ie=S.current)==null||ie.focus()},50);return()=>{window.clearTimeout(ne),document.body.style.overflow=J,document.body.style.paddingRight=Z,y.current&&typeof y.current.focus=="function"&&y.current.focus()}},[e]),u.useEffect(()=>{if(!e)return;const K=J=>{J.key==="Escape"?(J.preventDefault(),J.stopPropagation(),J.stopImmediatePropagation(),o()):J.key==="ArrowRight"?(J.preventDefault(),_()):J.key==="ArrowLeft"&&(J.preventDefault(),T())};return window.addEventListener("keydown",K,!0),()=>{window.removeEventListener("keydown",K,!0)}},[e,_,T,o]);const q=u.useRef(null),j=u.useCallback(()=>{f(!0),q.current&&window.clearTimeout(q.current),q.current=window.setTimeout(()=>{f(!1)},3500)},[]);u.useEffect(()=>{if(e)return j(),()=>{q.current&&window.clearTimeout(q.current)}},[e,j,I]);const z=u.useCallback(K=>{if(H())return;const J=K.target;if(J.closest("button")||J.closest("a"))return;const Z=Date.now(),ne=Z-k.current;k.current=Z,ne<300?h(ie=>!ie):f(ie=>{const F=!ie;return F?j():q.current&&window.clearTimeout(q.current),F})},[j,H]);if(!e||!N)return null;const O=((Y=N.photo)==null?void 0:Y.src)||N.imageSrc||"",U=((ee=N.photo)==null?void 0:ee.alt)||N.title,Q=((X=N.photo)==null?void 0:X.caption)||N.title,se=N.driveFileId||((te=N.id)!=null&&te.startsWith("drive-")?N.id.replace(/^drive-/,""):"")||on(O),ae=se&&!O.includes("/api/media/drive/")?ln(se,{width:1600}):O,de=se?`https://drive.google.com/thumbnail?id=${encodeURIComponent(se)}&sz=w1600`:void 0,B=r.jsxs("div",{ref:v,role:"dialog","aria-modal":"true","aria-label":"Photo Lightbox",className:Me.backdrop,onMouseMove:j,onPointerMove:K=>{j(),V(K)},onPointerDown:K=>{j(),P(K)},onPointerUp:D,onPointerCancel:W,onTouchStart:K=>{j(),w(K)},onTouchMove:K=>{j(),M(K)},onTouchEnd:$,onTouchCancel:A,style:a?{"--lightbox-accent":a}:void 0,children:[r.jsxs("div",{"aria-live":"polite",className:Me.srOnly,children:["Showing photo ",I+1," of ",t.length,": ",Q]}),r.jsxs("header",{className:`${Me.headerBar} ${p?"":Me.chromeHidden}`,children:[t.length>1?r.jsxs("div",{className:Me.counterPill,children:[r.jsx("span",{children:I+1}),r.jsx("span",{children:"/"}),r.jsx("span",{children:t.length})]}):r.jsx("div",{}),r.jsx("button",{ref:S,type:"button",className:Me.closeButton,onClick:o,"aria-label":"Close photo lightbox",children:r.jsx("span",{className:Me.closeIcon,"aria-hidden":"true",children:"✕"})})]}),r.jsxs("div",{className:`${Me.stage} ${d?Me.stageZoomed:""}`,onClick:z,children:[I>0&&r.jsx("button",{type:"button",className:`${Me.navButton} ${Me.navPrev} ${p?"":Me.chromeHidden}`,onClick:K=>{K.stopPropagation(),T()},"aria-label":"Previous photograph",children:r.jsx("span",{className:Me.navIcon,"aria-hidden":"true",children:"‹"})}),I<t.length-1&&r.jsx("button",{type:"button",className:`${Me.navButton} ${Me.navNext} ${p?"":Me.chromeHidden}`,onClick:K=>{K.stopPropagation(),_()},"aria-label":"Next photograph",children:r.jsx("span",{className:Me.navIcon,"aria-hidden":"true",children:"›"})}),r.jsx("div",{className:`${Me.imageFrame} ${d?Me.imageFrameZoomed:""}`,children:r.jsx("div",{className:Me.lightboxImageWrapper,children:r.jsx(pu,{src:ae,fallbackSrc:de,alt:U,className:Me.lightboxImage,imageClassName:Me.lightboxImage,objectFit:"contain",loading:"eager",decoding:"async",showRetry:!0})})})]}),r.jsxs("footer",{className:`${Me.footerBar} ${p?"":Me.footerHidden}`,children:[t.length>1&&r.jsx("div",{className:Me.photoStripWrapper,children:r.jsx(Fm,{items:t,currentIndex:I,accentColor:a,onNavigate:i})}),r.jsxs("div",{className:Me.footerTopRow,children:[r.jsx("div",{className:Me.metadataBlock,children:r.jsxs("div",{className:Me.titleRow,children:[r.jsx("h3",{className:Me.photoTitle,children:Q}),b&&c&&r.jsx(me,{type:"button",variant:"admin",size:"xs",onClick:K=>{K.stopPropagation(),c(N)},title:"Edit photo details","aria-label":"Edit photo details",children:"✎ Edit"})]})}),r.jsxs("div",{className:Me.sourceGroup,children:[s&&r.jsxs("a",{href:s,target:"_blank",rel:"noopener noreferrer",className:Me.driveButton,"aria-label":"Open Google Drive source",children:[r.jsx("span",{children:"Source"}),r.jsx("span",{className:Me.driveIcon,"aria-hidden":"true",children:"↗"})]}),b&&l&&r.jsx(me,{type:"button",variant:"admin",size:"xs",onClick:K=>{K.stopPropagation(),l()},title:"Edit Google Drive source","aria-label":"Edit Google Drive source",children:"✎ Edit"})]})]})]})]});return typeof document>"u"?B:bs.createPortal(B,document.body)},Um=Bi;function fn(e){return!e||typeof e!="string"?"":e.trim().toLowerCase().replace(/^node-/,"")}function zm(e){const t=fn(e);if(!t)return null;const n=Um[t]??null,s=`source.${t}.source`,a=si(s,null);if(a){const o="folderUrl"in a?a.folderUrl:a.url,i="folderTitle"in a?a.folderTitle:a.label;if(o!==void 0||i!==void 0)return{pointId:t,folderUrl:o??(n==null?void 0:n.folderUrl)??"",folderTitle:i??(n==null?void 0:n.folderTitle)??"Official Google Drive Folder",description:n==null?void 0:n.description,lastVerified:n==null?void 0:n.lastVerified}}return n}const gu=/^https:\/\/(?:drive\.google\.com\/(?:drive\/(?:u\/\d+\/)?folders\/|open\?id=))([a-zA-Z0-9_-]{15,})/;function Gm(e){return!e||typeof e!="string"?!1:gu.test(e.trim())}const Js=e=>(e||Ae())+"_evidence_cache_v2",bl=Js(),ao="engine-evidence-source-change",Wm=Bi;let Lt=null,Qs=null;function yl(){const e={};for(const[t,n]of Object.entries(Wm))e[t]={pointId:n.pointId,folderUrl:n.folderUrl,folderTitle:n.folderTitle,description:n.description,updatedBy:"Coordinator",lastVerified:n.lastVerified??new Date().toISOString().split("T")[0],createdAt:"2025-10-01T00:00:00Z"};return e}function oo(e){if(!Array.isArray(e.syncedPhotos)||e.syncedPhotos.length===0)return e;let t=!1;const n=e.syncedPhotos.map(s=>{var c,d,h,p,f,m,g,b,y,S,v;if(!(s.fullImageUrl&&s.fullImageUrl.includes("/drive-storage/")||s.thumbnailUrl&&s.thumbnailUrl.includes("/drive-storage/")||s.imageSrc&&s.imageSrc.includes("/drive-storage/")||((c=s.photo)==null?void 0:c.src)&&s.photo.src.includes("/drive-storage/")))return s;t=!0;const o=s.driveFileId||((d=s.id)!=null&&d.startsWith("drive-")?s.id.replace(/^drive-/,""):"");if(!o)return s;const i=`https://drive.google.com/thumbnail?id=${encodeURIComponent(o)}&sz=w1600`,l=`https://drive.google.com/thumbnail?id=${encodeURIComponent(o)}&sz=w320`;return{...s,thumbnailUrl:(h=s.thumbnailUrl)!=null&&h.includes("/drive-storage/")?l:s.thumbnailUrl,fullImageUrl:(p=s.fullImageUrl)!=null&&p.includes("/drive-storage/")?i:s.fullImageUrl,imageSrc:(f=s.imageSrc)!=null&&f.includes("/drive-storage/")?i:s.imageSrc,photo:{src:(g=(m=s.photo)==null?void 0:m.src)!=null&&g.includes("/drive-storage/")?i:((b=s.photo)==null?void 0:b.src)||i,alt:((y=s.photo)==null?void 0:y.alt)||"",caption:(S=s.photo)==null?void 0:S.caption,showCaption:(v=s.photo)==null?void 0:v.showCaption}}});return t?{...e,syncedPhotos:n}:e}function vu(){const e=Ee();if(!e)return null;try{const t=e.getItem(Js());if(!t)return null;const n=JSON.parse(t),s={};for(const[a,o]of Object.entries(n))s[a]=oo(o);return s}catch{return null}}function bu(e){const t=Ee();if(t)try{t.setItem(Js(),JSON.stringify(e))}catch{try{const n={};for(const[s,a]of Object.entries(e))n[s]={...a,syncedPhotos:void 0};t.setItem(Js(),JSON.stringify(n))}catch{}}}function Hm(e,t){if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(ao,{detail:{pointId:e,record:t}}))}catch{}}function Vm(e){const t={pointId:e.point_id,folderUrl:e.folder_url,folderTitle:e.folder_title,description:e.description??void 0,updatedBy:e.updated_by??"Coordinator",lastVerified:e.last_verified??new Date().toISOString(),createdAt:e.created_at??new Date().toISOString(),syncedPhotos:Array.isArray(e.synced_photos)?e.synced_photos:void 0};return oo(t)}async function _l(e){if(Lt!==null&&!(e!=null&&e.forceRefresh))return Lt;if(Qs&&!(e!=null&&e.forceRefresh))return Qs;Qs=(async()=>{const t=yl(),n=vu();n&&Object.assign(t,n);const s=tt();if(s)try{const a=typeof AbortController<"u"?new AbortController:null,o=a?setTimeout(()=>a.abort(),6e3):null,i=await fetch(`${s.url}/rest/v1/engine_sources?select=*`,{method:"GET",headers:{apikey:s.anonKey,Authorization:`Bearer ${s.anonKey}`,"Content-Type":"application/json"},signal:a==null?void 0:a.signal});if(o&&clearTimeout(o),i.ok){const l=await i.json();if(Array.isArray(l)){for(const c of l){const d=Vm(c);t[d.pointId]=d}bu(t)}}}catch{}return Lt=t,Lt})();try{return await Qs}finally{Qs=null}}async function io(e){const t=fn(e);return t?(await _l())[t]??null:null}function Yr(e){const t=fn(e);if(!t)return null;if(Lt&&Lt[t])return Lt[t];const n=vu();return n&&n[t]?(Lt||(Lt={...yl(),...n}),n[t]):yl()[t]??null}async function Zr(e,t){const n=fn(e.pointId);if(!n)throw new Error("Invalid pointId: cannot be empty");const s=new Date().toISOString(),a=await io(n),o=oo({pointId:n,folderUrl:e.folderUrl,folderTitle:e.folderTitle,description:e.description??(a==null?void 0:a.description),updatedBy:e.updatedBy??"Coordinator",lastVerified:s,createdAt:(a==null?void 0:a.createdAt)??s,syncedPhotos:e.syncedPhotos??(a==null?void 0:a.syncedPhotos)}),i=Lt??await _l();i[n]=o,Lt=i,bu(i),Hm(n,o);const l=tt();if(l)try{const c=t||l.anonKey,d={point_id:o.pointId,folder_url:o.folderUrl,folder_title:o.folderTitle,description:o.description??null,updated_by:o.updatedBy,last_verified:o.lastVerified,created_at:o.createdAt};o.syncedPhotos!==void 0&&(d.synced_photos=o.syncedPhotos),await fetch(`${l.url}/rest/v1/engine_sources`,{method:"POST",headers:{apikey:l.anonKey,Authorization:`Bearer ${c}`,"Content-Type":"application/json",Prefer:"resolution=merge-duplicates,return=representation"},body:JSON.stringify(d)})}catch{}return o}function qm(){Lt=null;const e=Ee();if(e)try{e.removeItem(bl)}catch{}}const wl={};function Sl(e){if(!e||typeof e!="string")return null;const t=e.trim().match(gu);return t&&t[1]?t[1]:null}function jm(){var t;const e=typeof{url:typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:We&&We.tagName.toUpperCase()==="SCRIPT"&&We.src||new URL("folio.umd.cjs",document.baseURI).href}<"u"&&(wl==null?void 0:wl.VITE_GOOGLE_DRIVE_API_KEY)||typeof process<"u"&&((t=process.env)==null?void 0:t.VITE_GOOGLE_DRIVE_API_KEY)||"";return e&&!e.includes("your-google-drive-api-key")?e.trim():null}function yu(e){if(!e||typeof e!="string")return null;const t=e.match(/[?&]resourcekey=([a-zA-Z0-9_-]+)/);return t&&t[1]?t[1]:null}async function _u(e){var s,a,o,i,l;const t=Sl(e);if(!t)return{status:"invalid_format",message:"Invalid URL format. Please paste a Google Drive folder link."};const n=jm();if(n)try{const c=typeof AbortController<"u"?new AbortController:null,d=c?setTimeout(()=>c.abort(),6e3):null,h=yu(e),p={Accept:"application/json"};h&&(p["X-Goog-Drive-Resource-Keys"]=`${t}/${h}`);const f=`https://www.googleapis.com/drive/v3/files/${encodeURIComponent(t)}?fields=id,name,mimeType&supportsAllDrives=true&includeItemsFromAllDrives=true&key=${encodeURIComponent(n)}`,m=await fetch(f,{method:"GET",headers:p,signal:c==null?void 0:c.signal});if(d&&clearTimeout(d),m.ok){const v=await m.json();return v.mimeType==="application/vnd.google-apps.folder"?{status:"valid",folderId:v.id,folderTitle:v.name,mimeType:v.mimeType,message:`Publicly accessible folder verified: "${v.name}"`}:{status:"not_a_folder",folderId:v.id,folderTitle:v.name,mimeType:v.mimeType,message:`Notice: This link points to an individual file ("${v.name}"), not a folder archive.`}}const g=await m.json().catch(()=>null),b=((o=(a=(s=g==null?void 0:g.error)==null?void 0:s.errors)==null?void 0:a[0])==null?void 0:o.reason)||((i=g==null?void 0:g.error)==null?void 0:i.status)||"",y=((l=g==null?void 0:g.error)==null?void 0:l.message)||m.statusText||"";if(b==="API_KEY_HTTP_REFERRER_BLOCKED"||b==="ipRefererBlocked"||b==="accessNotConfigured"||b==="SERVICE_DISABLED"||b==="keyInvalid"||b==="dailyLimitExceeded"||b==="rateLimitExceeded"||b==="userRateLimitExceeded"||y.toLowerCase().includes("referrer")||y.toLowerCase().includes("api key")||y.toLowerCase().includes("quota")||y.toLowerCase().includes("blocked")){const v=y?`[API Key: ${y}]`:`[API Reason: ${b}]`;return console.warn("[DriveVerification] Google Drive API Key or Referrer restriction detected:",y||b),{status:"unverified",folderId:t,message:`Folder format is valid, but Google Drive API reported a key/referrer issue ${v}. Ensure access is set to "Anyone with the link can view".`,apiError:{statusCode:m.status,reason:b,rawMessage:y}}}if(m.status===404)try{const v=`https://www.googleapis.com/drive/v3/files?q=${encodeURIComponent(`'${t}' in parents and trashed = false`)}&pageSize=1&fields=files(id)&supportsAllDrives=true&includeItemsFromAllDrives=true&key=${encodeURIComponent(n)}`;if((await fetch(v,{method:"GET",headers:p})).ok)return{status:"valid",folderId:t,message:"Publicly accessible folder verified."}}catch{}if(m.status===403){const v=y?` [HTTP 403: ${y}]`:" [HTTP 403: Forbidden]";return{status:"restricted",folderId:t,message:`Folder is restricted or requires login${v}. Set General Access to "Anyone with the link can view".`,apiError:{statusCode:403,reason:b,rawMessage:y}}}if(m.status===404){const v=y?` [HTTP 404: ${y}]`:" [HTTP 404: Not Found]";return{status:"restricted",folderId:t,message:`Folder not found or inaccessible via API${v}. Set General Access to "Anyone with the link can view".`,apiError:{statusCode:404,reason:b,rawMessage:y}}}return{status:"unverified",folderId:t,message:`Folder link format is valid, but Google Drive API returned HTTP ${m.status} (${y||"Unexpected error"}). Ensure access is set to "Anyone with the link can view".`,apiError:{statusCode:m.status,reason:b,rawMessage:y}}}catch(c){const h=c instanceof Error&&c.name==="AbortError"?"Request timed out (6s)":c instanceof Error?c.message:"Network or CORS connection error";return{status:"unverified",folderId:t,message:`Folder link format is valid, but Google Drive API could not be reached [Network/CORS: ${h}]. Ensure access is set to "Anyone with the link can view".`,apiError:{rawMessage:h}}}return{status:"unverified",folderId:t,message:'Folder link format is valid [No API Key configured]. Ensure access is set to "Anyone with the link can view".'}}const kl={};function Km(){var t;const e=typeof{url:typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:We&&We.tagName.toUpperCase()==="SCRIPT"&&We.src||new URL("folio.umd.cjs",document.baseURI).href}<"u"&&(kl==null?void 0:kl.VITE_GOOGLE_DRIVE_API_KEY)||typeof process<"u"&&((t=process.env)==null?void 0:t.VITE_GOOGLE_DRIVE_API_KEY)||"";return e&&!e.includes("your-google-drive-api-key")?e.trim():null}function Ym(e){if(!e||typeof e!="string")return"Source Photo";let t=e.replace(/\.(jpe?g|png|webp|gif|heic|tiff)$/i,"");return t=t.replace(/^IMG_\d+_/i,""),t=t.replace(/^\d+[\s_-]+/,""),t=t.replace(/[_-]+/g," "),t=t.replace(/\s+/g," ").trim(),t.length>0?t:"Source Photo"}function Zm(e,t){return e.localeCompare(t,void 0,{numeric:!0,sensitivity:"base"})}function Xm(e,t,n=!1){return n&&t?ln(t,{width:1600}):t&&(!e||e.includes("/drive-storage/"))?`https://drive.google.com/thumbnail?id=${encodeURIComponent(t)}&sz=w1600`:e&&e.includes("=s")?e.replace(/=s\d+.*$/,"=s1600"):t?`https://drive.google.com/thumbnail?id=${encodeURIComponent(t)}&sz=w1600`:e||""}function Jm(e,t,n=!1){return n&&t?ln(t,{width:320}):t&&(!e||e.includes("/drive-storage/"))?`https://drive.google.com/thumbnail?id=${encodeURIComponent(t)}&sz=w320`:e&&!e.includes("/drive-storage/")?e:t?`https://drive.google.com/thumbnail?id=${encodeURIComponent(t)}&sz=w320`:""}function Qm(e,t,n){if(e.length===0&&t.length===0)return{items:[],stats:{added:0,removed:0,retained:0,total:0,hasChanged:!1}};const s=new Map;for(let p=0;p<e.length;p++)s.set(e[p].driveFileId,e[p]);const a=[...t].sort((p,f)=>Zm(p.name,f.name)),o=new Set,i=[];let l=0,c=0;for(let p=0;p<a.length;p++){const f=a[p];o.add(f.id);const m=s.get(f.id),g=Jm(f.thumbnailLink,f.id),b=Xm(f.thumbnailLink,f.id);if(m)c++,i.push({...m,orderIndex:p,thumbnailUrl:g,fullImageUrl:b,imageSrc:b,photo:{...m.photo,src:b,alt:m.title,caption:m.title,showCaption:!0}});else{l++;const y=Ym(f.name),S=f.createdTime?f.createdTime.split("T")[0]:"2026-10-09";i.push({id:`drive-${f.id}`,pointId:n,driveFileId:f.id,originalFileName:f.name,title:y,category:"MOV Photo",date:S,dateStamp:S,imageSrc:b,thumbnailUrl:g,fullImageUrl:b,photo:{src:b,alt:y,caption:y,showCaption:!0},orderIndex:p,isCustomTitle:!1})}}let d=0;for(let p=0;p<e.length;p++)o.has(e[p].driveFileId)||d++;const h=l>0||d>0||i.length!==e.length;return{items:i,stats:{added:l,removed:d,retained:c,total:i.length,hasChanged:h}}}async function Rm(e){var b,y,S,v,k;const t=e?e.trim():"",n=t.includes("/")?Sl(t):t;if(!n)throw new Error("Invalid Google Drive folder link or folder ID.");const s=Km();if(!s)throw new Error("Google Drive API Key is not configured in VITE_GOOGLE_DRIVE_API_KEY.");const a=yu(t),o={Accept:"application/json"};a&&(o["X-Goog-Drive-Resource-Keys"]=`${n}/${a}`);const i=`'${n}' in parents and trashed = false`,l="files(id,name,mimeType,thumbnailLink,createdTime,modifiedTime)",c=`https://www.googleapis.com/drive/v3/files?q=${encodeURIComponent(i)}&fields=${encodeURIComponent(l)}&pageSize=100&supportsAllDrives=true&includeItemsFromAllDrives=true&key=${encodeURIComponent(s)}`,d=await fetch(c,{method:"GET",headers:o});if(!d.ok){const x=await d.json().catch(()=>null),I=((S=(y=(b=x==null?void 0:x.error)==null?void 0:b.errors)==null?void 0:y[0])==null?void 0:S.reason)||((v=x==null?void 0:x.error)==null?void 0:v.status)||"",N=((k=x==null?void 0:x.error)==null?void 0:k.message)||d.statusText||"";throw d.status===404?new Error(`Google Drive folder not found [HTTP 404: ${N||"Folder does not exist or has been deleted"}].`):d.status===403?I==="API_KEY_HTTP_REFERRER_BLOCKED"||I==="ipRefererBlocked"||N.toLowerCase().includes("referrer")?new Error(`Google Cloud API Key Referrer Block [HTTP 403: ${N}]. Add your deployment domain to allowed HTTP referrers in Google Cloud Console.`):new Error(`Access denied [HTTP 403: ${N||"Forbidden"}]. Ensure folder General Access is set to "Anyone with the link can view".`):new Error(`Google Drive API error [HTTP ${d.status}]: ${N}`)}const p=(await d.json()).files??[],f=x=>!!(x.mimeType&&x.mimeType.startsWith("image/")||/\.(jpe?g|png|webp|gif|heic|tiff|bmp|avif)$/i.test(x.name)),m=p.filter(f),g=p.filter(x=>x.mimeType==="application/vnd.google-apps.folder");if(g.length>0)try{const x=g.slice(0,5).map(async N=>{const _=`'${N.id}' in parents and trashed = false`,T=`https://www.googleapis.com/drive/v3/files?q=${encodeURIComponent(_)}&fields=${encodeURIComponent(l)}&pageSize=50&supportsAllDrives=true&includeItemsFromAllDrives=true&key=${encodeURIComponent(s)}`,w=await fetch(T,{method:"GET",headers:o});return w.ok?((await w.json()).files??[]).filter(f):[]}),I=await Promise.all(x);for(const N of I)m.push(...N)}catch{}return m}async function wu(e,t,n=[],s){if(!e||typeof e!="string"||!e.trim())throw new Error("Invalid pointId: must be a non-empty string.");if(!t||typeof t!="string"||!t.trim())throw new Error("Invalid folderUrl: must be a non-empty Google Drive folder URL.");const a=e.trim(),o=t.trim(),i=await Rm(o),l=Qm(n,i,a),c=Yr(a)||await io(a),d=(c==null?void 0:c.folderTitle)||"Official Google Drive Folder",h=c==null?void 0:c.description,p=await Zr({pointId:a,folderUrl:o,folderTitle:d,description:h,syncedPhotos:l.items,updatedBy:"Drive Sync Engine"},s);return{items:l.items,stats:l.stats,source:p}}const at={subtitle:"_subtitle_iysop_8",body:"_body_iysop_16",fieldGroup:"_fieldGroup_iysop_22",label:"_label_iysop_28",input:"_input_iysop_36",inputInvalid:"_inputInvalid_iysop_60",urlInputRow:"_urlInputRow_iysop_64",feedbackText:"_feedbackText_iysop_70",feedbackSuccess:"_feedbackSuccess_iysop_77",feedbackChecking:"_feedbackChecking_iysop_84",errorAlert:"_errorAlert_iysop_92",actions:"_actions_iysop_102",actionAuxiliary:"_actionAuxiliary_iysop_110",actionPrimary:"_actionPrimary_iysop_115",testLink:"_testLink_iysop_122"},Cl=({isOpen:e,pointId:t,initialTitle:n="",initialUrl:s="",onClose:a,onSuccess:o})=>{const{isDevMode:i,isDesktop:l}=Oe(),[c,d]=u.useState(n),[h,p]=u.useState(s),[f,m]=u.useState(!1),[g,b]=u.useState("idle"),[y,S]=u.useState(null),[v,k]=u.useState(null),[x,I]=u.useState(null),N=u.useRef(null);u.useEffect(()=>{e&&(!i||!l)&&a()},[e,i,l,a]),u.useEffect(()=>{if(e){const D=!s||s.trim().length===0;d(D||(n==="Official Google Drive Folder"||n==="Evidence Folder"||n==="Attach Drive Folder")?"":n),p(s),m(!1),b("idle"),S(null),k(null);const H=setTimeout(()=>{var q;(q=N.current)==null||q.focus()},50);return()=>clearTimeout(H)}},[e,n,s]);const _=u.useMemo(()=>e?c.trim()!==n.trim()||h.trim()!==s.trim():!1,[e,c,h,n,s]);eo(e&&_,`link-folder-${t}`);const T=h.trim(),w=Gm(T),M=T.length>0&&!w,$=w&&!f,A=u.useCallback(async()=>{var D;if(!(!w||!T)){m(!0),b("verifying"),k(null);try{const W=await _u(T);S(W),W.status==="valid"?!c.trim()&&W.folderTitle&&d(W.folderTitle):W.status==="restricted"||W.status==="not_a_folder"?k(W.message||null):W.status==="unverified"&&((D=W.message)!=null&&D.includes("["))&&k(W.message)}catch{}finally{m(!1),b("idle")}}},[w,T,c]),P=u.useCallback(async()=>{if(!(!w||!T||f)){m(!0),k(null);try{const D=Sl(T);let W=y;if((!W||W.folderId!==D)&&(b("verifying"),W=await _u(T),S(W)),W.status==="not_a_folder"||W.status==="invalid_format"){k(W.message||"Invalid folder format."),m(!1),b("idle");return}if(W.status==="restricted"){k(W.message||'Access restricted. Set Google Drive folder permissions to "Anyone with the link can view".'),m(!1),b("idle");return}b("saving");const H=c.trim()||W.folderTitle||"Official Google Drive Folder";await Zr({pointId:t,folderUrl:T,folderTitle:H,updatedBy:"Administrator"});try{wu(t,T,[])}catch{}I("Folder link updated successfully."),o==null||o(T,H),a()}catch(D){k(D instanceof Error?D.message:"Failed to update folder link.")}finally{m(!1),b("idle")}}},[w,T,f,y,c,t,o,a]),V=x?r.jsx(Zt,{message:x,type:"success",onDismiss:()=>I(null)}):null;return r.jsxs(r.Fragment,{children:[r.jsxs(bt,{isOpen:e,onClose:a,onConfirm:$?()=>P():void 0,title:"Link Folder",maxWidth:"480px",role:"dialog","aria-modal":"true",ariaLabelledBy:"link-folder-title",ariaDescribedBy:"link-folder-desc",children:[r.jsx("p",{id:"link-folder-desc",className:at.subtitle,children:"Attach a Google Drive folder for photos and documents."}),r.jsxs("div",{className:at.body,children:[r.jsxs("div",{className:at.fieldGroup,children:[r.jsx("label",{htmlFor:"folder-title-input",className:at.label,children:"Folder Label"}),r.jsx("input",{ref:N,id:"folder-title-input",type:"text",className:at.input,value:c,onChange:D=>d(D.target.value),placeholder:"e.g. Media & Documentation Folder",disabled:f})]}),r.jsxs("div",{className:at.fieldGroup,children:[r.jsx("label",{htmlFor:"folder-url-input",className:at.label,children:"Google Drive Folder URL"}),r.jsxs("div",{className:at.urlInputRow,children:[r.jsx("input",{id:"folder-url-input",type:"url",className:`${at.input} ${M?at.inputInvalid:""}`,value:h,onChange:D=>{p(D.target.value),S(null),k(null)},placeholder:"https://drive.google.com/drive/folders/...",disabled:f}),r.jsx(me,{variant:"secondary",size:"xs",type:"button",onClick:A,disabled:!w||f,title:"Verify public access via Google Drive API",children:g==="verifying"&&f?"Checking...":"Verify"})]}),g==="verifying"&&f&&r.jsx("div",{className:at.feedbackChecking,children:"Checking Google Drive permissions..."}),g!=="verifying"&&(y==null?void 0:y.status)==="valid"&&r.jsxs("div",{className:at.feedbackSuccess,children:["✓ Public folder verified (",y.folderTitle,")"]}),g!=="verifying"&&M&&r.jsx("div",{className:at.feedbackText,children:"Please enter a valid Google Drive folder link."})]}),v&&r.jsx("div",{className:at.errorAlert,role:"alert",children:v}),r.jsxs("div",{className:at.actions,children:[r.jsx("div",{className:at.actionAuxiliary,children:w&&r.jsx("a",{href:T,target:"_blank",rel:"noopener noreferrer",className:at.testLink,title:"Open folder in a new tab to verify access",children:"Test Link ↗"})}),r.jsxs("div",{className:at.actionPrimary,children:[r.jsx(me,{variant:"secondary",size:"sm",type:"button",onClick:a,disabled:f,children:"Cancel"}),r.jsx(me,{variant:"primary",size:"sm",type:"button",onClick:()=>P(),disabled:!$,children:g==="verifying"?"Verifying...":g==="saving"?"Saving...":"Save"})]})]})]})]}),V]})},xl=u.memo(({element:e,accentColor:t,isDevMode:n,className:s,onEdit:a})=>{const{isDevMode:o,isDesktop:i}=Oe(),l=!!(n||o&&i),c=e,[d,h]=u.useState(!1),[p,f]=u.useState(!1);u.useEffect(()=>{!l&&p&&f(!1)},[l,p]);const m=!!(c.src&&c.src.trim().length>0),g=!!(c.driveUrl&&c.driveUrl.trim().length>0),b=u.useMemo(()=>on(c.rawDriveUrl||"")||on(c.src||"")||on(c.driveUrl||"")||null,[c.rawDriveUrl,c.src,c.driveUrl]),y=u.useMemo(()=>{if(c.srcSet)return c.srcSet;if(b)return Mi(b)},[c.srcSet,b]),v=c.sizes||"(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 800px",k=u.useMemo(()=>c.src?b&&!c.src.includes("/api/media/drive/")?ln(b,{width:800}):c.src:"",[c.src,b]),[x,I]=u.useState(k);u.useEffect(()=>{I(k)},[k]);const N=u.useCallback(()=>{if(b){const A=c.rawDriveUrl||`https://drive.google.com/thumbnail?id=${encodeURIComponent(b)}&sz=w1600`;x!==A&&I(A)}},[b,c.rawDriveUrl,x]),_=u.useMemo(()=>{if(!c.src)return[];const A=b?ln(b,{width:1600}):c.rawDriveUrl||c.src;return[{id:e.id,driveFileId:b||void 0,title:c.caption||c.alt||"Evidence photograph",dateStamp:new Date().toISOString().slice(0,10),photo:{src:A,alt:c.alt||c.caption||"Evidence photograph",caption:c.caption||"",showCaption:!!c.caption},imageSrc:A}]},[e.id,b,c.src,c.rawDriveUrl,c.alt,c.caption]),T=u.useCallback(()=>{m&&h(!0)},[m]),w=u.useCallback(()=>{h(!1)},[]),M=u.useCallback(A=>{},[]),$=()=>m?r.jsxs("div",{className:`${rt.photoCard} ${s||""}`.trim(),children:[r.jsx("button",{type:"button",className:rt.photoButton,onClick:T,"aria-label":`View source photograph in full screen: ${c.caption||c.alt||"Evidence photo"}`,children:r.jsx("img",{src:x,srcSet:y,sizes:v,alt:c.alt||c.caption||"Evidence photograph",className:rt.photoImage,loading:"lazy",decoding:"async",referrerPolicy:"no-referrer",onError:N,style:c.aspectRatio?{aspectRatio:c.aspectRatio}:void 0})}),c.caption?r.jsx("p",{className:rt.photoCaption,children:c.caption}):null,g?r.jsx("div",{className:rt.driveContainer,children:r.jsx("a",{href:c.driveUrl,target:"_blank",rel:"noopener noreferrer",className:rt.driveBadge,"aria-label":"Official Google Drive folder",children:"Drive Folder ↗"})}):null]}):r.jsxs("div",{className:`${rt.placeholderCard} ${s||""}`.trim(),onClick:l&&a?a:void 0,role:l&&a?"button":void 0,tabIndex:l&&a?0:void 0,"aria-label":l&&a?"Click to edit source photo":void 0,children:[r.jsx("div",{className:rt.placeholderIconWrapper,"aria-hidden":"true",children:r.jsxs("svg",{className:rt.cameraIcon,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[r.jsx("path",{d:"M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"}),r.jsx("circle",{cx:"12",cy:"13",r:"4"})]})}),r.jsx("span",{className:rt.placeholderText,children:"Evidence photograph pending"}),g?r.jsx("div",{className:rt.driveContainer,children:r.jsx("a",{href:c.driveUrl,target:"_blank",rel:"noopener noreferrer",className:rt.driveBadge,"aria-label":"Official Google Drive folder",children:"Drive Folder ↗"})}):null]});return r.jsxs(r.Fragment,{children:[r.jsx("div",{className:`${rt.photoCardContainer} ${s||""}`.trim(),children:r.jsx("div",{className:rt.photoCardBody,children:$()})}),m&&d?r.jsx(mu,{isOpen:d,items:_,currentIndex:0,driveFolderUrl:c.driveUrl,accentColor:t,onClose:w,onNavigate:()=>{}}):null,l?r.jsx(Cl,{isOpen:p,pointId:e.pointId||`canvas.photo.${e.id}`,initialTitle:g&&(c.caption||c.alt)||"",initialUrl:c.driveUrl||"",onClose:()=>f(!1),onSuccess:M}):null]})});xl.displayName="CanvasPhoto";const Nl=JSON.parse('[{"id":"access","index":0,"nodeNumber":1,"title":"Foundation & Core Access","subtitle":"Architectural Baselines & Universal Access","summary":"Establishing resilient foundational scaffolding, token infrastructure, and zero-compromise accessibility contracts across distributed endpoints.","tagline":"Stage 01 · Baseline Protocol","accentColor":"#0284c7","accentTint":"#e0f2fe","heroImage":{"src":"https://images.unsplash.com/photo-1451187580459-43490279c0fa?w=1200&q=80&auto=format&fit=crop","alt":"Global network grid symbolizing universal access and infrastructural foundation","caption":"Foundational architectural baseline providing universal access and type-safe contracts.","showCaption":true},"annotation":"Stage 01 establishes core design tokens and foundational data pipelines.","stages":[{"step":1,"stageName":"Where We Are","narrative":"Heterogeneous legacy systems often suffer from fragmented styling tokens and unverified endpoints, creating brittle client integration boundaries."},{"step":2,"stageName":"What We Need","narrative":"A decoupled, token-first design infrastructure with deterministic schema verification and strict mathematical coordinate scaling."},{"step":3,"stageName":"What We Are Doing","narrative":"Isolating layout engines, compiling SVG Bézier tracks, and standardizing AST document models with zero institutional hardwiring."},{"step":4,"stageName":"What We Are Achieving","narrative":"Sub-millisecond edge resolution, 100% token purity across 247 components, and strict WCAG 2.1 AA keyboard accessibility."},{"step":5,"stageName":"How We Serve Users","narrative":"Empowering operators and technical teams to explore dynamic data sequences with complete confidence and evaluative ease."}],"sourceItems":[{"id":"src-acc-01","title":"Core Architecture Topology Blueprint","dateStamp":"2026-01-15","photo":{"src":"https://images.unsplash.com/photo-1504639725590-34d0984388bd?w=800&q=80","alt":"System architecture topology diagram on terminal","caption":"Baseline system architecture topology specification.","showCaption":false},"imageSrc":"https://images.unsplash.com/photo-1504639725590-34d0984388bd?w=800&q=80","reference":"RFC-1014 Architecture Specification"},{"id":"src-acc-02","title":"Design Token Distribution Matrix","dateStamp":"2026-02-10","photo":{"src":"https://images.unsplash.com/photo-1551288049-bebda4e38f71?w=800&q=80","alt":"Design system token verification dashboard","caption":"Mathematical color space tokens and semantic alias hierarchy.","showCaption":false},"imageSrc":"https://images.unsplash.com/photo-1551288049-bebda4e38f71?w=800&q=80","reference":"Design System RFC-880"}],"metadata":{"category":"infrastructure","stability":"stable","version":"2.4.0"}},{"id":"equity","index":1,"nodeNumber":2,"title":"Discovery & Data Equity","subtitle":"Democratic Inspection & Balanced Distribution","summary":"Delivering transparent exploration channels and equal information density for both mobile handhelds and ultra-wide workstations.","tagline":"Stage 02 · Exploratory Protocol","accentColor":"#881337","accentTint":"#ffe4e6","heroImage":{"src":"https://images.unsplash.com/photo-1518770660439-4636190af475?w=1200&q=80&auto=format&fit=crop","alt":"Microprocessor circuitry illustrating distributed data equity and telemetry flows","caption":"Transparent exploration channels distributing balanced telemetry across user touchpoints.","showCaption":true},"annotation":"Stage 02 ensures equal visual ergonomics across diverse client form factors.","stages":[{"step":1,"stageName":"Where We Are","narrative":"Dense technical metrics often overload non-specialist users, while mobile layouts frequently strip essential context or truncate data series."},{"step":2,"stageName":"What We Need","narrative":"Progressive disclosure models that present high-level clarity first, followed by effortless drill-downs to raw CSV records and mathematical proofs."},{"step":3,"stageName":"What We Are Doing","narrative":"Implementing adaptive 2-column editorial grids with sticky rail TOCs on desktop and non-intrusive mobile capsule navigators."},{"step":4,"stageName":"What We Are Achieving","narrative":"Zero cognitive friction, single unified breakpoint transitions at 1024px, and tactile touch interaction on high-density displays."},{"step":5,"stageName":"How We Serve Users","narrative":"Ensuring every stakeholder, from field inspectors to executive coordinators, inspects identical verified truth."}],"sourceItems":[{"id":"src-eq-01","title":"Responsive Viewport Parity Audit","dateStamp":"2026-03-01","photo":{"src":"https://images.unsplash.com/photo-1581291518857-4e27b48ff24e?w=800&q=80","alt":"Responsive design testing across multi-screen matrix","caption":"Adaptive layout verification across mobile and desktop viewports.","showCaption":false},"imageSrc":"https://images.unsplash.com/photo-1581291518857-4e27b48ff24e?w=800&q=80","reference":"UX Benchmark Audit 2026-B"}],"metadata":{"category":"ergonomics","stability":"active","version":"2.4.0"}},{"id":"quality","index":2,"nodeNumber":3,"title":"Architecture & System Quality","subtitle":"Rigorous AST Schemas & Pure Vector Visualizers","summary":"Transforming arbitrary tabular streams into high-precision vector charts, interactive drawer controls, and D3 mathematical curves.","tagline":"Stage 03 · Analytical Protocol","accentColor":"#f59e0b","accentTint":"#fef3c7","heroImage":{"src":"https://images.unsplash.com/photo-1460925895917-afdab827c52f?w=1200&q=80&auto=format&fit=crop","alt":"Financial analytics and vector graphics charting on modern glass interface","caption":"Dynamic vector charting studio rendering real-time analytical curves.","showCaption":true},"annotation":"Stage 03 anchors vector charting capabilities with instant synchronous rendering.","stages":[{"step":1,"stageName":"Where We Are","narrative":"Third-party charting libraries frequently introduce heavy canvas bloat, sluggish bundle sizes, and unstyled tooltips that break design harmony."},{"step":2,"stageName":"What We Need","narrative":"Pure SVG visualizers driven directly by CSS tokens with zero layout thrashing, responsive tooltips, and instant CSV verification receipts."},{"step":3,"stageName":"What We Are Doing","narrative":"Crafting native Bar, Line, Donut, Scatter, and Histogram renderers powered by D3 mathematical scales and memoized SVG paths."},{"step":4,"stageName":"What We Are Achieving","narrative":"Under 10ms initial paint time, interactive drawer parameterization, and LOESS polynomial smoothing curves."},{"step":5,"stageName":"How We Serve Users","narrative":"Enabling precise, verifiable visual analytics without sacrificing page speed or editorial restraint."}],"sourceItems":[{"id":"src-qual-01","title":"Vector Rendering Performance Profile","dateStamp":"2026-03-20","photo":{"src":"https://images.unsplash.com/photo-1551836022-d5d88e9218df?w=800&q=80","alt":"Performance benchmark graphs and telemetry monitor","caption":"Sub-10ms render latency benchmark across 5000 SVG points.","showCaption":false},"imageSrc":"https://images.unsplash.com/photo-1551836022-d5d88e9218df?w=800&q=80","reference":"Performance Profiling Report Q1"}],"metadata":{"category":"visualization","stability":"active","version":"2.4.0"}},{"id":"resiliency","index":3,"nodeNumber":4,"title":"Validation & Resilient Integrity","subtitle":"Edge-Cached Redundancy & Local-First Durability","summary":"Hardening client persistence with optimistic transactions, cryptographic verification, and instant rollback safety across offline states.","tagline":"Stage 04 · Verification Protocol","accentColor":"#15803d","accentTint":"#dcfce7","heroImage":{"src":"https://images.unsplash.com/photo-1526374965328-7f61d4dc18c5?w=1200&q=80&auto=format&fit=crop","alt":"Encrypted code stream and cryptographic matrix symbolizing data resiliency","caption":"Local-first persistence architecture with multi-tier cryptographic safeguards.","showCaption":true},"annotation":"Stage 04 provides resilient transactional guarantees and rollback safety.","stages":[{"step":1,"stageName":"Where We Are","narrative":"Network intermittency and cloud sync timeouts risk user data loss when editing dynamic canvas structures in the browser."},{"step":2,"stageName":"What We Need","narrative":"A dual-channel storage engine combining synchronous localStorage caching with asynchronous IndexedDB transactional undo/redo stacks."},{"step":3,"stageName":"What We Are Doing","narrative":"Scaffolding 50-step undo/redo circular ring buffers and automatic recovery procedures for unsaved draft modifications."},{"step":4,"stageName":"What We Are Achieving","narrative":"Instantaneous optimistic UI dispatch, zero lost keystrokes, and clean separation between draft editing and published channels."},{"step":5,"stageName":"How We Serve Users","narrative":"Providing an authoring environment where creative changes can be tested boldly with immediate rollback protection."}],"sourceItems":[{"id":"src-res-01","title":"Offline Durability & Stress Testing Logs","dateStamp":"2026-04-05","photo":{"src":"https://images.unsplash.com/photo-1544197150-b99a580bb7a8?w=800&q=80","alt":"Server rack cabling and edge infrastructure cluster","caption":"Cluster redundancy tests under simulated network partitioning.","showCaption":false},"imageSrc":"https://images.unsplash.com/photo-1544197150-b99a580bb7a8?w=800&q=80","reference":"Resilience Test Report SEC-44"}],"metadata":{"category":"storage","stability":"active","version":"2.4.0"}},{"id":"governance","index":4,"nodeNumber":5,"title":"Scale & Coordinated Governance","subtitle":"Multi-Tenant Orchestration & Versioned History","summary":"Enabling collaborative multi-editor workflows with audit logging, pin-secured publication gates, and tenant autonomy.","tagline":"Stage 05 · Governance Protocol","accentColor":"#d97706","accentTint":"#ffedd5","heroImage":{"src":"https://images.unsplash.com/photo-1507679799987-c73779587ccf?w=1200&q=80&auto=format&fit=crop","alt":"Modern collaborative architectural workspace representing team governance","caption":"Collaborative coordinator governance with multi-editor publication checkpoints.","showCaption":true},"annotation":"Stage 05 manages multi-editor deployment gates and historical audit logs.","stages":[{"step":1,"stageName":"Where We Are","narrative":"Unregulated deployments and uncoordinated concurrent edits cause staging collisions and inadvertent overwrites in production."},{"step":2,"stageName":"What We Need","narrative":"Role-gated coordinator mode secured by salted SHA-256 PIN authentication and explicit staging review checkpoints."},{"step":3,"stageName":"What We Are Doing","narrative":"Integrating DevPinModal, DevModeBadge, DevLockService, and UniversalEditModal into a unified coordinator dock."},{"step":4,"stageName":"What We Are Achieving","narrative":"Cryptographically verified release pipelines, tamper-evident publication records, and instantaneous edge KV sync."},{"step":5,"stageName":"How We Serve Users","narrative":"Delivering enterprise-grade administrative governance with complete transparency and zero operational downtime."}],"sourceItems":[{"id":"src-gov-01","title":"Cryptographic Audit & Access Logs","dateStamp":"2026-04-18","photo":{"src":"https://images.unsplash.com/photo-1563986768609-322da13575f3?w=800&q=80","alt":"Cryptographic key signature and audit trail verification UI","caption":"Cryptographic commit verification for edge deployment pipeline.","showCaption":false},"imageSrc":"https://images.unsplash.com/photo-1563986768609-322da13575f3?w=800&q=80","reference":"Governance Standard GOV-2026"}],"metadata":{"category":"governance","stability":"active","version":"2.4.0"}}]');function Tl(e){var g,b;const t=fn(e),[n,s]=u.useState(()=>t?Yr(t):null),[a,o]=u.useState(()=>!n&&!!t),[i,l]=u.useState(!1),[c,d]=u.useState(null);u.useEffect(()=>{if(!t){s(null),o(!1);return}let y=!0;const S=Yr(t);S&&s(S),io(t).then(I=>{y&&(I&&s(I),o(!1))}).catch(I=>{y&&(d(I instanceof Error?I.message:"Failed to fetch live source source"),o(!1))});const v=I=>{const N=I;N.detail&&fn(N.detail.pointId)===t&&s(N.detail.record)},k=`source.${t}.source`,x=ai(I=>{if((I.key===k||I.key==="*")&&y){const N=Yr(t);N&&s(N)}},!1);return window.addEventListener(ao,v),()=>{y=!1,window.removeEventListener(ao,v),x()}},[t]);const h=u.useCallback(async(y,S,v)=>{if(!t)throw new Error("Cannot update source source: invalid or empty pointId");l(!0),d(null);try{const k=S&&S.trim().length>0?S.trim():(n==null?void 0:n.folderTitle)||"Official Google Drive Folder",x=await Zr({pointId:t,folderUrl:y.trim(),folderTitle:k,description:v??(n==null?void 0:n.description),updatedBy:"Coordinator"});return s(x),x}catch(k){const x=k instanceof Error?k.message:"Failed to save source source";throw d(x),k}finally{l(!1)}},[t,n]),p=((g=n==null?void 0:n.folderUrl)==null?void 0:g.trim())||"",f=((b=n==null?void 0:n.folderTitle)==null?void 0:b.trim())||"Official Google Drive Folder",m=p.length>0;return{source:n,folderUrl:p,folderTitle:f,description:n==null?void 0:n.description,lastVerified:n==null?void 0:n.lastVerified,isLoading:a,isUpdating:i,error:c,updateFolder:h,hasFolder:m}}function eg(e){const{source:t,folderUrl:n}=Tl(e),[s,a]=u.useTransition(),[o,i]=u.useState(!1),[l,c]=u.useState(null),[d,h]=u.useState(null),[p,f]=u.useState(null),m=fn(e);u.useEffect(()=>{if(typeof window>"u"||!m)return;const v=k=>{if(k.key===bl){const x=Yr(m);x&&x.syncedPhotos!==void 0&&f(x.syncedPhotos)}};return window.addEventListener("storage",v),()=>{window.removeEventListener("storage",v)}},[m]),u.useEffect(()=>{f(null)},[t]);const g=p??(t==null?void 0:t.syncedPhotos)??[],b=p!==null||(t==null?void 0:t.syncedPhotos)!==void 0,y=u.useMemo(()=>o||s?"syncing":l?"sync_error":b?g.length>0?"synced_success":"synced_empty":"never_synced",[o,s,l,b,g.length]),S=u.useCallback(async()=>{if(!n)return c("No Google Drive folder linked to this node."),null;i(!0),c(null);try{const v=await wu(e,n,g);return a(()=>{h(v.stats)}),v.stats}catch(v){const k=v instanceof Error?v.message:"Failed to sync photos from Google Drive.";throw c(k),v}finally{i(!1)}},[e,n,g]);return{syncedPhotos:g,syncState:y,hasSynced:b,isSyncing:o||s,error:l,lastStats:d,syncPhotos:S}}const Su=({title:e="No items found"})=>r.jsx("div",{children:e}),vt={sourceFigure:"_sourceFigure_1keci_15",collageItem:"_collageItem_1keci_27",photoCard:"_photoCard_1keci_33",clickable:"_clickable_1keci_51",disabled:"_disabled_1keci_82",sourceImageWrapper:"_sourceImageWrapper_1keci_88",aspectLandscape:"_aspectLandscape_1keci_96",aspectSquare:"_aspectSquare_1keci_100",aspectAuto:"_aspectAuto_1keci_104",overflowOverlay:"_overflowOverlay_1keci_109",overflowBadge:"_overflowBadge_1keci_135",sourceImage:"_sourceImage_1keci_88",captionWrapper:"_captionWrapper_1keci_158",photoCaption:"_photoCaption_1keci_167"},ku=({item:e,accentColor:t,onClick:n,onEditTitle:s,onEditPhoto:a,disabled:o=!1,className:i="",overlayCount:l,aspectRatio:c="landscape",hideCaption:d=!1})=>{var P;const{isDevMode:h,isDesktop:p}=Oe(),f=h&&p,m=e.photo??{src:e.imageSrc||"",alt:e.title,caption:e.title,showCaption:!1},g=u.useCallback(()=>{n&&n(e)},[n,e]),b=u.useCallback(V=>{(V.key==="Enter"||V.key===" ")&&n&&(V.preventDefault(),n(e))},[n,e]),y=!o&&!!n,S=!!(l&&l>0),v=m.caption??e.title,k=!!((S||m.showCaption)&&v),x=S?`+${l} more photos`:v,I=c==="square"?vt.aspectSquare:c==="auto"?vt.aspectAuto:vt.aspectLandscape,N=y?S?`View gallery photos, +${l} more in archive`:`View source photo: ${v||e.title}`:void 0,_=t?{"--card-accent":t}:void 0,T=e.driveFileId||((P=e.id)!=null&&P.startsWith("drive-")?e.id.replace(/^drive-/,""):"")||on(m.src||e.imageSrc||""),w=T&&!m.src.includes("/api/media/drive/")?ln(T,{width:800}):m.src,M=T?Mi(T):void 0,$="(max-width: 640px) 100vw, (max-width: 1024px) 50vw, 400px",A=T?`https://drive.google.com/thumbnail?id=${encodeURIComponent(T)}&sz=w1600`:void 0;return r.jsxs("figure",{className:`${vt.sourceFigure} ${d?vt.collageItem:""} ${o?vt.disabled:""} ${i}`,style:_,children:[r.jsx("div",{className:`${vt.photoCard} ${y?vt.clickable:""} ${o?vt.disabled:""}`,onClick:y?g:void 0,onKeyDown:y?b:void 0,role:y?"button":void 0,tabIndex:y?0:void 0,"aria-label":N,"aria-disabled":o?!0:void 0,children:r.jsxs("div",{className:`${vt.sourceImageWrapper} ${I}`,children:[r.jsx(pu,{src:w,srcSet:M,sizes:$,fallbackSrc:A,alt:m.alt||e.title,imageClassName:vt.sourceImage,loading:"lazy",decoding:"async"}),S&&r.jsx("div",{className:vt.overflowOverlay,"aria-hidden":"true",children:r.jsxs("span",{className:vt.overflowBadge,children:["+",l]})})]})}),!d&&r.jsxs("div",{className:vt.captionWrapper,children:[k&&r.jsx("figcaption",{className:vt.photoCaption,children:x}),f&&(a||s)&&r.jsx(me,{variant:"admin",size:"xs",onClick:V=>{V.stopPropagation(),a?a(e):s&&s(e)},title:"Edit photo details","aria-label":"Edit photo details",children:"✎ Edit"})]})]})},Jt={wrapper:"_wrapper_10c84_13",editorial:"_editorial_10c84_25",editorialContent:"_editorialContent_10c84_65",editorialHeader:"_editorialHeader_10c84_72",editorialTitle:"_editorialTitle_10c84_78",editorialDesc:"_editorialDesc_10c84_86",editorialAction:"_editorialAction_10c84_93",driveIcon:"_driveIcon_10c84_109",externalIcon:"_externalIcon_10c84_116",verifiedDot:"_verifiedDot_10c84_130"},tg=({pointId:e,label:t,variant:n="compact",accentColor:s,className:a=""})=>{const{isDevMode:o,isDesktop:i}=Oe(),l=o&&i,[c,d]=u.useState(!1);u.useEffect(()=>{!l&&c&&d(!1)},[l,c]);const{folderUrl:h,folderTitle:p,description:f,hasFolder:m,updateFolder:g}=Tl(e),b=t||p||"Official Google Drive Folder",y=`source.${fn(e)}.source`,S=u.useMemo(()=>({url:h,label:m?b:"",openInNewTab:!0}),[h,b,m]),v=u.useCallback((I,N,_)=>{_!=null&&_.url&&g(_.url,_.label)},[g]);if(!m&&!l)return null;const k=r.jsx("svg",{className:Jt.driveIcon,viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:r.jsx("path",{d:"M19.35 10.04C18.67 6.59 15.64 4 12 4 9.11 4 6.6 5.64 5.35 8.04 2.34 8.36 0 10.91 0 14c0 3.31 2.69 6 6 6h13c2.76 0 5-2.24 5-5 0-2.64-2.05-4.78-4.65-4.96zM19 18H6c-2.21 0-4-1.79-4-4 0-2.05 1.53-3.76 3.56-3.97l1.07-.11.5-.95C8.08 7.14 9.94 6 12 6c2.62 0 4.88 1.86 5.39 4.43l.3 1.5 1.53.11c1.56.1 2.78 1.41 2.78 2.96 0 1.65-1.35 3-3 3z"})}),x=()=>{if(!m&&l)return r.jsx(qs,{variant:"neutral",size:"sm",icon:k,label:"Attach Drive Folder",title:"No Drive folder configured. Use Edit to link an official folder."});if(n==="editorial"){const I=s?{"--accent":s}:void 0;return r.jsxs("a",{href:h,target:"_blank",rel:"noopener noreferrer",className:Jt.editorial,style:I,"aria-label":`Official Google Drive Folder: ${b}`,children:[r.jsxs("div",{className:Jt.editorialContent,children:[r.jsxs("div",{className:Jt.editorialHeader,children:[r.jsx("span",{className:Jt.verifiedDot,"aria-hidden":"true"}),k,r.jsx("span",{className:Jt.editorialTitle,children:b})]}),f&&r.jsx("span",{className:Jt.editorialDesc,children:f})]}),r.jsxs("span",{className:Jt.editorialAction,children:["Inspect MOV Archive ",r.jsx("span",{className:Jt.externalIcon,"aria-hidden":"true",children:"↗"})]})]})}return r.jsx(qs,{variant:"link",size:"sm",href:h,icon:k,label:b,ariaLabel:`Official Google Drive Folder: ${b}`})};return r.jsxs("div",{className:`${Jt.wrapper} ${a}`.trim(),children:[r.jsx(Qn,{pointId:y,type:"link",defaultValue:S,currentValue:S,onEditText:()=>d(!0),onSave:v,children:x()}),r.jsx(Cl,{isOpen:c,pointId:e,initialTitle:m?p:"",initialUrl:h,onClose:()=>d(!1),onSuccess:(I,N)=>{g(I,N)}})]})},Gt={modalBody:"_modalBody_f0gv9_1",photoPreviewBlock:"_photoPreviewBlock_f0gv9_8",previewThumbnail:"_previewThumbnail_f0gv9_17",previewMeta:"_previewMeta_f0gv9_26",previewLabel:"_previewLabel_f0gv9_33",previewOriginalName:"_previewOriginalName_f0gv9_41",formGroup:"_formGroup_f0gv9_50",fieldLabel:"_fieldLabel_f0gv9_56",inputField:"_inputField_f0gv9_63",fieldHint:"_fieldHint_f0gv9_83",actionRow:"_actionRow_f0gv9_90"},ng=({isOpen:e,item:t,photoItem:n,onClose:s,onSave:a})=>{var v;const o=t??n??null,{isDevMode:i,isDesktop:l,showToast:c}=Oe(),[d,h]=u.useState(""),[p,f]=u.useState(!1),m=u.useRef(null);if(u.useEffect(()=>{e&&(!i||!l)&&s()},[e,i,l,s]),u.useEffect(()=>{var k,x;if(e&&o){const I=!!((k=o.photo)!=null&&k.src||o.imageSrc),N=o.title||((x=o.photo)==null?void 0:x.caption)||"";h(!I||(N==="Evidence photograph"||N==="Evidence documentation photo"||N==="Photographic proof for this strategic milestone."||N==="Photo Caption")?"":N),f(!1);const T=setTimeout(()=>{var w;(w=m.current)==null||w.focus()},50);return()=>clearTimeout(T)}},[e,o]),!e||!o)return null;const g=o,b=((v=o.photo)==null?void 0:v.src)||o.imageSrc||g.thumbnailUrl||"",y=g.originalFileName,S=async k=>{if(k&&k.preventDefault(),!(!d.trim()||p)){f(!0);try{await a(o.id,d.trim()),c("Photo title saved to draft successfully.","success"),s()}catch(x){console.error("Failed to save photo title:",x),c("Failed to save photo title.","error")}finally{f(!1)}}};return r.jsx(bt,{isOpen:e,onClose:s,onConfirm:!p&&d.trim()?()=>{S()}:void 0,title:"Edit Photo Title",maxWidth:"540px",children:r.jsxs("form",{onSubmit:S,className:Gt.modalBody,children:[b&&r.jsxs("div",{className:Gt.photoPreviewBlock,children:[r.jsx("img",{src:b,alt:o.title,className:Gt.previewThumbnail,referrerPolicy:"no-referrer"}),r.jsxs("div",{className:Gt.previewMeta,children:[r.jsx("span",{className:Gt.previewLabel,children:"Google Drive Asset"}),y&&r.jsx("span",{className:Gt.previewOriginalName,title:y,children:y})]})]}),r.jsxs("div",{className:Gt.formGroup,children:[r.jsx("label",{htmlFor:"edit-photo-title",className:Gt.fieldLabel,children:"Title / Caption"}),r.jsx("input",{ref:m,id:"edit-photo-title",type:"text",className:Gt.inputField,value:d,onChange:k=>h(k.target.value),placeholder:"e.g., Community Stakeholders Assembly",disabled:p,required:!0}),r.jsx("p",{className:Gt.fieldHint,children:"This title will be preserved across future Google Drive folder syncs."})]}),r.jsxs("div",{className:Gt.actionRow,children:[r.jsx(me,{variant:"secondary",size:"sm",type:"button",onClick:s,disabled:p,children:"Cancel"}),r.jsx(me,{variant:"primary",size:"sm",type:"submit",disabled:p||!d.trim(),children:p?"Saving...":"Save Title"})]})]})})},Qe={container:"_container_1ejsb_12",footer:"_footer_1ejsb_20",footerLeft:"_footerLeft_1ejsb_30",footerRight:"_footerRight_1ejsb_37",syncButton:"_syncButton_1ejsb_46",syncIcon:"_syncIcon_1ejsb_92",syncing:"_syncing_1ejsb_99",galleryCardContainer:"_galleryCardContainer_1ejsb_113",galleryCardBody:"_galleryCardBody_1ejsb_121",sideEditWrapper:"_sideEditWrapper_1ejsb_129",sideEditBtn:"_sideEditBtn_1ejsb_138",sideSyncBtn:"_sideSyncBtn_1ejsb_139",highlightedGallery:"_highlightedGallery_1ejsb_146",collageContainer:"_collageContainer_1ejsb_154",topRow:"_topRow_1ejsb_165",topRowSingle:"_topRowSingle_1ejsb_172",bottomRow:"_bottomRow_1ejsb_176",bottomRowDuo:"_bottomRowDuo_1ejsb_183"},rg=({nodeId:e,sourceItems:t,accentColor:n,className:s="",editTriggerId:a})=>{const[o,i]=u.useState(!1),[l,c]=u.useState(0),[d,h]=u.useState(!1),[p,f]=u.useState(null),[m,g]=u.useState(null),[b,y]=u.useState("success"),[S,v]=u.useState(!1),{isDevMode:k,isDesktop:x}=Oe(),I=k&&x;u.useEffect(()=>{I||(d&&h(!1),p&&f(null))},[I,d,p]);const{folderUrl:N,folderTitle:_,hasFolder:T,updateFolder:w}=Tl(e),{syncedPhotos:M,syncState:$,isSyncing:A,syncPhotos:P,error:V}=eg(e),D=u.useMemo(()=>zm(e),[e]),W=`source.${fn(e)}.source`,H=N||(D==null?void 0:D.folderUrl)||"",q=_||(D==null?void 0:D.folderTitle)||"Official Google Drive Folder",j=T||!!(H&&H.trim().length>0),z=u.useMemo(()=>$==="synced_success"&&M.length>0?M:t,[$,M,t]),O=$==="synced_empty",U=!O&&z.length>0,Q=u.useCallback(async()=>{try{const te=await P();te?te.total===0?(g("Sync completed: 0 photos found in the Google Drive folder."),y("info")):te.hasChanged?(g(`Synced ${te.total} photos (+${te.added} added, -${te.removed} removed).`),y("success")):(g(`Gallery is up to date (${te.total} photos verified).`),y("info")):(g(V||"Sync completed with no changes."),y(V?"error":"info"))}catch(te){const K=te instanceof Error?te.message:"Failed to sync photos from Google Drive.";g(K),y("error")}},[P,V]),se=u.useCallback(async(te,K,J,Z)=>{const ne=K.trim();if(ne)if(M&&M.length>0){const ie=M.map(F=>{var L;return F.id===te||F.driveFileId===te?{...F,title:ne,date:J||F.date,dateStamp:J||F.dateStamp,isCustomTitle:!0,photo:{...F.photo,src:((L=F.photo)==null?void 0:L.src)||F.fullImageUrl||F.thumbnailUrl||"",alt:ne,caption:(Z==null?void 0:Z.trim())||ne,showCaption:!0}}:F});await Zr({pointId:e,folderUrl:H,folderTitle:q,syncedPhotos:ie,updatedBy:"Coordinator"}),g(`Updated photo: "${ne}".`),y("success")}else{const ie=z.map((F,L)=>{var he,oe,ye,xe,ke;const G=F.id===te||F.driveFileId===te,le=G?ne:F.title,ue=G&&J?J:F.date||F.dateStamp||"2026-10-09";return{id:F.id,pointId:e,driveFileId:F.driveFileId||F.id,originalFileName:F.originalFileName||`${F.id}.jpg`,title:le,isCustomTitle:G?!0:F.isCustomTitle??!1,orderIndex:L,date:ue,dateStamp:ue,thumbnailUrl:((he=F.photo)==null?void 0:he.src)||F.imageSrc||"",fullImageUrl:((oe=F.photo)==null?void 0:oe.src)||F.imageSrc||"",imageSrc:((ye=F.photo)==null?void 0:ye.src)||F.imageSrc||"",photo:{src:((xe=F.photo)==null?void 0:xe.src)||F.imageSrc||"",alt:le,caption:G?(Z==null?void 0:Z.trim())||le:((ke=F.photo)==null?void 0:ke.caption)||le,showCaption:!0}}});await Zr({pointId:e,folderUrl:H,folderTitle:q,syncedPhotos:ie,updatedBy:"Coordinator"}),g(`Updated photo: "${ne}".`),y("success")}},[M,z,e,H,q]),ae=u.useCallback(te=>{c(te),i(!0)},[]),de=u.useCallback(()=>{i(!1)},[]),B=u.useCallback(te=>{c(te)},[]),Y=z.length,{topRowItems:ee,bottomRowItems:X}=u.useMemo(()=>Y===0?{topRowItems:[],bottomRowItems:[]}:Y===1?{topRowItems:[{item:z[0],originalIndex:0,aspectRatio:"landscape"}],bottomRowItems:[]}:Y===2?{topRowItems:[{item:z[0],originalIndex:0,aspectRatio:"landscape"},{item:z[1],originalIndex:1,aspectRatio:"landscape"}],bottomRowItems:[]}:Y===3?{topRowItems:[{item:z[0],originalIndex:0,aspectRatio:"landscape"}],bottomRowItems:[{item:z[1],originalIndex:1,aspectRatio:"landscape"},{item:z[2],originalIndex:2,aspectRatio:"landscape"}]}:Y===4?{topRowItems:[{item:z[0],originalIndex:0,aspectRatio:"landscape"},{item:z[1],originalIndex:1,aspectRatio:"landscape"}],bottomRowItems:[{item:z[2],originalIndex:2,aspectRatio:"landscape"},{item:z[3],originalIndex:3,aspectRatio:"landscape"}]}:{topRowItems:[{item:z[0],originalIndex:0,aspectRatio:"landscape"},{item:z[1],originalIndex:1,aspectRatio:"landscape"}],bottomRowItems:[{item:z[2],originalIndex:2,aspectRatio:"square"},{item:z[3],originalIndex:3,aspectRatio:"square"},{item:z[4],originalIndex:4,aspectRatio:"square",overlayCount:Y-4}]},[z,Y]);return r.jsxs("div",{className:`${Qe.container} ${s}`.trim(),children:[r.jsxs("div",{className:Qe.galleryCardContainer,children:[r.jsx("div",{className:`${Qe.galleryCardBody} ${S?Qe.highlightedGallery:""}`,children:U?r.jsxs("div",{className:Qe.collageContainer,children:[ee.length>0&&r.jsx("div",{className:`${Qe.topRow} ${ee.length===1?Qe.topRowSingle:""}`.trim(),children:ee.map(te=>r.jsx(ku,{item:te.item,accentColor:n,aspectRatio:te.aspectRatio,hideCaption:!0,onClick:()=>ae(te.originalIndex),onEditPhoto:K=>f(K)},te.item.id))}),X.length>0&&r.jsx("div",{className:`${Qe.bottomRow} ${X.length===2?Qe.bottomRowDuo:""}`.trim(),children:X.map(te=>r.jsx(ku,{item:te.item,accentColor:n,aspectRatio:te.aspectRatio,hideCaption:!0,overlayCount:"overlayCount"in te?te.overlayCount:void 0,onClick:()=>ae(te.originalIndex),onEditPhoto:K=>f(K)},te.item.id))})]}):O?r.jsx(Su,{variant:"card",title:"No Photos Found in Drive Folder",description:"The linked Google Drive folder does not contain any image files yet. Upload Means of Verification (MOVs) to Google Drive to display them here.",actionLabel:H?"Open Google Drive to Upload ↗":void 0,onAction:H?()=>{typeof window<"u"&&window.open(H,"_blank","noopener,noreferrer")}:void 0}):r.jsx(Su,{variant:"card",title:"Evidence Documentation in Progress",description:"Official Means of Verification (MOVs), activity photos, and completion reports are currently being compiled for this node."})}),I&&r.jsxs("div",{className:Qe.sideEditWrapper,children:[r.jsx(me,{type:"button",variant:"admin",size:"xs","data-dev-edit-trigger":"true","data-canvas-edit-trigger":a,onClick:()=>h(!0),onMouseEnter:()=>v(!0),onMouseLeave:()=>v(!1),className:Qe.sideEditBtn,title:"Edit source photo repository","aria-label":"Edit source photo repository",children:"✎ Edit"}),r.jsxs(me,{type:"button",variant:"admin",size:"xs",onClick:Q,onMouseEnter:()=>v(!0),onMouseLeave:()=>v(!1),disabled:A,className:Qe.sideSyncBtn,title:"Sync photos from Google Drive","aria-label":"Sync photos from Google Drive",children:[r.jsx("span",{className:`${Qe.syncIcon} ${A?Qe.spinning:""}`,"aria-hidden":"true",children:"↻"}),r.jsx("span",{children:A?"Syncing…":"Sync"})]})]})]}),o&&r.jsx(mu,{isOpen:o,items:z,currentIndex:l,driveFolderUrl:H,accentColor:n,onClose:de,onNavigate:B,onEditSource:()=>h(!0),onEditPhoto:te=>f(te)}),(j||I)&&r.jsxs("div",{className:Qe.footer,children:[r.jsx("div",{className:Qe.footerLeft,children:r.jsx(tg,{pointId:e,variant:"compact",accentColor:n})}),I&&j&&r.jsx("div",{className:Qe.footerRight,children:r.jsxs("button",{type:"button",className:`${Qe.syncButton} ${A?Qe.syncing:""}`,onClick:Q,disabled:A,title:"Reconcile and sync photos from Google Drive","aria-label":"Sync photos from Google Drive",children:[r.jsx("span",{className:Qe.syncIcon,"aria-hidden":"true",children:"↻"}),r.jsx("span",{children:A?"Syncing...":"Sync Photos"})]})})]}),W&&r.jsx(Cl,{isOpen:d,pointId:e,initialTitle:q,initialUrl:H,onClose:()=>h(!1),onSuccess:(te,K)=>{w(te,K)}}),p&&r.jsx(ng,{isOpen:!!p,photoItem:p,onClose:()=>f(null),onSave:se}),m&&r.jsx(Zt,{message:m,type:b,onDismiss:()=>g(null)})]})},sg=Array.isArray(Nl)?Nl:Nl.nodes||[],Al=u.memo(({element:e,nodeId:t,accentColor:n,className:s})=>{const a=u.useMemo(()=>{const o=sg.find(i=>i.id===t);return(o==null?void 0:o.sourceItems)||[]},[t]);return r.jsx("div",{className:`${Zs.galleryWrapper} ${s||""}`.trim(),children:r.jsx(rg,{nodeId:t,sourceItems:a,accentColor:n,editTriggerId:e.id})})});Al.displayName="CanvasGallery";function lo(e,t){return e==null||t==null?NaN:e<t?-1:e>t?1:e>=t?0:NaN}function ag(e,t){return e==null||t==null?NaN:t<e?-1:t>e?1:t>=e?0:NaN}function Cu(e){let t,n,s;e.length!==2?(t=lo,n=(l,c)=>lo(e(l),c),s=(l,c)=>e(l)-c):(t=e===lo||e===ag?e:og,n=e,s=e);function a(l,c,d=0,h=l.length){if(d<h){if(t(c,c)!==0)return h;do{const p=d+h>>>1;n(l[p],c)<0?d=p+1:h=p}while(d<h)}return d}function o(l,c,d=0,h=l.length){if(d<h){if(t(c,c)!==0)return h;do{const p=d+h>>>1;n(l[p],c)<=0?d=p+1:h=p}while(d<h)}return d}function i(l,c,d=0,h=l.length){const p=a(l,c,d,h-1);return p>d&&s(l[p-1],c)>-s(l[p],c)?p-1:p}return{left:a,center:i,right:o}}function og(){return 0}function ig(e){return e===null?NaN:+e}const lg=Cu(lo).right;Cu(ig).center;function cg(e,t){let n,s;for(const a of e)a!=null&&(n===void 0?a>=a&&(n=s=a):(n>a&&(n=a),s<a&&(s=a)));return[n,s]}class xu extends Map{constructor(t,n=hg){if(super(),Object.defineProperties(this,{_intern:{value:new Map},_key:{value:n}}),t!=null)for(const[s,a]of t)this.set(s,a)}get(t){return super.get(Nu(this,t))}has(t){return super.has(Nu(this,t))}set(t,n){return super.set(dg(this,t),n)}delete(t){return super.delete(ug(this,t))}}function Nu({_intern:e,_key:t},n){const s=t(n);return e.has(s)?e.get(s):n}function dg({_intern:e,_key:t},n){const s=t(n);return e.has(s)?e.get(s):(e.set(s,n),n)}function ug({_intern:e,_key:t},n){const s=t(n);return e.has(s)&&(n=e.get(s),e.delete(s)),n}function hg(e){return e!==null&&typeof e=="object"?e.valueOf():e}const fg=Math.sqrt(50),pg=Math.sqrt(10),mg=Math.sqrt(2);function co(e,t,n){const s=(t-e)/Math.max(0,n),a=Math.floor(Math.log10(s)),o=s/Math.pow(10,a),i=o>=fg?10:o>=pg?5:o>=mg?2:1;let l,c,d;return a<0?(d=Math.pow(10,-a)/i,l=Math.round(e*d),c=Math.round(t*d),l/d<e&&++l,c/d>t&&--c,d=-d):(d=Math.pow(10,a)*i,l=Math.round(e/d),c=Math.round(t/d),l*d<e&&++l,c*d>t&&--c),c<l&&.5<=n&&n<2?co(e,t,n*2):[l,c,d]}function gg(e,t,n){if(t=+t,e=+e,n=+n,!(n>0))return[];if(e===t)return[e];const s=t<e,[a,o,i]=s?co(t,e,n):co(e,t,n);if(!(o>=a))return[];const l=o-a+1,c=new Array(l);if(s)if(i<0)for(let d=0;d<l;++d)c[d]=(o-d)/-i;else for(let d=0;d<l;++d)c[d]=(o-d)*i;else if(i<0)for(let d=0;d<l;++d)c[d]=(a+d)/-i;else for(let d=0;d<l;++d)c[d]=(a+d)*i;return c}function Il(e,t,n){return t=+t,e=+e,n=+n,co(e,t,n)[2]}function vg(e,t,n){t=+t,e=+e,n=+n;const s=t<e,a=s?Il(t,e,n):Il(e,t,n);return(s?-1:1)*(a<0?1/-a:a)}function bg(e,t,n){e=+e,t=+t,n=(a=arguments.length)<2?(t=e,e=0,1):a<3?1:+n;for(var s=-1,a=Math.max(0,Math.ceil((t-e)/n))|0,o=new Array(a);++s<a;)o[s]=e+s*n;return o}function $l(e,t){switch(arguments.length){case 0:break;case 1:this.range(e);break;default:this.range(t).domain(e);break}return this}const Tu=Symbol("implicit");function Au(){var e=new xu,t=[],n=[],s=Tu;function a(o){let i=e.get(o);if(i===void 0){if(s!==Tu)return s;e.set(o,i=t.push(o)-1)}return n[i%n.length]}return a.domain=function(o){if(!arguments.length)return t.slice();t=[],e=new xu;for(const i of o)e.has(i)||e.set(i,t.push(i)-1);return a},a.range=function(o){return arguments.length?(n=Array.from(o),a):n.slice()},a.unknown=function(o){return arguments.length?(s=o,a):s},a.copy=function(){return Au(t,n).unknown(s)},$l.apply(a,arguments),a}function Iu(){var e=Au().unknown(void 0),t=e.domain,n=e.range,s=0,a=1,o,i,l=!1,c=0,d=0,h=.5;delete e.unknown;function p(){var f=t().length,m=a<s,g=m?a:s,b=m?s:a;o=(b-g)/Math.max(1,f-c+d*2),l&&(o=Math.floor(o)),g+=(b-g-o*(f-c))*h,i=o*(1-c),l&&(g=Math.round(g),i=Math.round(i));var y=bg(f).map(function(S){return g+o*S});return n(m?y.reverse():y)}return e.domain=function(f){return arguments.length?(t(f),p()):t()},e.range=function(f){return arguments.length?([s,a]=f,s=+s,a=+a,p()):[s,a]},e.rangeRound=function(f){return[s,a]=f,s=+s,a=+a,l=!0,p()},e.bandwidth=function(){return i},e.step=function(){return o},e.round=function(f){return arguments.length?(l=!!f,p()):l},e.padding=function(f){return arguments.length?(c=Math.min(1,d=+f),p()):c},e.paddingInner=function(f){return arguments.length?(c=Math.min(1,f),p()):c},e.paddingOuter=function(f){return arguments.length?(d=+f,p()):d},e.align=function(f){return arguments.length?(h=Math.max(0,Math.min(1,f)),p()):h},e.copy=function(){return Iu(t(),[s,a]).round(l).paddingInner(c).paddingOuter(d).align(h)},$l.apply(p(),arguments)}function El(e,t,n){e.prototype=t.prototype=n,n.constructor=e}function $u(e,t){var n=Object.create(e.prototype);for(var s in t)n[s]=t[s];return n}function Rs(){}var ea=.7,uo=1/ea,Xr="\\s*([+-]?\\d+)\\s*",ta="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",Qt="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",yg=/^#([0-9a-f]{3,8})$/,_g=new RegExp(`^rgb\\(${Xr},${Xr},${Xr}\\)$`),wg=new RegExp(`^rgb\\(${Qt},${Qt},${Qt}\\)$`),Sg=new RegExp(`^rgba\\(${Xr},${Xr},${Xr},${ta}\\)$`),kg=new RegExp(`^rgba\\(${Qt},${Qt},${Qt},${ta}\\)$`),Cg=new RegExp(`^hsl\\(${ta},${Qt},${Qt}\\)$`),xg=new RegExp(`^hsla\\(${ta},${Qt},${Qt},${ta}\\)$`),Eu={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074};El(Rs,na,{copy(e){return Object.assign(new this.constructor,this,e)},displayable(){return this.rgb().displayable()},hex:Lu,formatHex:Lu,formatHex8:Ng,formatHsl:Tg,formatRgb:Mu,toString:Mu});function Lu(){return this.rgb().formatHex()}function Ng(){return this.rgb().formatHex8()}function Tg(){return Fu(this).formatHsl()}function Mu(){return this.rgb().formatRgb()}function na(e){var t,n;return e=(e+"").trim().toLowerCase(),(t=yg.exec(e))?(n=t[1].length,t=parseInt(t[1],16),n===6?Du(t):n===3?new yt(t>>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):n===8?ho(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):n===4?ho(t>>12&15|t>>8&240,t>>8&15|t>>4&240,t>>4&15|t&240,((t&15)<<4|t&15)/255):null):(t=_g.exec(e))?new yt(t[1],t[2],t[3],1):(t=wg.exec(e))?new yt(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=Sg.exec(e))?ho(t[1],t[2],t[3],t[4]):(t=kg.exec(e))?ho(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=Cg.exec(e))?Pu(t[1],t[2]/100,t[3]/100,1):(t=xg.exec(e))?Pu(t[1],t[2]/100,t[3]/100,t[4]):Eu.hasOwnProperty(e)?Du(Eu[e]):e==="transparent"?new yt(NaN,NaN,NaN,0):null}function Du(e){return new yt(e>>16&255,e>>8&255,e&255,1)}function ho(e,t,n,s){return s<=0&&(e=t=n=NaN),new yt(e,t,n,s)}function Ag(e){return e instanceof Rs||(e=na(e)),e?(e=e.rgb(),new yt(e.r,e.g,e.b,e.opacity)):new yt}function Ll(e,t,n,s){return arguments.length===1?Ag(e):new yt(e,t,n,s??1)}function yt(e,t,n,s){this.r=+e,this.g=+t,this.b=+n,this.opacity=+s}El(yt,Ll,$u(Rs,{brighter(e){return e=e==null?uo:Math.pow(uo,e),new yt(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=e==null?ea:Math.pow(ea,e),new yt(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new yt(Rn(this.r),Rn(this.g),Rn(this.b),fo(this.opacity))},displayable(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:Bu,formatHex:Bu,formatHex8:Ig,formatRgb:Ou,toString:Ou}));function Bu(){return`#${er(this.r)}${er(this.g)}${er(this.b)}`}function Ig(){return`#${er(this.r)}${er(this.g)}${er(this.b)}${er((isNaN(this.opacity)?1:this.opacity)*255)}`}function Ou(){const e=fo(this.opacity);return`${e===1?"rgb(":"rgba("}${Rn(this.r)}, ${Rn(this.g)}, ${Rn(this.b)}${e===1?")":`, ${e})`}`}function fo(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function Rn(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function er(e){return e=Rn(e),(e<16?"0":"")+e.toString(16)}function Pu(e,t,n,s){return s<=0?e=t=n=NaN:n<=0||n>=1?e=t=NaN:t<=0&&(e=NaN),new Wt(e,t,n,s)}function Fu(e){if(e instanceof Wt)return new Wt(e.h,e.s,e.l,e.opacity);if(e instanceof Rs||(e=na(e)),!e)return new Wt;if(e instanceof Wt)return e;e=e.rgb();var t=e.r/255,n=e.g/255,s=e.b/255,a=Math.min(t,n,s),o=Math.max(t,n,s),i=NaN,l=o-a,c=(o+a)/2;return l?(t===o?i=(n-s)/l+(n<s)*6:n===o?i=(s-t)/l+2:i=(t-n)/l+4,l/=c<.5?o+a:2-o-a,i*=60):l=c>0&&c<1?0:i,new Wt(i,l,c,e.opacity)}function $g(e,t,n,s){return arguments.length===1?Fu(e):new Wt(e,t,n,s??1)}function Wt(e,t,n,s){this.h=+e,this.s=+t,this.l=+n,this.opacity=+s}El(Wt,$g,$u(Rs,{brighter(e){return e=e==null?uo:Math.pow(uo,e),new Wt(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?ea:Math.pow(ea,e),new Wt(this.h,this.s,this.l*e,this.opacity)},rgb(){var e=this.h%360+(this.h<0)*360,t=isNaN(e)||isNaN(this.s)?0:this.s,n=this.l,s=n+(n<.5?n:1-n)*t,a=2*n-s;return new yt(Ml(e>=240?e-240:e+120,a,s),Ml(e,a,s),Ml(e<120?e+240:e-120,a,s),this.opacity)},clamp(){return new Wt(Uu(this.h),po(this.s),po(this.l),fo(this.opacity))},displayable(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl(){const e=fo(this.opacity);return`${e===1?"hsl(":"hsla("}${Uu(this.h)}, ${po(this.s)*100}%, ${po(this.l)*100}%${e===1?")":`, ${e})`}`}}));function Uu(e){return e=(e||0)%360,e<0?e+360:e}function po(e){return Math.max(0,Math.min(1,e||0))}function Ml(e,t,n){return(e<60?t+(n-t)*e/60:e<180?n:e<240?t+(n-t)*(240-e)/60:t)*255}const Dl=e=>()=>e;function Eg(e,t){return function(n){return e+n*t}}function Lg(e,t,n){return e=Math.pow(e,n),t=Math.pow(t,n)-e,n=1/n,function(s){return Math.pow(e+s*t,n)}}function Mg(e){return(e=+e)==1?zu:function(t,n){return n-t?Lg(t,n,e):Dl(isNaN(t)?n:t)}}function zu(e,t){var n=t-e;return n?Eg(e,n):Dl(isNaN(e)?t:e)}const Gu=(function e(t){var n=Mg(t);function s(a,o){var i=n((a=Ll(a)).r,(o=Ll(o)).r),l=n(a.g,o.g),c=n(a.b,o.b),d=zu(a.opacity,o.opacity);return function(h){return a.r=i(h),a.g=l(h),a.b=c(h),a.opacity=d(h),a+""}}return s.gamma=e,s})(1);function Dg(e,t){t||(t=[]);var n=e?Math.min(t.length,e.length):0,s=t.slice(),a;return function(o){for(a=0;a<n;++a)s[a]=e[a]*(1-o)+t[a]*o;return s}}function Bg(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function Og(e,t){var n=t?t.length:0,s=e?Math.min(n,e.length):0,a=new Array(s),o=new Array(n),i;for(i=0;i<s;++i)a[i]=Pl(e[i],t[i]);for(;i<n;++i)o[i]=t[i];return function(l){for(i=0;i<s;++i)o[i]=a[i](l);return o}}function Pg(e,t){var n=new Date;return e=+e,t=+t,function(s){return n.setTime(e*(1-s)+t*s),n}}function mo(e,t){return e=+e,t=+t,function(n){return e*(1-n)+t*n}}function Fg(e,t){var n={},s={},a;(e===null||typeof e!="object")&&(e={}),(t===null||typeof t!="object")&&(t={});for(a in t)a in e?n[a]=Pl(e[a],t[a]):s[a]=t[a];return function(o){for(a in n)s[a]=n[a](o);return s}}var Bl=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,Ol=new RegExp(Bl.source,"g");function Ug(e){return function(){return e}}function zg(e){return function(t){return e(t)+""}}function Gg(e,t){var n=Bl.lastIndex=Ol.lastIndex=0,s,a,o,i=-1,l=[],c=[];for(e=e+"",t=t+"";(s=Bl.exec(e))&&(a=Ol.exec(t));)(o=a.index)>n&&(o=t.slice(n,o),l[i]?l[i]+=o:l[++i]=o),(s=s[0])===(a=a[0])?l[i]?l[i]+=a:l[++i]=a:(l[++i]=null,c.push({i,x:mo(s,a)})),n=Ol.lastIndex;return n<t.length&&(o=t.slice(n),l[i]?l[i]+=o:l[++i]=o),l.length<2?c[0]?zg(c[0].x):Ug(t):(t=c.length,function(d){for(var h=0,p;h<t;++h)l[(p=c[h]).i]=p.x(d);return l.join("")})}function Pl(e,t){var n=typeof t,s;return t==null||n==="boolean"?Dl(t):(n==="number"?mo:n==="string"?(s=na(t))?(t=s,Gu):Gg:t instanceof na?Gu:t instanceof Date?Pg:Bg(t)?Dg:Array.isArray(t)?Og:typeof t.valueOf!="function"&&typeof t.toString!="function"||isNaN(t)?Fg:mo)(e,t)}function Wg(e,t){return e=+e,t=+t,function(n){return Math.round(e*(1-n)+t*n)}}function Hg(e){return function(){return e}}function Vg(e){return+e}var Wu=[0,1];function Jr(e){return e}function Fl(e,t){return(t-=e=+e)?function(n){return(n-e)/t}:Hg(isNaN(t)?NaN:.5)}function qg(e,t){var n;return e>t&&(n=e,e=t,t=n),function(s){return Math.max(e,Math.min(t,s))}}function jg(e,t,n){var s=e[0],a=e[1],o=t[0],i=t[1];return a<s?(s=Fl(a,s),o=n(i,o)):(s=Fl(s,a),o=n(o,i)),function(l){return o(s(l))}}function Kg(e,t,n){var s=Math.min(e.length,t.length)-1,a=new Array(s),o=new Array(s),i=-1;for(e[s]<e[0]&&(e=e.slice().reverse(),t=t.slice().reverse());++i<s;)a[i]=Fl(e[i],e[i+1]),o[i]=n(t[i],t[i+1]);return function(l){var c=lg(e,l,1,s)-1;return o[c](a[c](l))}}function Yg(e,t){return t.domain(e.domain()).range(e.range()).interpolate(e.interpolate()).clamp(e.clamp()).unknown(e.unknown())}function Zg(){var e=Wu,t=Wu,n=Pl,s,a,o,i=Jr,l,c,d;function h(){var f=Math.min(e.length,t.length);return i!==Jr&&(i=qg(e[0],e[f-1])),l=f>2?Kg:jg,c=d=null,p}function p(f){return f==null||isNaN(f=+f)?o:(c||(c=l(e.map(s),t,n)))(s(i(f)))}return p.invert=function(f){return i(a((d||(d=l(t,e.map(s),mo)))(f)))},p.domain=function(f){return arguments.length?(e=Array.from(f,Vg),h()):e.slice()},p.range=function(f){return arguments.length?(t=Array.from(f),h()):t.slice()},p.rangeRound=function(f){return t=Array.from(f),n=Wg,h()},p.clamp=function(f){return arguments.length?(i=f?!0:Jr,h()):i!==Jr},p.interpolate=function(f){return arguments.length?(n=f,h()):n},p.unknown=function(f){return arguments.length?(o=f,p):o},function(f,m){return s=f,a=m,h()}}function Xg(){return Zg()(Jr,Jr)}function Jg(e){return Math.abs(e=Math.round(e))>=1e21?e.toLocaleString("en").replace(/,/g,""):e.toString(10)}function go(e,t){if(!isFinite(e)||e===0)return null;var n=(e=t?e.toExponential(t-1):e.toExponential()).indexOf("e"),s=e.slice(0,n);return[s.length>1?s[0]+s.slice(2):s,+e.slice(n+1)]}function Qr(e){return e=go(Math.abs(e)),e?e[1]:NaN}function Qg(e,t){return function(n,s){for(var a=n.length,o=[],i=0,l=e[0],c=0;a>0&&l>0&&(c+l+1>s&&(l=Math.max(1,s-c)),o.push(n.substring(a-=l,a+l)),!((c+=l+1)>s));)l=e[i=(i+1)%e.length];return o.reverse().join(t)}}function Rg(e){return function(t){return t.replace(/[0-9]/g,function(n){return e[+n]})}}var ev=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;function vo(e){if(!(t=ev.exec(e)))throw new Error("invalid format: "+e);var t;return new Ul({fill:t[1],align:t[2],sign:t[3],symbol:t[4],zero:t[5],width:t[6],comma:t[7],precision:t[8]&&t[8].slice(1),trim:t[9],type:t[10]})}vo.prototype=Ul.prototype;function Ul(e){this.fill=e.fill===void 0?" ":e.fill+"",this.align=e.align===void 0?">":e.align+"",this.sign=e.sign===void 0?"-":e.sign+"",this.symbol=e.symbol===void 0?"":e.symbol+"",this.zero=!!e.zero,this.width=e.width===void 0?void 0:+e.width,this.comma=!!e.comma,this.precision=e.precision===void 0?void 0:+e.precision,this.trim=!!e.trim,this.type=e.type===void 0?"":e.type+""}Ul.prototype.toString=function(){return this.fill+this.align+this.sign+this.symbol+(this.zero?"0":"")+(this.width===void 0?"":Math.max(1,this.width|0))+(this.comma?",":"")+(this.precision===void 0?"":"."+Math.max(0,this.precision|0))+(this.trim?"~":"")+this.type};function tv(e){e:for(var t=e.length,n=1,s=-1,a;n<t;++n)switch(e[n]){case".":s=a=n;break;case"0":s===0&&(s=n),a=n;break;default:if(!+e[n])break e;s>0&&(s=0);break}return s>0?e.slice(0,s)+e.slice(a+1):e}var bo;function nv(e,t){var n=go(e,t);if(!n)return bo=void 0,e.toPrecision(t);var s=n[0],a=n[1],o=a-(bo=Math.max(-8,Math.min(8,Math.floor(a/3)))*3)+1,i=s.length;return o===i?s:o>i?s+new Array(o-i+1).join("0"):o>0?s.slice(0,o)+"."+s.slice(o):"0."+new Array(1-o).join("0")+go(e,Math.max(0,t+o-1))[0]}function Hu(e,t){var n=go(e,t);if(!n)return e+"";var s=n[0],a=n[1];return a<0?"0."+new Array(-a).join("0")+s:s.length>a+1?s.slice(0,a+1)+"."+s.slice(a+1):s+new Array(a-s.length+2).join("0")}const Vu={"%":(e,t)=>(e*100).toFixed(t),b:e=>Math.round(e).toString(2),c:e=>e+"",d:Jg,e:(e,t)=>e.toExponential(t),f:(e,t)=>e.toFixed(t),g:(e,t)=>e.toPrecision(t),o:e=>Math.round(e).toString(8),p:(e,t)=>Hu(e*100,t),r:Hu,s:nv,X:e=>Math.round(e).toString(16).toUpperCase(),x:e=>Math.round(e).toString(16)};function qu(e){return e}var ju=Array.prototype.map,Ku=["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"];function rv(e){var t=e.grouping===void 0||e.thousands===void 0?qu:Qg(ju.call(e.grouping,Number),e.thousands+""),n=e.currency===void 0?"":e.currency[0]+"",s=e.currency===void 0?"":e.currency[1]+"",a=e.decimal===void 0?".":e.decimal+"",o=e.numerals===void 0?qu:Rg(ju.call(e.numerals,String)),i=e.percent===void 0?"%":e.percent+"",l=e.minus===void 0?"−":e.minus+"",c=e.nan===void 0?"NaN":e.nan+"";function d(p,f){p=vo(p);var m=p.fill,g=p.align,b=p.sign,y=p.symbol,S=p.zero,v=p.width,k=p.comma,x=p.precision,I=p.trim,N=p.type;N==="n"?(k=!0,N="g"):Vu[N]||(x===void 0&&(x=12),I=!0,N="g"),(S||m==="0"&&g==="=")&&(S=!0,m="0",g="=");var _=(f&&f.prefix!==void 0?f.prefix:"")+(y==="$"?n:y==="#"&&/[boxX]/.test(N)?"0"+N.toLowerCase():""),T=(y==="$"?s:/[%p]/.test(N)?i:"")+(f&&f.suffix!==void 0?f.suffix:""),w=Vu[N],M=/[defgprs%]/.test(N);x=x===void 0?6:/[gprs]/.test(N)?Math.max(1,Math.min(21,x)):Math.max(0,Math.min(20,x));function $(A){var P=_,V=T,D,W,H;if(N==="c")V=w(A)+V,A="";else{A=+A;var q=A<0||1/A<0;if(A=isNaN(A)?c:w(Math.abs(A),x),I&&(A=tv(A)),q&&+A==0&&b!=="+"&&(q=!1),P=(q?b==="("?b:l:b==="-"||b==="("?"":b)+P,V=(N==="s"&&!isNaN(A)&&bo!==void 0?Ku[8+bo/3]:"")+V+(q&&b==="("?")":""),M){for(D=-1,W=A.length;++D<W;)if(H=A.charCodeAt(D),48>H||H>57){V=(H===46?a+A.slice(D+1):A.slice(D))+V,A=A.slice(0,D);break}}}k&&!S&&(A=t(A,1/0));var j=P.length+A.length+V.length,z=j<v?new Array(v-j+1).join(m):"";switch(k&&S&&(A=t(z+A,z.length?v-V.length:1/0),z=""),g){case"<":A=P+A+V+z;break;case"=":A=P+z+A+V;break;case"^":A=z.slice(0,j=z.length>>1)+P+A+V+z.slice(j);break;default:A=z+P+A+V;break}return o(A)}return $.toString=function(){return p+""},$}function h(p,f){var m=Math.max(-8,Math.min(8,Math.floor(Qr(f)/3)))*3,g=Math.pow(10,-m),b=d((p=vo(p),p.type="f",p),{suffix:Ku[8+m/3]});return function(y){return b(g*y)}}return{format:d,formatPrefix:h}}var yo,Yu,Zu;sv({thousands:",",grouping:[3],currency:["$",""]});function sv(e){return yo=rv(e),Yu=yo.format,Zu=yo.formatPrefix,yo}function av(e){return Math.max(0,-Qr(Math.abs(e)))}function ov(e,t){return Math.max(0,Math.max(-8,Math.min(8,Math.floor(Qr(t)/3)))*3-Qr(Math.abs(e)))}function iv(e,t){return e=Math.abs(e),t=Math.abs(t)-e,Math.max(0,Qr(t)-Qr(e))+1}function lv(e,t,n,s){var a=vg(e,t,n),o;switch(s=vo(s??",f"),s.type){case"s":{var i=Math.max(Math.abs(e),Math.abs(t));return s.precision==null&&!isNaN(o=ov(a,i))&&(s.precision=o),Zu(s,i)}case"":case"e":case"g":case"p":case"r":{s.precision==null&&!isNaN(o=iv(a,Math.max(Math.abs(e),Math.abs(t))))&&(s.precision=o-(s.type==="e"));break}case"f":case"%":{s.precision==null&&!isNaN(o=av(a))&&(s.precision=o-(s.type==="%")*2);break}}return Yu(s)}function cv(e){var t=e.domain;return e.ticks=function(n){var s=t();return gg(s[0],s[s.length-1],n??10)},e.tickFormat=function(n,s){var a=t();return lv(a[0],a[a.length-1],n??10,s)},e.nice=function(n){n==null&&(n=10);var s=t(),a=0,o=s.length-1,i=s[a],l=s[o],c,d,h=10;for(l<i&&(d=i,i=l,l=d,d=a,a=o,o=d);h-- >0;){if(d=Il(i,l,n),d===c)return s[a]=i,s[o]=l,t(s);if(d>0)i=Math.floor(i/d)*d,l=Math.ceil(l/d)*d;else if(d<0)i=Math.ceil(i*d)/d,l=Math.floor(l*d)/d;else break;c=d}return e},e}function Xu(){var e=Xg();return e.copy=function(){return Yg(e,Xu())},$l.apply(e,arguments),cv(e)}function Rr(e,t,n=!0){const s=Xu().domain(e).range(t);return n?s.nice():s}function Ju(e,t,n=.2){return Iu().domain(e).range(t).padding(n)}const zl=[1,2,5,10,20,25,50,100];function dv(e){if(e<=0||!Number.isFinite(e))return 1;if(e<=100){let o=zl[0],i=Math.abs(e-o);for(let l=1;l<zl.length;l++){const c=zl[l],d=Math.abs(e-c);d<i&&(i=d,o=c)}return o}const t=Math.pow(10,Math.floor(Math.log10(e))),n=e/t;let s=1,a=Math.abs(n-1);for(const o of[1,2,2.5,5,10]){const i=Math.abs(n-o);i<a&&(a=i,s=o)}return Math.round(s*t)}function Qu(e){const t=e.filter(p=>typeof p=="number"&&Number.isFinite(p));if(t.length<2)return 1;const n=[...t].sort((p,f)=>p-f),s=n.length,a=(s-1)*.25,o=(s-1)*.75,i=p=>{const f=Math.floor(p),m=p-f;return f+1<s?n[f]+m*(n[f+1]-n[f]):n[f]},l=i(a),d=i(o)-l;let h;if(d>0)h=2*d/Math.cbrt(s);else{const p=Ru(n);if(p.stdDev>0)h=3.5*p.stdDev/Math.cbrt(s);else{const f=n[s-1]-n[0],m=Math.ceil(Math.log2(s)+1);h=f>0?f/m:1}}return dv(h)}function Ru(e){const t=e.filter(f=>typeof f=="number"&&Number.isFinite(f)),n=t.length;if(n===0)return{n:0,mean:0,median:0,mode:void 0,stdDev:0};const a=t.reduce((f,m)=>f+m,0)/n,o=[...t].sort((f,m)=>f-m);let i=0;n%2===1?i=o[Math.floor(n/2)]:i=(o[n/2-1]+o[n/2])/2;const l=new Map;let c=0;for(const f of t){const m=(l.get(f)||0)+1;l.set(f,m),m>c&&(c=m)}let d;if(c>1){const f=[];for(const[m,g]of l.entries())g===c&&f.push(m);f.sort((m,g)=>m-g),d=f.length===1?f[0]:f.length<=3?f.join(", "):"Multimodal"}else{const f=Gl(t);if(f.length>0){let m=f[0];for(const g of f)g.count>m.count&&(m=g);d=`${m.x0}–${m.x1}`}}const h=t.reduce((f,m)=>f+Math.pow(m-a,2),0)/n,p=Math.sqrt(h);return{n,mean:Number(a.toFixed(2)),median:Number(i.toFixed(2)),mode:d,stdDev:Number(p.toFixed(2))}}function Gl(e,t){const n=e.filter(p=>typeof p=="number"&&Number.isFinite(p));if(n.length===0)return[];const s=typeof t=="number"?{binCount:t}:t||{},a=s.min!==void 0?s.min:Math.min(...n),o=s.max!==void 0?s.max:Math.max(...n);let i;if(s.strategy==="custom")if(s.bucketSize&&s.bucketSize>0)i=s.bucketSize;else if(s.binCount&&s.binCount>0){const p=o-a;i=p>0?Math.max(1,Math.round(p/s.binCount)):1}else i=Qu(n);else if(s.bucketSize&&s.bucketSize>0)i=s.bucketSize;else if(s.binCount&&s.binCount>0&&s.strategy!=="auto"){const p=o-a;i=p>0?Math.max(1,Math.round(p/s.binCount)):1}else i=Qu(n);(i<=0||!Number.isFinite(i))&&(i=1);const l=Math.floor(a/i)*i;let c=Math.ceil(o/i)*i;c<=l&&(c=l+i);const d=[];for(let p=l;p<c;p+=i){const f=Number(p.toFixed(4)),m=Number((p+i).toFixed(4));d.push({x0:f,x1:m,count:0})}d.length===0&&d.push({x0:a,x1:a+i,count:0});const h=d.length-1;for(const p of n)for(let f=0;f<=h;f++){const m=d[f];if(f===h?p>=m.x0&&p<=m.x1:p>=m.x0&&p<m.x1){m.count++;break}}return d}function eh(e){const t=e.filter(a=>a!==null&&Number.isFinite(a));if(t.length===0)return[0,100];const[n,s]=cg(t);return[n??0,s??100]}function ra(e){if(e.length===0)return"";if(e.length===1)return`M ${e[0].x.toFixed(2)} ${e[0].y.toFixed(2)}`;let t=`M ${e[0].x.toFixed(2)} ${e[0].y.toFixed(2)}`;for(let n=0;n<e.length-1;n++){const s=e[n===0?0:n-1],a=e[n],o=e[n+1],i=e[n+2<e.length?n+2:n+1],l=a.x+(o.x-s.x)/6,c=a.y+(o.y-s.y)/6,d=o.x-(i.x-a.x)/6,h=o.y-(i.y-a.y)/6;t+=` C ${l.toFixed(2)} ${c.toFixed(2)}, ${d.toFixed(2)} ${h.toFixed(2)}, ${o.x.toFixed(2)} ${o.y.toFixed(2)}`}return t}function th(e){return e.length===0?"":e.length===1?`M ${e[0].x.toFixed(2)} ${e[0].y.toFixed(2)}`:`M ${e.map(t=>`${t.x.toFixed(2)} ${t.y.toFixed(2)}`).join(" L ")}`}function nh(e,t,n,s,a={}){if(n<=0||s<=0)return"";const o=Math.min(n/2,s/2),i=Math.max(0,Math.min(a.tl??0,o)),l=Math.max(0,Math.min(a.tr??0,o)),c=Math.max(0,Math.min(a.br??0,o)),d=Math.max(0,Math.min(a.bl??0,o));return i===0&&l===0&&c===0&&d===0?`M ${e.toFixed(2)} ${t.toFixed(2)} h ${n.toFixed(2)} v ${s.toFixed(2)} h ${(-n).toFixed(2)} Z`:[`M ${(e+i).toFixed(2)} ${t.toFixed(2)}`,`h ${(n-i-l).toFixed(2)}`,l>0?`a ${l.toFixed(2)} ${l.toFixed(2)} 0 0 1 ${l.toFixed(2)} ${l.toFixed(2)}`:"",`v ${(s-l-c).toFixed(2)}`,c>0?`a ${c.toFixed(2)} ${c.toFixed(2)} 0 0 1 ${(-c).toFixed(2)} ${c.toFixed(2)}`:"",`h ${(-(n-c-d)).toFixed(2)}`,d>0?`a ${d.toFixed(2)} ${d.toFixed(2)} 0 0 1 ${(-d).toFixed(2)} ${(-d).toFixed(2)}`:"",`v ${(-(s-d-i)).toFixed(2)}`,i>0?`a ${i.toFixed(2)} ${i.toFixed(2)} 0 0 1 ${i.toFixed(2)} ${(-i).toFixed(2)}`:"","Z"].filter(Boolean).join(" ")}function uv(e,t,n,s="asc"){if(!n||n==="sheet_order"||e.length===0){if(s==="desc"){const l=[...e].reverse(),c=t.map(d=>({...d,data:[...d.data].reverse()}));return{categories:l,series:c}}return{categories:e,series:t}}const a=e.map((l,c)=>c);if(n==="category")a.sort((l,c)=>{const d=(e[l]||"").localeCompare(e[c]||"",void 0,{numeric:!0,sensitivity:"base"});return s==="desc"?-d:d});else{const l=t.find(c=>c.name===n);a.sort((c,d)=>{let h=0,p=0;if(l)h=typeof l.data[c]=="number"&&Number.isFinite(l.data[c])?l.data[c]:0,p=typeof l.data[d]=="number"&&Number.isFinite(l.data[d])?l.data[d]:0;else for(const f of t){const m=f.data[c],g=f.data[d];typeof m=="number"&&Number.isFinite(m)&&(h+=m),typeof g=="number"&&Number.isFinite(g)&&(p+=g)}return s==="desc"?p-h:h-p})}const o=a.map(l=>e[l]),i=t.map(l=>({...l,data:a.map(c=>l.data[c])}));return{categories:o,series:i}}function Wl(e){const t=e.filter(b=>typeof b.x=="number"&&Number.isFinite(b.x)&&typeof b.y=="number"&&Number.isFinite(b.y)),n=t.length;if(n<2)return{slope:0,intercept:0,r:0,rSquared:0,n};const s=t.reduce((b,y)=>b+y.x,0),a=t.reduce((b,y)=>b+y.y,0),o=s/n,i=a/n;let l=0,c=0,d=0;for(const b of t){const y=b.x-o,S=b.y-i;l+=y*y,c+=S*S,d+=y*S}if(l===0)return{slope:0,intercept:Number(i.toFixed(4)),r:0,rSquared:0,n};const h=d/l,p=i-h*o,f=Math.sqrt(l*c),m=f>0?d/f:0,g=m*m;return{slope:Number(h.toFixed(4)),intercept:Number(p.toFixed(4)),r:Number(m.toFixed(4)),rSquared:Number(g.toFixed(4)),n}}function hv(e,t,n){const s=e.filter(p=>typeof p.x=="number"&&Number.isFinite(p.x)&&typeof p.y=="number"&&Number.isFinite(p.y)),a=s.length;if(a<=2)return[];const i=s.reduce((p,f)=>p+f.x,0)/a;let l=0,c=0;for(const p of s){const f=p.x-i;l+=f*f;const m=p.y-(t*p.x+n);c+=m*m}if(l===0)return[];const d=Math.sqrt(c/(a-2));return Array.from(new Set(s.map(p=>p.x))).sort((p,f)=>p-f).map(p=>{const f=d*Math.sqrt(1/a+Math.pow(p-i,2)/l),m=t*p+n,g=1.96*f;return{x:p,y0:Number((m-g).toFixed(4)),y1:Number((m+g).toFixed(4))}})}function rh(e,t,n=2){const s=e.filter(h=>typeof h.x=="number"&&Number.isFinite(h.x)&&typeof h.y=="number"&&Number.isFinite(h.y)),a=s.length;if(a<=n||t.length===0)return[];const i=s.reduce((h,p)=>h+p.x,0)/a;let l=0;for(const h of s){const p=h.x-i;l+=p*p}if(l===0)return[];let c=0;for(const h of s){let p=t[0].y,f=Math.abs(t[0].x-h.x);for(let g=1;g<t.length;g++){const b=Math.abs(t[g].x-h.x);b<f&&(f=b,p=t[g].y)}const m=h.y-p;c+=m*m}const d=Math.sqrt(c/Math.max(1,a-n));return t.map(h=>{const f=1.96*(d*Math.sqrt(1/a+Math.pow(h.x-i,2)/l));return{x:h.x,y0:Number((h.y-f).toFixed(4)),y1:Number((h.y+f).toFixed(4))}})}function fv(e,t=.5){const n=e.filter(i=>typeof i.x=="number"&&Number.isFinite(i.x)&&typeof i.y=="number"&&Number.isFinite(i.y)),s=n.length;if(s<2)return n.map(i=>({x:i.x,y:i.y}));const a=[...n].sort((i,l)=>i.x-l.x),o=Math.max(2,Math.floor(t*s));return a.map(i=>{const l=i.x,c=a.map(I=>Math.abs(I.x-l)),h=[...c].sort((I,N)=>I-N)[o-1]||1;let p=0,f=0,m=0;const g=c.map(I=>{if(h===0)return 1;const N=I/h;return N>=1?0:Math.pow(1-Math.pow(N,3),3)});for(let I=0;I<s;I++){const N=g[I];p+=N,f+=N*a[I].x,m+=N*a[I].y}if(p===0)return{x:l,y:i.y};const b=f/p,y=m/p;let S=0,v=0;for(let I=0;I<s;I++){const N=g[I],_=a[I].x-b,T=a[I].y-y;S+=N*_*_,v+=N*_*T}if(S===0)return{x:l,y:Number(y.toFixed(4))};const k=v/S,x=y+k*(l-b);return{x:l,y:Number(x.toFixed(4))}})}function pv(e){const t=e.filter(a=>typeof a.x=="number"&&Number.isFinite(a.x)&&typeof a.y=="number"&&Number.isFinite(a.y));if(t.length===0)return{meanX:0,meanY:0};const n=t.reduce((a,o)=>a+o.x,0),s=t.reduce((a,o)=>a+o.y,0);return{meanX:Number((n/t.length).toFixed(4)),meanY:Number((s/t.length).toFixed(4))}}function mv(e,t,n="asc"){if(!t||t==="sheet_order"||t==="sheet"||e.length===0)return n==="desc"?[...e].reverse():[...e];const s=[...e];return t==="x"||t==="horizontal"||t==="Horizontal Number"?s.sort((a,o)=>n==="desc"?o.x-a.x:a.x-o.x):t==="y"||t==="vertical"||t==="Vertical Number"?s.sort((a,o)=>n==="desc"?o.y-a.y:a.y-o.y):t==="label"||t==="dot_label"||t==="category"||t==="Point Label"?s.sort((a,o)=>{const i=(a.label||"").localeCompare(o.label||"",void 0,{numeric:!0});return n==="desc"?-i:i}):(t==="group"||t==="category_group"||t==="Group / Category")&&s.sort((a,o)=>{const i=(a.group||"").localeCompare(o.group||"",void 0,{numeric:!0});return n==="desc"?-i:i}),s}function gv(e,t=40){const n=e.filter(W=>typeof W.x=="number"&&Number.isFinite(W.x)&&typeof W.y=="number"&&Number.isFinite(W.y)),s=n.length;if(s<3){const W=Wl(n),H=[...n].map(O=>O.x).sort((O,U)=>O-U),q=H[0]??0,j=H[H.length-1]??100,z=[];for(let O=0;O<=t;O++){const U=q+O/t*(j-q);z.push({x:U,y:W.slope*U+W.intercept})}return{a:0,b:W.slope,c:W.intercept,rSquared:W.rSquared,points:z}}const a=n.reduce((W,H)=>W+H.x,0)/s,o=n.reduce((W,H)=>W+H.y,0)/s;let i=0,l=0,c=0,d=0;const h=s;let p=0,f=0,m=0;for(const W of n){const H=W.x-a,q=W.y,j=H*H;i+=j*j,l+=j*H,c+=j,d+=H,p+=q,f+=H*q,m+=j*q}const g=i*(c*h-d*d)-l*(l*h-d*c)+c*(l*d-c*c);if(Math.abs(g)<1e-12){const W=Wl(n),H=[...n].map(O=>O.x).sort((O,U)=>O-U),q=H[0]??0,j=H[H.length-1]??100,z=[];for(let O=0;O<=t;O++){const U=q+O/t*(j-q);z.push({x:U,y:W.slope*U+W.intercept})}return{a:0,b:W.slope,c:W.intercept,rSquared:W.rSquared,points:z}}const b=m*(c*h-d*d)-l*(f*h-d*p)+c*(f*d-c*p),y=i*(f*h-d*p)-m*(l*h-d*c)+c*(l*p-f*c),S=i*(c*p-f*d)-l*(l*p-m*d)+m*(l*d-c*c),v=b/g,k=y/g,x=S/g;let I=0,N=0;for(const W of n){const H=W.x-a,q=v*H*H+k*H+x;I+=(W.y-o)*(W.y-o),N+=(W.y-q)*(W.y-q)}const _=I>0?Math.max(0,1-N/I):0,T=[...n].map(W=>W.x).sort((W,H)=>W-H),w=T[0],$=T[T.length-1]-w||1,A=[];for(let W=0;W<=t;W++){const H=w+W/t*$,q=H-a,j=v*q*q+k*q+x;A.push({x:H,y:j})}const P=v,V=k-2*v*a,D=x-k*a+v*a*a;return{a:P,b:V,c:D,rSquared:_,points:A}}const sh={access:"var(--color-node-1)",equity:"var(--color-node-2)",quality:"var(--color-node-3)",resiliency:"var(--color-node-4)",governance:"var(--color-node-5)"},ah=["var(--folio-primary)","var(--folio-accent)","var(--color-node-1)","var(--color-node-4)","var(--color-node-5)","var(--color-chart-indigo)","var(--color-chart-teal)"],vv=[...ah,"var(--color-chart-cyan)","var(--color-chart-purple)","var(--color-chart-rose)","var(--color-chart-coral)","var(--color-chart-lime)","var(--color-chart-blue)","var(--color-chart-violet)"],oh=["var(--color-chart-primary-dark)","var(--color-chart-accent-dark)","var(--color-chart-blue-dark)","var(--color-chart-green-dark)","var(--color-chart-amber-dark)","var(--color-chart-indigo-dark)","var(--color-chart-teal-dark)"],ih=["var(--brand-primary-tint)","var(--brand-accent-tint)","var(--color-node-1-tint)","var(--color-node-4-tint)","var(--color-node-5-tint)","var(--color-chart-indigo-tint)","var(--color-chart-teal-tint)","var(--color-chart-cyan-tint)","var(--color-chart-purple-tint)","var(--color-chart-rose-tint)","var(--color-chart-coral-tint)","var(--color-chart-lime-tint)","var(--color-chart-blue-tint)","var(--color-chart-violet-tint)"];function Nt(e){if(!e)return"";const t=e.trim();return t==="var(--color-node-2)"?"var(--folio-primary)":t==="var(--color-node-3)"?"var(--folio-accent)":t}function es(e){const{count:t,accentColor:n,tierMode:s="bright"}=e;if(t<=0)return[];const a=[],o=new Set;if(n&&(a.push(n),o.add(Nt(n))),s==="dark"){const c=ah.filter(p=>!o.has(Nt(p))),d=Math.min(t,5);let h=0;for(;a.length<d&&h<c.length;){const p=c[h++];a.push(p),o.add(Nt(p))}if(a.length<t){const p=oh.filter(m=>!o.has(Nt(m)));let f=0;for(;a.length<t&&f<p.length;){const m=p[f++];a.push(m),o.add(Nt(m))}}if(a.length<t){const p=ih.filter(m=>!o.has(Nt(m)));let f=0;for(;a.length<t&&f<p.length;){const m=p[f++];a.push(m),o.add(Nt(m))}}return a}const i=vv.filter(c=>!o.has(Nt(c)));let l=0;for(;a.length<t&&l<i.length;){const c=i[l++];a.push(c),o.add(Nt(c))}if(a.length<t){const c=ih.filter(h=>!o.has(Nt(h)));let d=0;for(;a.length<t&&d<c.length;){const h=c[d++];a.push(h),o.add(Nt(h))}}if(a.length<t){const c=oh.filter(h=>!o.has(Nt(h)));let d=0;for(;a.length<t&&d<c.length;){const h=c[d++];a.push(h),o.add(Nt(h))}}return a}const _o={viewBoxWidth:800,viewBoxHeight:360,margins:{top:28,right:32,bottom:48,left:56},compactMargins:{top:16,right:16,bottom:36,left:44}};function bv(e={}){var d,h,p,f;const t=e.width??_o.viewBoxWidth,n=e.height??_o.viewBoxHeight,s=e.isCompact?_o.compactMargins:_o.margins;let a=((d=e.margins)==null?void 0:d.left)??s.left;typeof e.dynamicLeftMargin=="number"&&(a=Math.min(160,Math.max(s.left,e.dynamicLeftMargin)));const o={top:((h=e.margins)==null?void 0:h.top)??s.top,right:((p=e.margins)==null?void 0:p.right)??s.right,bottom:((f=e.margins)==null?void 0:f.bottom)??s.bottom,left:a},i=Math.max(0,t-o.left-o.right),l=Math.max(0,n-o.top-o.bottom),c=o.top+l;return{width:t,height:n,margin:o,innerWidth:i,innerHeight:l,baselineY:c}}function sa(e={}){var o,i,l,c;const t=(o=e.margins)==null?void 0:o.top,n=(i=e.margins)==null?void 0:i.right,s=(l=e.margins)==null?void 0:l.bottom,a=(c=e.margins)==null?void 0:c.left;return u.useMemo(()=>bv(e),[e.width,e.height,t,n,s,a,e.dynamicLeftMargin,e.isCompact])}function aa(e){const[t,n]=u.useState({visible:!1,x:0,y:0,value:null}),s=u.useCallback(o=>{let i=o.x,l=o.y;n({...o,x:i,y:l,visible:!0})},[e==null?void 0:e.clampX,e==null?void 0:e.clampY]),a=u.useCallback(()=>{n(o=>o.visible?{...o,visible:!1}:o)},[]);return{tooltipState:t,setTooltipState:n,showTooltip:s,hideTooltip:a}}const tr={tooltipContainer:"_tooltipContainer_czh6l_1",tooltipCard:"_tooltipCard_czh6l_12",title:"_title_czh6l_26",valueRow:"_valueRow_czh6l_34",value:"_value_czh6l_34",seriesBadge:"_seriesBadge_czh6l_49",seriesDot:"_seriesDot_czh6l_58"},ts=({visible:e,x:t,y:n,title:s,seriesName:a,value:o,unit:i,color:l})=>{if(!e||o===null||o===void 0)return null;const c=typeof o=="number"?Number.isInteger(o)?o.toLocaleString():o.toFixed(1):o;return r.jsx("div",{className:tr.tooltipContainer,style:{left:`${t}px`,top:`${n}px`},role:"tooltip","aria-hidden":!e,children:r.jsxs("div",{className:tr.tooltipCard,children:[s&&r.jsx("div",{className:tr.title,children:s}),r.jsx("div",{className:tr.valueRow,children:r.jsx("span",{className:tr.value,children:c})}),a&&r.jsxs("div",{className:tr.seriesBadge,children:[l&&r.jsx("span",{className:tr.seriesDot,style:{backgroundColor:l}}),r.jsx("span",{children:a})]})]})})},oa={legend:"_legend_ksjsx_1",legendItem:"_legendItem_ksjsx_11",dimmed:"_dimmed_ksjsx_39",active:"_active_ksjsx_43",swatch:"_swatch_ksjsx_49"},ns=.15,rs=({items:e,activeIndex:t=null,onHover:n,className:s=""})=>!e||e.length===0?null:r.jsx("div",{className:`${oa.legend} ${s}`.trim(),role:"list","aria-label":"Chart legend",onMouseLeave:()=>n==null?void 0:n(null),children:e.map((a,o)=>{const i=t!==null&&t===o,l=t!==null&&t!==o;return r.jsxs("button",{type:"button",role:"listitem",className:`${oa.legendItem} ${i?oa.active:""} ${l?oa.dimmed:""}`.trim(),onMouseEnter:()=>n==null?void 0:n(o),onFocus:()=>n==null?void 0:n(o),onBlur:()=>n==null?void 0:n(null),"aria-pressed":i,children:[r.jsx("span",{className:oa.swatch,style:{backgroundColor:a.color},"aria-hidden":"true"}),r.jsx("span",{children:a.name})]},a.id||o)})}),Ve={container:"_container_134xx_1",svgWrapper:"_svgWrapper_134xx_10",chartSvg:"_chartSvg_134xx_17",gridLine:"_gridLine_134xx_25",baseline:"_baseline_134xx_31",axisText:"_axisText_134xx_36",axisTextY:"_axisTextY_134xx_43",barRect:"_barRect_134xx_51",valueLabel:"_valueLabel_134xx_68",valueLabelInside:"_valueLabelInside_134xx_81",axisTextLeft:"_axisTextLeft_134xx_92",axisTitle:"_axisTitle_134xx_139"},lh=24,ch=.15,dh=({categories:e=[],series:t=[],unit:n,accentColor:s,orientation:a,barOrientation:o,stacked:i=!1,showValues:l=!1,xLabel:c,yLabel:d,onSelectDataPoint:h})=>{const p=u.useRef(null),m=(a||o||"vertical")==="horizontal",[g,b]=u.useState(null),{tooltipState:y,showTooltip:S,hideTooltip:v}=aa(),k=u.useMemo(()=>{if(!m||e.length===0)return;const O=Math.max(...e.map(Q=>String(Q).length),4),U=d?24:0;return Math.min(180,Math.max(56,O*7+16+U))},[m,e,d]),{width:x,height:I,margin:N,innerWidth:_,innerHeight:T,baselineY:w}=sa({dynamicLeftMargin:k,margins:{bottom:c?56:48,left:!m&&d?64:void 0}}),{maxValue:M,seriesList:$}=u.useMemo(()=>{const O=es({count:t.length,accentColor:s,tierMode:"bright"}),U=t.map((ae,de)=>({...ae,resolvedColor:ae.color||O[de]||"var(--folio-primary)"}));let Q=0;if(i){const ae=e.length;for(let de=0;de<ae;de++){let B=0;for(const Y of U){const ee=Y.data[de];typeof ee=="number"&&Number.isFinite(ee)&&ee>0&&(B+=ee)}B>Q&&(Q=B)}}else for(const ae of U)for(const de of ae.data)typeof de=="number"&&Number.isFinite(de)&&de>Q&&(Q=de);return{maxValue:Q>0?Q*1.1:100,seriesList:U}},[t,e,s,i]),A=u.useMemo(()=>m?Ju(e,[N.top,N.top+T],.25):Ju(e,[N.left,N.left+_],.25),[e,m,N.left,N.top,_,T]),P=u.useMemo(()=>m?Rr([0,M],[N.left,N.left+_],!0):Rr([0,M],[w,N.top],!0),[M,m,N.left,N.top,_,w]),V=u.useMemo(()=>P.ticks(5),[P]),D=Math.max($.length,1),W=A.bandwidth(),H=!i&&D>1?3:0,q=i?W:Math.max((W-(D-1)*H)/D,2),j=(O,U,Q,se,ae)=>{if(!p.current)return;const de=p.current.getBoundingClientRect(),B=O.clientX-de.left,Y=O.clientY-de.top;b(Q),S({x:B,y:Y,title:U,seriesName:Q,value:se,unit:n,color:ae})},z=()=>{b(null),v()};return r.jsxs("div",{className:Ve.container,ref:p,children:[r.jsx("div",{className:Ve.svgWrapper,children:r.jsxs("svg",{viewBox:`0 0 ${x} ${I}`,className:Ve.chartSvg,role:"graphics-document document","aria-label":"Bar Chart Visualizer",children:[m?V.map(O=>{const U=P(O);return r.jsxs("g",{children:[r.jsx("line",{x1:U,y1:N.top,x2:U,y2:w,className:Ve.gridLine}),r.jsx("text",{x:U,y:w+18,className:Ve.axisText,children:O.toLocaleString()})]},`grid-x-${O}`)}):V.map(O=>{const U=P(O);return r.jsxs("g",{children:[r.jsx("line",{x1:N.left,y1:U,x2:N.left+_,y2:U,className:Ve.gridLine}),r.jsx("text",{x:N.left-10,y:U,className:Ve.axisTextY,children:O.toLocaleString()})]},`grid-y-${O}`)}),m?r.jsx("line",{x1:N.left,y1:N.top,x2:N.left,y2:w,className:Ve.baseline}):r.jsx("line",{x1:N.left,y1:w,x2:N.left+_,y2:w,className:Ve.baseline}),c&&r.jsx("text",{x:N.left+_/2,y:I-8,textAnchor:"middle",className:Ve.axisTitle,children:c}),d&&r.jsx("text",{x:-(N.top+T/2),y:16,transform:"rotate(-90)",textAnchor:"middle",className:Ve.axisTitle,children:d}),e.map((O,U)=>{if(m){const B=A(O)??N.top;let Y=N.left,ee=0;const X=String(O),te=X.length>16?`${X.slice(0,14)}...`:X,K=i?$.map((J,Z)=>({idx:Z,val:J.data[U]})).filter(J=>typeof J.val=="number"&&Number.isFinite(J.val)&&J.val>0).map(J=>J.idx):[];return r.jsxs("g",{children:[r.jsx("text",{x:N.left-10,y:B+W/2,className:Ve.axisTextLeft,tabIndex:0,onPointerEnter:J=>{X!==te&&j(J,X,"",null,"")},onPointerLeave:z,children:te}),$.map((J,Z)=>{const ne=J.data[U]??null;if(ne==null)return null;const F=g!==null&&g!==J.name?ch:1;let L,G,le,ue;i?(le=Math.max(ne/M*_,0),L=Y,G=B,ue=q,Y+=le,ee+=ne):(le=Math.max(P(ne)-N.left,0),L=N.left,G=B+Z*(q+H),ue=q);let he="";if(i){const oe=K.length>0&&K[0]===Z,ye=K.length>0&&K[K.length-1]===Z;he=nh(L,G,le,ue,oe&&ye?{tl:3,tr:3,br:3,bl:3}:oe?{tl:3,bl:3,tr:0,br:0}:ye?{tr:3,br:3,tl:0,bl:0}:{tl:0,tr:0,br:0,bl:0})}return r.jsxs(u.Fragment,{children:[i?r.jsx("path",{d:he,fill:J.resolvedColor,style:{opacity:F},className:Ve.barRect,tabIndex:0,onPointerEnter:oe=>j(oe,O,J.name,ne,J.resolvedColor),onPointerMove:oe=>j(oe,O,J.name,ne,J.resolvedColor),onPointerLeave:z,onClick:()=>h==null?void 0:h({category:O,seriesName:J.name,value:ne}),onKeyDown:oe=>{(oe.key==="Enter"||oe.key===" ")&&(h==null||h({category:O,seriesName:J.name,value:ne}))},"aria-label":`${O}, ${J.name}: ${ne}`}):r.jsx("rect",{x:L,y:G,width:le,height:ue,rx:3,ry:3,fill:J.resolvedColor,style:{opacity:F},className:Ve.barRect,tabIndex:0,onPointerEnter:oe=>j(oe,O,J.name,ne,J.resolvedColor),onPointerMove:oe=>j(oe,O,J.name,ne,J.resolvedColor),onPointerLeave:z,onClick:()=>h==null?void 0:h({category:O,seriesName:J.name,value:ne}),onKeyDown:oe=>{(oe.key==="Enter"||oe.key===" ")&&(h==null||h({category:O,seriesName:J.name,value:ne}))},"aria-label":`${O}, ${J.name}: ${ne}`}),l&&!i&&r.jsx("text",{x:L+le+6,y:G+ue/2+4,textAnchor:"start",className:Ve.valueLabel,children:ne.toLocaleString()}),l&&i&&le>=lh&&r.jsx("text",{x:L+le/2,y:G+ue/2+3,textAnchor:"middle",className:Ve.valueLabelInside,children:ne.toLocaleString()})]},`bar-frag-h-${O}-${J.name}-${Z}`)}),l&&i&&ee>0&&r.jsx("text",{x:Y+6,y:B+W/2+4,textAnchor:"start",className:Ve.valueLabel,children:ee.toLocaleString()})]},`cat-group-h-${O}`)}const Q=A(O)??N.left;let se=w,ae=0;const de=i?$.map((B,Y)=>({idx:Y,val:B.data[U]})).filter(B=>typeof B.val=="number"&&Number.isFinite(B.val)&&B.val>0).map(B=>B.idx):[];return r.jsxs("g",{children:[$.map((B,Y)=>{const ee=B.data[U]??null;if(ee==null)return null;const te=g!==null&&g!==B.name?ch:1;let K,J,Z,ne;i?(ne=Math.max(ee/M*T,0),J=se-ne,K=Q,Z=q,se-=ne,ae+=ee):(J=P(ee),ne=Math.max(w-J,0),K=Q+Y*(q+H),Z=q);let ie="";if(i){const F=de.length>0&&de[0]===Y,L=de.length>0&&de[de.length-1]===Y;ie=nh(K,J,Z,ne,F&&L?{tl:3,tr:3,br:3,bl:3}:F?{bl:3,br:3,tl:0,tr:0}:L?{tl:3,tr:3,bl:0,br:0}:{tl:0,tr:0,br:0,bl:0})}return r.jsxs(u.Fragment,{children:[i?r.jsx("path",{d:ie,fill:B.resolvedColor,style:{opacity:te},className:Ve.barRect,tabIndex:0,onPointerEnter:F=>j(F,O,B.name,ee,B.resolvedColor),onPointerMove:F=>j(F,O,B.name,ee,B.resolvedColor),onPointerLeave:z,onClick:()=>h==null?void 0:h({category:O,seriesName:B.name,value:ee}),onKeyDown:F=>{(F.key==="Enter"||F.key===" ")&&(h==null||h({category:O,seriesName:B.name,value:ee}))},"aria-label":`${O}, ${B.name}: ${ee}`}):r.jsx("rect",{x:K,y:J,width:Z,height:ne,rx:3,ry:3,fill:B.resolvedColor,style:{opacity:te},className:Ve.barRect,tabIndex:0,onPointerEnter:F=>j(F,O,B.name,ee,B.resolvedColor),onPointerMove:F=>j(F,O,B.name,ee,B.resolvedColor),onPointerLeave:z,onClick:()=>h==null?void 0:h({category:O,seriesName:B.name,value:ee}),onKeyDown:F=>{(F.key==="Enter"||F.key===" ")&&(h==null||h({category:O,seriesName:B.name,value:ee}))},"aria-label":`${O}, ${B.name}: ${ee}`}),l&&!i&&r.jsx("text",{x:K+Z/2,y:J-6,textAnchor:"middle",className:Ve.valueLabel,children:ee.toLocaleString()}),l&&i&&ne>=lh&&r.jsx("text",{x:K+Z/2,y:J+ne/2+4,textAnchor:"middle",className:Ve.valueLabelInside,children:ee.toLocaleString()})]},`bar-frag-v-${O}-${B.name}-${Y}`)}),l&&i&&ae>0&&r.jsx("text",{x:Q+W/2,y:se-6,textAnchor:"middle",className:Ve.valueLabel,children:ae.toLocaleString()}),r.jsx("text",{x:Q+W/2,y:w+22,className:Ve.axisText,children:O})]},`cat-group-v-${O}`)})]})}),r.jsx(ts,{visible:y.visible,x:y.x,y:y.y,title:y.title,seriesName:y.seriesName,value:y.value,unit:n,color:y.color}),$.length>1&&r.jsx(rs,{items:$.map(O=>({id:O.name,name:O.name,color:O.resolvedColor})),activeIndex:g!==null?$.findIndex(O=>O.name===g):null,onHover:O=>{var U;return b(O!==null?((U=$[O])==null?void 0:U.name)??null:null)}})]})},ht={container:"_container_1rexj_1",svgWrapper:"_svgWrapper_1rexj_10",chartSvg:"_chartSvg_1rexj_17",gridLine:"_gridLine_1rexj_25",baseline:"_baseline_1rexj_31",axisText:"_axisText_1rexj_36",axisTextY:"_axisTextY_1rexj_43",splinePath:"_splinePath_1rexj_51",areaPath:"_areaPath_1rexj_59",dashedBridge:"_dashedBridge_1rexj_65",crosshairLine:"_crosshairLine_1rexj_76",pointValueLabel:"_pointValueLabel_1rexj_83",dataNode:"_dataNode_1rexj_98",dimmed:"_dimmed_1rexj_118",axisTitle:"_axisTitle_1rexj_122"},uh=({categories:e=[],series:t=[],unit:n,accentColor:s,curveInterpolation:a="smooth",showAreaFill:o=!1,markerSize:i="regular",autoScaleY:l=!1,startAtZero:c,showValues:d=!1,xLabel:h,yLabel:p,onSelectDataPoint:f})=>{const m=u.useRef(null),{tooltipState:g,showTooltip:b,hideTooltip:y}=aa(),[S,v]=u.useState(null),[k,x]=u.useState(null),{width:I,height:N,margin:_,innerWidth:T,innerHeight:w,baselineY:M}=sa({margins:{bottom:h?56:48,left:p?64:56}}),{seriesList:$,yDomainMin:A,yDomainMax:P}=u.useMemo(()=>{let U=1/0,Q=-1/0,se=!1;for(const X of t)for(const te of X.data)typeof te=="number"&&Number.isFinite(te)&&(se=!0,te<U&&(U=te),te>Q&&(Q=te));se||(U=0,Q=100);const ae=es({count:t.length,accentColor:s,tierMode:"bright"}),de=t.map((X,te)=>({...X,resolvedColor:X.color||ae[te]||"var(--folio-primary)"})),B=c!==void 0?c:!l;let Y,ee;return B?(Y=0,ee=Q>0?Q*1.1:100):U===Q?(Y=Math.max(0,U*.9),ee=Q>0?Q*1.1:100):(Y=U>0?Math.max(0,U*.9):U*1.1,ee=Q>0?Q*1.1:Q*.9),{seriesList:de,yDomainMin:Y,yDomainMax:ee}},[t,s,l,c]),V=Math.max(e.length,1),D=u.useMemo(()=>{if(V===1)return[_.left+T/2];const U=T/(V-1);return e.map((Q,se)=>_.left+se*U)},[V,T,_.left,e]),W=u.useMemo(()=>Rr([A,P],[M,_.top],!0),[A,P,M,_.top]),H=u.useMemo(()=>W.ticks(5),[W]),q=u.useMemo(()=>{switch(i){case"compact":return 3;case"prominent":return 7;case"regular":default:return 5}},[i]),j=u.useCallback((U,Q,se,ae)=>{if(!m.current)return;const de=m.current.getBoundingClientRect(),B=U.clientX-de.left,Y=U.clientY-de.top;v(se),x(Q.x),b({x:B,y:Y,title:Q.cat,seriesName:se,value:Q.val,unit:n,color:ae})},[b,n]),z=u.useCallback(()=>{y(),v(null),x(null)},[y]),O=u.useMemo(()=>{if(S===null)return null;const U=$.findIndex(Q=>Q.name===S);return U!==-1?U:null},[S,$]);return r.jsxs("div",{className:ht.container,ref:m,children:[r.jsx("div",{className:ht.svgWrapper,children:r.jsxs("svg",{viewBox:`0 0 ${I} ${N}`,className:ht.chartSvg,role:"img","aria-label":"Line Chart Visualizer",onMouseLeave:z,children:[r.jsx("defs",{children:$.map((U,Q)=>r.jsxs("linearGradient",{id:`area-grad-${Q}`,x1:"0",y1:"0",x2:"0",y2:"1",children:[r.jsx("stop",{offset:"0%",stopColor:U.resolvedColor,stopOpacity:"0.15"}),r.jsx("stop",{offset:"100%",stopColor:U.resolvedColor,stopOpacity:"0.01"})]},`grad-${Q}`))}),H.map(U=>{const Q=W(U);return r.jsxs("g",{children:[r.jsx("line",{x1:_.left,y1:Q,x2:_.left+T,y2:Q,className:ht.gridLine}),r.jsx("text",{x:_.left-10,y:Q,className:ht.axisTextY,children:U.toLocaleString()})]},`grid-${U}`)}),r.jsx("line",{x1:_.left,y1:M,x2:_.left+T,y2:M,className:ht.baseline}),h&&r.jsx("text",{x:_.left+T/2,y:N-8,textAnchor:"middle",className:ht.axisTitle,children:h}),p&&r.jsx("text",{x:-(_.top+w/2),y:16,transform:"rotate(-90)",textAnchor:"middle",className:ht.axisTitle,children:p}),k!==null&&r.jsx("line",{x1:k,y1:_.top,x2:k,y2:M,className:ht.crosshairLine}),e.map((U,Q)=>r.jsx("text",{x:D[Q],y:M+22,className:ht.axisText,children:U},`x-label-${U}`)),$.map((U,Q)=>{const se=[];if(U.data.forEach((X,te)=>{typeof X=="number"&&Number.isFinite(X)&&se.push({x:D[te],y:W(X),val:X,cat:e[te],colIndex:te})}),se.length===0)return null;const ae=[],de=[];let B=[se[0]];for(let X=1;X<se.length;X++){const te=se[X-1],K=se[X];K.colIndex===te.colIndex+1?B.push(K):(ae.push(B),de.push([te,K]),B=[K])}ae.push(B);const Y=S!==null&&S!==U.name,ee=Y?ns:1;return r.jsxs("g",{className:Y?ht.dimmed:void 0,style:{opacity:ee,transition:"opacity var(--duration-fast) var(--ease-out)"},children:[o&&ae.map((X,te)=>{if(X.length<2)return null;const J=`${a==="straight"?th(X):ra(X)} L ${X[X.length-1].x} ${M} L ${X[0].x} ${M} Z`;return r.jsx("path",{d:J,fill:`url(#area-grad-${Q})`,className:ht.areaPath},`area-${Q}-${te}`)}),ae.map((X,te)=>{if(X.length<2)return null;const K=a==="straight"?th(X):ra(X);return r.jsx("path",{d:K,stroke:U.resolvedColor,className:ht.splinePath},`path-${Q}-${te}`)}),de.map(([X,te],K)=>r.jsx("line",{x1:X.x,y1:X.y,x2:te.x,y2:te.y,stroke:U.resolvedColor,className:ht.dashedBridge},`bridge-${Q}-${K}`)),d&&se.map((X,te)=>r.jsx("text",{x:X.x,y:X.y-(q+5),className:ht.pointValueLabel,children:X.val.toLocaleString()},`val-label-${U.name}-${te}`)),se.map((X,te)=>r.jsx("circle",{cx:X.x,cy:X.y,r:q,fill:U.resolvedColor,className:ht.dataNode,tabIndex:0,onPointerEnter:K=>j(K,X,U.name,U.resolvedColor),onPointerMove:K=>j(K,X,U.name,U.resolvedColor),onClick:()=>f==null?void 0:f({category:X.cat,seriesName:U.name,value:X.val}),onKeyDown:K=>{(K.key==="Enter"||K.key===" ")&&(f==null||f({category:X.cat,seriesName:U.name,value:X.val}))},"aria-label":`${X.cat}, ${U.name}: ${X.val.toLocaleString()}`},`point-${U.name}-${te}`))]},`series-${U.name}-${Q}`)})]})}),r.jsx(ts,{visible:g.visible,x:g.x,y:g.y,title:g.title,seriesName:g.seriesName,value:g.value,unit:n,color:g.color}),$.length>1&&r.jsx(rs,{items:$.map(U=>({id:U.name,name:U.name,color:U.resolvedColor})),activeIndex:O,onHover:U=>{var Q;U==null?v(null):v(((Q=$[U])==null?void 0:Q.name)||null)}})]})},_t={container:"_container_nbga0_1",svgWrapper:"_svgWrapper_nbga0_11",chartSvg:"_chartSvg_nbga0_22",slicesGroup:"_slicesGroup_nbga0_31",segmentSlice:"_segmentSlice_nbga0_35",labelsGroup:"_labelsGroup_nbga0_52",sliceValueText:"_sliceValueText_nbga0_56",centerCalloutGroup:"_centerCalloutGroup_nbga0_70",centerTotalText:"_centerTotalText_nbga0_75",centerCategoryText:"_centerCategoryText_nbga0_86",centerMetricText:"_centerMetricText_nbga0_95"},yv=24,hh=({categories:e=[],data:t=[],accentColor:n,donutVariant:s="donut",groupOthers:a=!0,showValues:o=!1,onSelectDataPoint:i})=>{const l=u.useRef(null),c=s==="pie",{tooltipState:d,showTooltip:h,hideTooltip:p}=aa(),[f,m]=u.useState(null),{width:g,height:b}=sa(),y=g/2,S=b/2,v=120,k=c?0:78,x=(v+k)/2,I=v-k,N=2*Math.PI*x,{validTotal:_,segments:T}=u.useMemo(()=>{const A=[];let P=0;for(let U=0;U<e.length;U++){const Q=e[U]||`Category ${U+1}`,se=t[U],ae=typeof se=="number"&&Number.isFinite(se)&&se>0?se:0;A.push({category:Q,value:ae}),P+=ae}const V=P>0?P:1;let D=[];if(a&&A.length>5){const U=[...A].sort((de,B)=>B.value-de.value),Q=U.slice(0,5),se=U.slice(5),ae=se.reduce((de,B)=>de+B.value,0);D=[...Q],(ae>0||se.length>0)&&D.push({category:"Others",value:ae,isOther:!0})}else D=A;const W=D.filter(U=>!U.isOther).length,H=es({count:W,accentColor:n,tierMode:"bright"});let q=0,j=-Math.PI/2,z=0;const O=D.map((U,Q)=>{const se=U.value/V,ae=se*2*Math.PI,de=j,B=j+ae;j=B;const Y=se*N,ee=N-Y,X=-z*N;z+=se;const te=Math.round(se*100),K=U.isOther?"var(--bg-surface-muted)":H[q++]||"var(--folio-primary)",J=de+ae/2,Z=c?v*.65:x,ne=y+Z*Math.cos(J),ie=S+Z*Math.sin(J),F=se*N;let L="";if(c)if(se>=.9999)L="";else{const G=y+v*Math.cos(de),le=S+v*Math.sin(de),ue=y+v*Math.cos(B),he=S+v*Math.sin(B),oe=ae>Math.PI?1:0;L=`M ${y} ${S} L ${G.toFixed(2)} ${le.toFixed(2)} A ${v} ${v} 0 ${oe} 1 ${ue.toFixed(2)} ${he.toFixed(2)} Z`}return{id:`${U.category}-${Q}`,category:U.category,value:U.value,percentage:te,fraction:se,color:K,dashLength:Y,dashSpace:ee,dashOffset:X,wedgePath:L,labelX:ne,labelY:ie,arcLength:F,isOther:U.isOther}});return{validTotal:P,segments:O}},[e,t,a,n,N,y,S,c,v,x]),w=u.useCallback((A,P)=>{if(!l.current)return;const V=l.current.getBoundingClientRect(),D=T[P];D&&(m(P),h({x:A.clientX-V.left,y:A.clientY-V.top,title:D.category,seriesName:`${D.percentage}%`,value:D.value,color:D.color}))},[T,h]),M=u.useCallback(()=>{m(null),p()},[p]),$=f!==null?T[f]:null;return r.jsxs("div",{className:_t.container,ref:l,children:[r.jsx("div",{className:_t.svgWrapper,children:r.jsxs("svg",{viewBox:`0 0 ${g} ${b}`,className:_t.chartSvg,role:"img","aria-label":"Donut Chart Visualizer",children:[!c&&r.jsx("circle",{cx:y,cy:S,r:x,stroke:"var(--bg-surface-muted)",strokeWidth:I,fill:"none",opacity:.35}),c?r.jsx("g",{className:_t.slicesGroup,children:T.map((A,P)=>{const D=f!==null&&f!==P?ns:1;return A.fraction>=.9999?r.jsx("circle",{cx:y,cy:S,r:v,fill:A.color,opacity:D,className:_t.segmentSlice,tabIndex:0,onPointerEnter:W=>w(W,P),onPointerMove:W=>w(W,P),onPointerLeave:M,onClick:()=>i==null?void 0:i({category:A.category,value:A.value}),onKeyDown:W=>{(W.key==="Enter"||W.key===" ")&&(i==null||i({category:A.category,value:A.value}))},"aria-label":`${A.category}: ${A.value.toLocaleString()} (${A.percentage}%)`},A.id):r.jsx("path",{d:A.wedgePath,fill:A.color,opacity:D,className:_t.segmentSlice,tabIndex:0,onPointerEnter:W=>w(W,P),onPointerMove:W=>w(W,P),onPointerLeave:M,onClick:()=>i==null?void 0:i({category:A.category,value:A.value}),onKeyDown:W=>{(W.key==="Enter"||W.key===" ")&&(i==null||i({category:A.category,value:A.value}))},"aria-label":`${A.category}: ${A.value.toLocaleString()} (${A.percentage}%)`},A.id)})}):r.jsx("g",{transform:`rotate(-90 ${y} ${S})`,className:_t.slicesGroup,children:T.map((A,P)=>{const V=f!==null&&f===P,W=f!==null&&f!==P?ns:1,H=V?I+6:I;return r.jsx("circle",{cx:y,cy:S,r:x,stroke:A.color,strokeWidth:H,strokeDasharray:`${A.dashLength.toFixed(2)} ${A.dashSpace.toFixed(2)}`,strokeDashoffset:A.dashOffset.toFixed(2),fill:"none",opacity:W,className:_t.segmentSlice,tabIndex:0,onPointerEnter:q=>w(q,P),onPointerMove:q=>w(q,P),onPointerLeave:M,onClick:()=>i==null?void 0:i({category:A.category,value:A.value}),onKeyDown:q=>{(q.key==="Enter"||q.key===" ")&&(i==null||i({category:A.category,value:A.value}))},"aria-label":`${A.category}: ${A.value.toLocaleString()} (${A.percentage}%)`},A.id)})}),o&&r.jsx("g",{className:_t.labelsGroup,pointerEvents:"none",children:T.map((A,P)=>{if(A.arcLength<yv)return null;const V=f!==null&&f!==P;return r.jsxs("text",{x:A.labelX,y:A.labelY,opacity:V?ns:1,className:_t.sliceValueText,children:[A.percentage,"%"]},`label-${A.id}`)})}),!c&&r.jsx("g",{className:_t.centerCalloutGroup,pointerEvents:"none",children:$?r.jsxs(r.Fragment,{children:[r.jsx("text",{x:y,y:S-8,textAnchor:"middle",className:_t.centerCategoryText,children:$.category.length>14?`${$.category.slice(0,13)}…`:$.category}),r.jsxs("text",{x:y,y:S+16,textAnchor:"middle",className:_t.centerMetricText,children:[$.value.toLocaleString()," (",$.percentage,"%)"]})]}):r.jsx("text",{x:y,y:S,textAnchor:"middle",dominantBaseline:"central",className:_t.centerTotalText,children:_.toLocaleString()})})]})}),r.jsx(ts,{visible:d.visible,x:d.x,y:d.y,title:d.title,seriesName:d.seriesName,value:d.value,color:d.color}),r.jsx(rs,{items:T.map(A=>({id:A.id,name:`${A.category} (${A.percentage}%)`,color:A.color})),activeIndex:f,onHover:A=>{m(A),A===null&&p()}})]})},Xe={container:"_container_vc9pg_1",topBar:"_topBar_vc9pg_10",correlationChip:"_correlationChip_vc9pg_19",chipDivider:"_chipDivider_vc9pg_33",svgWrapper:"_svgWrapper_vc9pg_38",chartSvg:"_chartSvg_vc9pg_45",gridLine:"_gridLine_vc9pg_53",axisLine:"_axisLine_vc9pg_59",meanLine:"_meanLine_vc9pg_64",axisText:"_axisText_vc9pg_71",axisTextY:"_axisTextY_vc9pg_78",axisTitle:"_axisTitle_vc9pg_86",trendLine:"_trendLine_vc9pg_93",confidenceBand:"_confidenceBand_vc9pg_100",pointNode:"_pointNode_vc9pg_105"},fh=({points:e=[],xLabel:t,yLabel:n,unit:s,accentColor:a="var(--folio-primary)",curveInterpolation:o="none",loessBandwidth:i=.5,showAreaFill:l=!1,markerSize:c="regular",autoScaleY:d=!1,autoScaleX:h=!1,startAtZero:p,startAtZeroX:f,showCorrelationChip:m=!1,showReferenceGuide:g=!1,onSelectPoint:b})=>{const y=u.useRef(null),{tooltipState:S,showTooltip:v,hideTooltip:k}=aa(),[x,I]=u.useState(null),[N,_]=u.useState(null),{width:T,height:w,margin:M,innerWidth:$,innerHeight:A,baselineY:P}=sa({margins:{bottom:t?56:48,left:n?64:56}}),V=u.useMemo(()=>{switch(c){case"compact":return 3;case"prominent":return 7;case"regular":default:return 5}},[c]),D=u.useMemo(()=>e.filter(Z=>typeof Z.x=="number"&&Number.isFinite(Z.x)&&typeof Z.y=="number"&&Number.isFinite(Z.y)),[e]),{distinctGroups:W,groupColorMap:H,legendItems:q}=u.useMemo(()=>{const Z=D.map(G=>G.group).filter(Boolean),ne=Array.from(new Set(Z));if(ne.length===0)return{distinctGroups:[],groupColorMap:{},legendItems:[]};const ie=es({count:ne.length,accentColor:a,tierMode:"bright"}),F={},L=[];return ne.forEach((G,le)=>{const ue=ie[le]||a;F[G]=ue,L.push({id:`group-${le}-${G}`,name:G,color:ue})}),{distinctGroups:ne,groupColorMap:F,legendItems:L}},[D,a]),j=x!==null?W[x]:null,{xScale:z,yScale:O,xTicks:U,yTicks:Q,xDataRange:se}=u.useMemo(()=>{const Z=D.map(ke=>ke.x),ne=D.map(ke=>ke.y),[ie,F]=eh(Z),[L,G]=eh(ne),le=f!==void 0?f:!h,ue=p!==void 0?p:!d;let he;if(le)he=[0,F>0?F*1.1:100];else{const ke=F-ie||10,Ze=Math.max(0,ie-ke*.1),De=F+ke*.1;he=[Ze,De]}let oe;if(ue)oe=[0,G>0?G*1.15:100];else{const ke=G-L||10,Ze=Math.max(0,L-ke*.1),De=G+ke*.1;oe=[Ze,De]}const ye=Rr(he,[M.left,M.left+$],!0),xe=Rr(oe,[P,M.top],!0);return{xScale:ye,yScale:xe,xTicks:ye.ticks(6),yTicks:xe.ticks(5),xDataRange:[ie,F]}},[D,$,P,M.left,M.top,h,d,p,f]),ae=u.useMemo(()=>Wl(D),[D]),de=u.useMemo(()=>o!=="smooth"||D.length<2?[]:fv(D,i),[o,D,i]),B=u.useMemo(()=>{if(de.length<2)return"";const Z=de.map(ne=>({x:z(ne.x),y:O(ne.y)}));return ra(Z)},[de,z,O]),Y=u.useMemo(()=>o!=="polynomial"||D.length<2?null:gv(D,40),[o,D]),ee=u.useMemo(()=>{if(!Y||Y.points.length<2)return"";const Z=Y.points.map(ne=>({x:z(ne.x),y:O(ne.y)}));return ra(Z)},[Y,z,O]),X=u.useMemo(()=>{if(!l)return"";let Z=[];if(o==="linear"?Z=hv(D,ae.slope,ae.intercept):o==="polynomial"&&Y?Z=rh(D,Y.points,3):o==="smooth"&&de.length>0&&(Z=rh(D,de,2)),Z.length<2)return"";const ne=Z.map((F,L)=>`${L===0?"M":"L"} ${z(F.x).toFixed(2)} ${O(F.y1).toFixed(2)}`).join(" "),ie=[...Z].reverse().map(F=>`L ${z(F.x).toFixed(2)} ${O(F.y0).toFixed(2)}`).join(" ");return`${ne} ${ie} Z`},[l,o,D,ae,Y,de,z,O]),te=u.useMemo(()=>!g||D.length===0?null:pv(D),[g,D]),K=(Z,ne,ie)=>{if(!y.current)return;const F=y.current.getBoundingClientRect(),L=ne.group&&H[ne.group]||a;_(ie),v({x:Z.clientX-F.left,y:Z.clientY-F.top,title:ne.label||"Data Point",seriesName:ne.group||t||"Coordinate",value:`X: ${ne.x.toLocaleString()} · Y: ${ne.y.toLocaleString()}`,color:L,unit:s})},J=()=>{_(null),k()};return r.jsxs("div",{className:Xe.container,ref:y,children:[m&&ae.n>=2&&r.jsx("div",{className:Xe.topBar,children:r.jsxs("div",{className:Xe.correlationChip,children:[r.jsxs("span",{children:["r = ",ae.r>=0?`+${ae.r.toFixed(2)}`:ae.r.toFixed(2)]}),r.jsx("span",{className:Xe.chipDivider,children:"·"}),r.jsxs("span",{children:["R² = ",ae.rSquared.toFixed(2)]})]})}),r.jsx("div",{className:Xe.svgWrapper,children:r.jsxs("svg",{viewBox:`0 0 ${T} ${w}`,className:Xe.chartSvg,role:"img","aria-label":"Scatter Plot Visualizer",children:[X&&r.jsx("path",{d:X,fill:a,className:Xe.confidenceBand}),Q.map(Z=>{const ne=O(Z);return r.jsxs("g",{children:[r.jsx("line",{x1:M.left,y1:ne,x2:M.left+$,y2:ne,className:Xe.gridLine}),r.jsx("text",{x:M.left-10,y:ne,className:Xe.axisTextY,children:Z.toLocaleString()})]},`y-grid-${Z}`)}),U.map(Z=>{const ne=z(Z);return r.jsx("line",{x1:ne,y1:M.top,x2:ne,y2:P,className:Xe.gridLine},`x-grid-${Z}`)}),r.jsx("line",{x1:M.left,y1:P,x2:M.left+$,y2:P,className:Xe.axisLine}),r.jsx("line",{x1:M.left,y1:M.top,x2:M.left,y2:P,className:Xe.axisLine}),U.map(Z=>{const ne=z(Z);return r.jsx("text",{x:ne,y:P+20,className:Xe.axisText,children:Z.toLocaleString()},`x-tick-${Z}`)}),te&&r.jsxs("g",{"aria-label":"Mean quadrant crosshairs",children:[r.jsx("line",{x1:z(te.meanX),y1:M.top,x2:z(te.meanX),y2:P,className:Xe.meanLine}),r.jsx("line",{x1:M.left,y1:O(te.meanY),x2:M.left+$,y2:O(te.meanY),className:Xe.meanLine})]}),o==="linear"&&ae.n>=2&&(()=>{const Z=z(se[0]),ne=O(ae.slope*se[0]+ae.intercept),ie=z(se[1]),F=O(ae.slope*se[1]+ae.intercept);return r.jsx("line",{x1:Z,y1:ne,x2:ie,y2:F,stroke:a,className:Xe.trendLine})})(),o==="smooth"&&B&&r.jsx("path",{d:B,stroke:a,className:Xe.trendLine}),o==="polynomial"&&ee&&r.jsx("path",{d:ee,stroke:a,className:Xe.trendLine}),t&&r.jsx("text",{x:M.left+$/2,y:w-8,textAnchor:"middle",className:Xe.axisTitle,children:t}),n&&r.jsx("text",{x:-(M.top+A/2),y:16,transform:"rotate(-90)",textAnchor:"middle",className:Xe.axisTitle,children:n}),D.map((Z,ne)=>{const ie=z(Z.x),F=O(Z.y),L=Z.group&&H[Z.group]||a,G=N===ne,le=j!==null&&Z.group!==j;let ue=.6;le?ue=ns:G&&(ue=1);const he=G?8:V;return r.jsx("circle",{cx:ie,cy:F,r:he,fill:L,opacity:ue,className:Xe.pointNode,tabIndex:0,onPointerEnter:oe=>K(oe,Z,ne),onPointerMove:oe=>K(oe,Z,ne),onPointerLeave:J,onClick:()=>b==null?void 0:b(Z),onKeyDown:oe=>{(oe.key==="Enter"||oe.key===" ")&&(b==null||b(Z))},onFocus:()=>{_(ne),v({x:ie,y:F,title:Z.label||"Data Point",seriesName:Z.group||t||"Coordinate",value:`X: ${Z.x.toLocaleString()} · Y: ${Z.y.toLocaleString()}`,color:L,unit:s})},onBlur:()=>{_(null),k()},"aria-label":`${Z.label||"Point"}: (${Z.x}, ${Z.y})`},`point-${ne}-${Z.x}-${Z.y}`)})]})}),r.jsx(ts,{visible:S.visible,x:S.x,y:S.y,title:S.title,seriesName:S.seriesName,value:S.value,unit:S.unit,color:S.color}),q.length>0&&r.jsx(rs,{items:q,activeIndex:x,onHover:I})]})},Ie={container:"_container_qwgca_1",organicStats:"_organicStats_qwgca_10",statItem:"_statItem_qwgca_22",statLabel:"_statLabel_qwgca_28",statValue:"_statValue_qwgca_37",statDivider:"_statDivider_qwgca_42",svgWrapper:"_svgWrapper_qwgca_48",chartSvg:"_chartSvg_qwgca_55",gridLine:"_gridLine_qwgca_63",baseline:"_baseline_qwgca_69",axisText:"_axisText_qwgca_74",axisTextY:"_axisTextY_qwgca_81",barRect:"_barRect_qwgca_89",meanLine:"_meanLine_qwgca_105",meanLabel:"_meanLabel_qwgca_111",trendCurve:"_trendCurve_qwgca_118",emptyState:"_emptyState_qwgca_125",axisTitle:"_axisTitle_qwgca_135"},ph=({rawValues:e=[],series:t=[],unit:n="learners",accentColor:s="var(--folio-primary)",binStrategy:a="auto",binCount:o,bucketSize:i,histogramYMode:l="frequency",curveInterpolation:c="none",showSummaryStats:d=!1,showMedianMode:h=!1,showReferenceGuide:p=!1,sortField:f,sortDirection:m="asc",xLabel:g,yLabel:b,onSelectBin:y})=>{var J,Z,ne;const S=u.useRef(null),{tooltipState:v,showTooltip:k,hideTooltip:x}=aa(),[I,N]=u.useState(null),{width:_,height:T,margin:w,innerWidth:M,innerHeight:$,baselineY:A}=sa({margins:{bottom:g?56:48,left:b?64:56}}),P=u.useMemo(()=>t&&t.length>0?t:e&&e.length>0?[{name:"Distribution",data:e}]:[],[t,e]),V=u.useMemo(()=>es({count:P.length,accentColor:s,tierMode:"bright"}),[P.length,s]),{allNumbers:D,primaryData:W}=u.useMemo(()=>{const ie=[];let F=[];return P.forEach((L,G)=>{const le=L.data.filter(ue=>typeof ue=="number"&&Number.isFinite(ue));ie.push(...le),G===0&&(F=le)}),{allNumbers:ie,primaryData:F}},[P]),H=u.useMemo(()=>Ru(W),[W]),{processedSeries:q,templateBins:j,maxCountOrPct:z}=u.useMemo(()=>{if(D.length===0)return{processedSeries:[],templateBins:[],maxCountOrPct:10};const ie=Math.min(...D),F=Math.max(...D),L=Gl(W.length>0?W:D,{strategy:a,binCount:o,bucketSize:i,min:ie,max:F}),G=P.map((he,oe)=>{const ye=he.data.filter(De=>typeof De=="number"&&Number.isFinite(De)),xe=ye.length,ke=L.map(De=>({x0:De.x0,x1:De.x1,count:0,percentage:0})),Ze=ke.length-1;for(const De of ye)for(let je=0;je<=Ze;je++){const kt=ke[je];if(je===Ze?De>=kt.x0&&De<=kt.x1:De>=kt.x0&&De<kt.x1){kt.count++;break}}for(const De of ke)De.percentage=xe>0?De.count/xe*100:0;return{name:he.name,color:he.color||V[oe]||"var(--folio-primary)",data:ye,totalCount:xe,bins:ke}});let le=[...L];if(f==="frequency"&&G.length>0){const he=le.map((oe,ye)=>{var xe;return{bin:oe,count:((xe=G[0].bins[ye])==null?void 0:xe.count)??0,idx:ye}});he.sort((oe,ye)=>m==="desc"?ye.count-oe.count:oe.count-ye.count),le=he.map(oe=>oe.bin);for(const oe of G)oe.bins=he.map(ye=>oe.bins[ye.idx])}else if(m==="desc"&&f!=="sheet"&&f!=="sheet_order"){le.reverse();for(const he of G)he.bins.reverse()}let ue=0;for(const he of G)for(const oe of he.bins){const ye=l==="relative"?oe.percentage:oe.count;ye>ue&&(ue=ye)}return{processedSeries:G,templateBins:le,maxCountOrPct:ue>0?ue*1.15:10}},[D,W,P,a,o,i,V,f,m,l]),O=u.useMemo(()=>Rr([0,z],[A,w.top],!0),[z,A,w.top]),U=u.useMemo(()=>O.ticks(5),[O]),Q=Math.max(j.length,1),se=M/Q,ae=.75,de=Math.max(se-ae*2,2),B=u.useMemo(()=>{if(!p||j.length===0||H.n===0)return null;const ie=j[0].x0,L=j[j.length-1].x1-ie;if(L<=0)return null;const G=(H.mean-ie)/L;return G<0||G>1?null:w.left+G*M},[p,j,H,w.left,M]),{curvePath:Y,areaPath:ee}=u.useMemo(()=>{if(c!=="smooth"||q.length===0||j.length===0)return{curvePath:"",areaPath:""};const F=q[0].bins.map((he,oe)=>{const ye=w.left+oe*se+se/2,xe=l==="relative"?he.percentage:he.count,ke=O(xe);return{x:ye,y:ke}}),L=ra(F);if(!L||F.length===0)return{curvePath:"",areaPath:""};const G=F[0],le=F[F.length-1],ue=`${L} L ${le.x.toFixed(2)} ${A} L ${G.x.toFixed(2)} ${A} Z`;return{curvePath:L,areaPath:ue}},[c,q,j,w.left,se,l,O,A]),X=u.useCallback((ie,F,L,G)=>{if(!S.current)return;const le=S.current.getBoundingClientRect(),ue=`${F.percentage.toFixed(1)}%`;k({x:ie.clientX-le.left,y:ie.clientY-le.top,title:`Range: [${F.x0} – ${F.x1}]`,seriesName:L,value:F.count,unit:`${n} (${ue})`,color:G})},[k,n]),te=u.useCallback(()=>{x()},[x]);if(D.length===0)return r.jsx("div",{className:Ie.emptyState,children:"No valid numerical data available for histogram distribution."});const K=q.length>1;return r.jsxs("div",{className:Ie.container,ref:S,children:[(d||h)&&H.n>0&&r.jsxs("div",{className:Ie.organicStats,role:"region","aria-label":"Distribution Summary Statistics",children:[d&&r.jsxs(r.Fragment,{children:[r.jsxs("span",{className:Ie.statItem,children:[r.jsx("span",{className:Ie.statLabel,children:"N"}),r.jsx("span",{className:Ie.statValue,children:H.n.toLocaleString()})]}),r.jsx("span",{className:Ie.statDivider,"aria-hidden":"true",children:"·"}),r.jsxs("span",{className:Ie.statItem,children:[r.jsx("span",{className:Ie.statLabel,children:"Mean (μ)"}),r.jsx("span",{className:Ie.statValue,children:H.mean})]})]}),h&&r.jsxs(r.Fragment,{children:[d&&r.jsx("span",{className:Ie.statDivider,"aria-hidden":"true",children:"·"}),r.jsxs("span",{className:Ie.statItem,children:[r.jsx("span",{className:Ie.statLabel,children:"Median"}),r.jsx("span",{className:Ie.statValue,children:H.median})]}),H.mode!==void 0&&r.jsxs(r.Fragment,{children:[r.jsx("span",{className:Ie.statDivider,"aria-hidden":"true",children:"·"}),r.jsxs("span",{className:Ie.statItem,children:[r.jsx("span",{className:Ie.statLabel,children:"Mode"}),r.jsx("span",{className:Ie.statValue,children:H.mode})]})]})]}),d&&r.jsxs(r.Fragment,{children:[r.jsx("span",{className:Ie.statDivider,"aria-hidden":"true",children:"·"}),r.jsxs("span",{className:Ie.statItem,children:[r.jsx("span",{className:Ie.statLabel,children:"Std Dev (σ)"}),r.jsxs("span",{className:Ie.statValue,children:["±",H.stdDev]})]})]})]}),r.jsx("div",{className:Ie.svgWrapper,children:r.jsxs("svg",{viewBox:`0 0 ${_} ${T}`,className:Ie.chartSvg,role:"img","aria-label":"Histogram Frequency Distribution",children:[r.jsx("defs",{children:r.jsxs("linearGradient",{id:"hist-trend-curve-grad",x1:"0",y1:"0",x2:"0",y2:"1",children:[r.jsx("stop",{offset:"0%",stopColor:((J=q[0])==null?void 0:J.color)||s,stopOpacity:"0.25"}),r.jsx("stop",{offset:"100%",stopColor:((Z=q[0])==null?void 0:Z.color)||s,stopOpacity:"0.0"})]})}),U.map(ie=>{const F=O(ie);return r.jsxs("g",{children:[r.jsx("line",{x1:w.left,y1:F,x2:w.left+M,y2:F,className:Ie.gridLine}),r.jsx("text",{x:w.left-10,y:F,className:Ie.axisTextY,children:l==="relative"?`${ie.toFixed(0)}%`:ie.toLocaleString()})]},`y-grid-${ie}`)}),r.jsx("line",{x1:w.left,y1:A,x2:w.left+M,y2:A,className:Ie.baseline}),g&&r.jsx("text",{x:w.left+M/2,y:T-8,textAnchor:"middle",className:Ie.axisTitle,children:g}),b&&r.jsx("text",{x:-(w.top+$/2),y:16,transform:"rotate(-90)",textAnchor:"middle",className:Ie.axisTitle,children:b}),q.map((ie,F)=>{const L=F>0,G=I===ie.name,he=I!==null&&!G?ns:L?.6:.85;return r.jsx("g",{children:ie.bins.map((oe,ye)=>{const xe=w.left+ye*se+ae,ke=l==="relative"?oe.percentage:oe.count,Ze=O(ke),De=Math.max(A-Ze,0);return r.jsx("rect",{x:xe,y:Ze,width:de,height:De,rx:3,ry:3,fill:ie.color,stroke:L?ie.color:"none",strokeWidth:L?1:0,fillOpacity:he,className:Ie.barRect,tabIndex:0,onPointerEnter:je=>X(je,oe,ie.name,ie.color),onPointerMove:je=>X(je,oe,ie.name,ie.color),onPointerLeave:te,onClick:()=>y==null?void 0:y({x0:oe.x0,x1:oe.x1,count:oe.count}),onKeyDown:je=>{(je.key==="Enter"||je.key===" ")&&(y==null||y({x0:oe.x0,x1:oe.x1,count:oe.count}))},"aria-label":`${ie.name} Range [${oe.x0} – ${oe.x1}]: ${oe.count} ${n} (${oe.percentage.toFixed(1)}%)`},`rect-${F}-${ye}-${oe.x0}-${oe.x1}`)})},`series-bins-${ie.name}-${F}`)}),c==="smooth"&&Y&&r.jsxs("g",{className:Ie.trendOverlay,children:[ee&&r.jsx("path",{d:ee,fill:"url(#hist-trend-curve-grad)"}),r.jsx("path",{d:Y,className:Ie.trendCurve,stroke:((ne=q[0])==null?void 0:ne.color)||s})]}),p&&B!==null&&r.jsxs("g",{className:Ie.meanGuideGroup,children:[r.jsx("line",{x1:B,y1:w.top,x2:B,y2:A,className:Ie.meanLine}),r.jsxs("text",{x:B+4,y:w.top+10,className:Ie.meanLabel,children:["Mean: ",H.mean]})]}),j.map((ie,F)=>{const L=w.left+F*se+se/2;return r.jsxs("text",{x:L,y:A+20,className:Ie.axisText,children:[ie.x0,"–",ie.x1]},`axis-label-${F}-${ie.x0}-${ie.x1}`)})]})}),K&&r.jsx(rs,{items:q.map(ie=>({id:ie.name,name:ie.name,color:ie.color})),activeIndex:I!==null?q.findIndex(ie=>ie.name===I):null,onHover:ie=>{var F;ie==null?N(null):N(((F=q[ie])==null?void 0:F.name)||null)}}),r.jsx(ts,{visible:v.visible,x:v.x,y:v.y,title:v.title,seriesName:v.seriesName,value:v.value,unit:v.unit||n,color:v.color})]})},Mn={routerContainer:"_routerContainer_8p17x_1",emptyState:"_emptyState_8p17x_9",emptyTitle:"_emptyTitle_8p17x_25",emptySubtitle:"_emptySubtitle_8p17x_33"},mh=({dataset:e,overrideType:t,accentColor:n})=>{var c,d,h,p,f,m,g,b,y,S,v,k,x,I,N,_,T,w,M,$,A,P,V,D,W,H,q,j,z,O,U,Q,se,ae,de,B,Y,ee,X,te,K,J,Z,ne,ie,F,L,G,le,ue,he,oe,ye;const s=t||e.chartType||"bar",a=n||e.nodeId&&sh[e.nodeId]||"var(--folio-primary)",o=e.categories||[],i=e.series||[],l=e.unit||((c=e.visualConfig)==null?void 0:c.unit);if(s==="bar")return r.jsx("div",{className:Mn.routerContainer,children:r.jsx(dh,{categories:o,series:i,unit:l,accentColor:a,variant:((d=e.visualConfig)==null?void 0:d.barVariant)||"standard",targetValue:(h=e.visualConfig)==null?void 0:h.targetValue,targetLabel:(p=e.visualConfig)==null?void 0:p.targetLabel,orientation:((f=e.visualConfig)==null?void 0:f.barOrientation)||"vertical",stacked:((m=e.visualConfig)==null?void 0:m.stacked)||!1,showValues:((g=e.visualConfig)==null?void 0:g.showValues)||!1,xLabel:(b=e.visualConfig)==null?void 0:b.xLabel,yLabel:(y=e.visualConfig)==null?void 0:y.yLabel})});if(s==="line")return r.jsx("div",{className:Mn.routerContainer,children:r.jsx(uh,{categories:o,series:i,unit:l,accentColor:a,curveInterpolation:((S=e.visualConfig)==null?void 0:S.curveInterpolation)==="linear"||((v=e.visualConfig)==null?void 0:v.curveInterpolation)==="polynomial"?"straight":(k=e.visualConfig)==null?void 0:k.curveInterpolation,showAreaFill:(x=e.visualConfig)==null?void 0:x.showAreaFill,markerSize:(I=e.visualConfig)==null?void 0:I.markerSize,autoScaleY:(N=e.visualConfig)==null?void 0:N.autoScaleY,startAtZero:(_=e.visualConfig)==null?void 0:_.startAtZero,showValues:(T=e.visualConfig)==null?void 0:T.showValues,xLabel:(w=e.visualConfig)==null?void 0:w.xLabel,yLabel:(M=e.visualConfig)==null?void 0:M.yLabel})});if(s==="donut"){const xe=i.length>0?i[0].data.map(ke=>typeof ke=="number"&&Number.isFinite(ke)?ke:0):[];return r.jsx("div",{className:Mn.routerContainer,children:r.jsx(hh,{categories:o,data:xe,unit:l,accentColor:a,donutVariant:($=e.visualConfig)==null?void 0:$.donutVariant,groupOthers:(A=e.visualConfig)==null?void 0:A.groupOthers,showValues:(P=e.visualConfig)==null?void 0:P.showValues,seriesName:(V=i[0])==null?void 0:V.name})})}if(s==="scatter"){let xe=e.scatterPoints||[];if(xe.length===0&&i.length>=2){const ke=o.length,Ze=[];for(let De=0;De<ke;De++){const je=i[0].data[De],kt=i[1].data[De];typeof je=="number"&&Number.isFinite(je)&&typeof kt=="number"&&Number.isFinite(kt)&&Ze.push({x:je,y:kt,label:o[De],group:i[0].name})}xe=Ze}return r.jsx("div",{className:Mn.routerContainer,children:r.jsx(fh,{points:xe,xLabel:((D=e.visualConfig)==null?void 0:D.xLabel)||(xe===e.scatterPoints||(W=i[0])==null?void 0:W.name),yLabel:((H=e.visualConfig)==null?void 0:H.yLabel)||(xe===e.scatterPoints||(q=i[1])==null?void 0:q.name),unit:l,accentColor:a,curveInterpolation:(j=e.visualConfig)==null?void 0:j.curveInterpolation,loessBandwidth:(z=e.visualConfig)==null?void 0:z.loessBandwidth,showAreaFill:(O=e.visualConfig)==null?void 0:O.showAreaFill,markerSize:(U=e.visualConfig)==null?void 0:U.markerSize,autoScaleY:(Q=e.visualConfig)==null?void 0:Q.autoScaleY,autoScaleX:(se=e.visualConfig)==null?void 0:se.autoScaleX,startAtZero:(ae=e.visualConfig)==null?void 0:ae.startAtZero,startAtZeroX:(de=e.visualConfig)==null?void 0:de.startAtZeroX,showCorrelationChip:(B=e.visualConfig)==null?void 0:B.showCorrelationChip,showReferenceGuide:(Y=e.visualConfig)==null?void 0:Y.showReferenceGuide})})}if(s==="histogram"){const xe=((ee=e.rawValues)==null?void 0:ee.filter(ke=>typeof ke=="number"&&Number.isFinite(ke)))||(i.length>0?i[0].data.filter(ke=>typeof ke=="number"&&Number.isFinite(ke)):[]);return r.jsx("div",{className:Mn.routerContainer,children:r.jsx(ph,{rawValues:xe,series:i,binStrategy:(X=e.visualConfig)==null?void 0:X.binStrategy,binCount:(te=e.visualConfig)==null?void 0:te.binCount,bucketSize:(K=e.visualConfig)==null?void 0:K.bucketSize,histogramYMode:(J=e.visualConfig)==null?void 0:J.histogramYMode,curveInterpolation:((Z=e.visualConfig)==null?void 0:Z.curveInterpolation)==="linear"||((ne=e.visualConfig)==null?void 0:ne.curveInterpolation)==="polynomial"?"straight":(ie=e.visualConfig)==null?void 0:ie.curveInterpolation,showSummaryStats:(F=e.visualConfig)==null?void 0:F.showSummaryStats,showMedianMode:(L=e.visualConfig)==null?void 0:L.showMedianMode,showReferenceGuide:(G=e.visualConfig)==null?void 0:G.showReferenceGuide,sortBy:(le=e.visualConfig)==null?void 0:le.sortBy,sortField:(ue=e.visualConfig)==null?void 0:ue.sortField,sortDirection:(he=e.visualConfig)==null?void 0:he.sortDirection,xLabel:(oe=e.visualConfig)==null?void 0:oe.xLabel,yLabel:(ye=e.visualConfig)==null?void 0:ye.yLabel,unit:l,accentColor:a})})}return r.jsxs("div",{className:Mn.emptyState,children:[r.jsx("div",{className:Mn.emptyTitle,children:"Data Distribution Pending"}),r.jsx("div",{className:Mn.emptySubtitle,children:"The designated visualizer for this indicator is being formatted."})]})},Mt={wireframeWrapper:"_wireframeWrapper_uk8sj_8",wireframeSvg:"_wireframeSvg_uk8sj_23",axisLine:"_axisLine_uk8sj_30",gridLine:"_gridLine_uk8sj_37",ghostBar:"_ghostBar_uk8sj_44",ghostBarAccent:"_ghostBarAccent_uk8sj_52"},Hl=u.memo(({className:e})=>r.jsx("div",{className:`${Mt.wireframeWrapper} ${e||""}`.trim(),"aria-hidden":"true",tabIndex:-1,children:r.jsxs("svg",{className:Mt.wireframeSvg,viewBox:"0 0 540 220",preserveAspectRatio:"none",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[r.jsx("line",{x1:"45",y1:"40",x2:"515",y2:"40",className:Mt.gridLine}),r.jsx("line",{x1:"45",y1:"90",x2:"515",y2:"90",className:Mt.gridLine}),r.jsx("line",{x1:"45",y1:"140",x2:"515",y2:"140",className:Mt.gridLine}),r.jsx("line",{x1:"45",y1:"20",x2:"45",y2:"190",className:Mt.axisLine}),r.jsx("line",{x1:"45",y1:"190",x2:"515",y2:"190",className:Mt.axisLine}),r.jsx("rect",{x:"75",y:"100",width:"48",height:"90",rx:"4",className:Mt.ghostBar}),r.jsx("rect",{x:"165",y:"60",width:"48",height:"130",rx:"4",className:Mt.ghostBarAccent}),r.jsx("rect",{x:"255",y:"120",width:"48",height:"70",rx:"4",className:Mt.ghostBar}),r.jsx("rect",{x:"345",y:"45",width:"48",height:"145",rx:"4",className:Mt.ghostBarAccent}),r.jsx("rect",{x:"435",y:"85",width:"48",height:"105",rx:"4",className:Mt.ghostBar})]})}));Hl.displayName="ChartGhostWireframe";const wt={container:"_container_1md1z_11",publicNoticeWrapper:"_publicNoticeWrapper_1md1z_28",logoWrapper:"_logoWrapper_1md1z_47",kicker:"_kicker_1md1z_55",title:"_title_1md1z_64",description:"_description_1md1z_73",diagnosticPanel:"_diagnosticPanel_1md1z_84",diagBadge:"_diagBadge_1md1z_103",diagBadgeUnlinked:"_diagBadgeUnlinked_1md1z_118",diagBadgeConnection:"_diagBadgeConnection_1md1z_124",diagBadgeDataFormat:"_diagBadgeDataFormat_1md1z_130",diagTitle:"_diagTitle_1md1z_136",diagHint:"_diagHint_1md1z_145",actionRow:"_actionRow_1md1z_153"},gh=({chartId:e,nodeTitle:t,category:n="unlinked",errorMessage:s,hasSheetUrl:a=!1,onEdit:o,className:i,headline:l,description:c})=>{const{isDevMode:d,isDesktop:h}=Oe(),p=d&&h,f=u.useMemo(()=>n&&n!=="none"?n:a?s?"connection_error":"data_format":"unlinked",[n,a,s]),m=u.useMemo(()=>{switch(f){case"connection_error":return{badgeClass:wt.diagBadgeConnection,badgeLabel:"Connection Issue",title:"Unable to Access Google Sheet",hint:s||'Verify that the Google Sheet sharing permission is set to "Anyone with the link can view" and the sheet is online.'};case"data_format":return{badgeClass:wt.diagBadgeDataFormat,badgeLabel:"Data Range Issue",title:"Empty or Unrecognized Data Range",hint:s||"The selected tab or range contains no valid rows or numeric data. Check the tab name and cell coordinates."};case"unlinked":default:return{badgeClass:wt.diagBadgeUnlinked,badgeLabel:"Unlinked Source",title:"No Google Sheet Linked",hint:"Link an official Google Sheet to automatically ingest and publish validated indicator metrics."}}},[f,s]);return r.jsxs("div",{className:`${wt.container} ${i||""}`.trim(),role:"region","aria-label":"Indicator Data Notice",tabIndex:-1,children:[r.jsx(Hl,{}),p?r.jsxs("div",{className:wt.diagnosticPanel,children:[r.jsx("span",{className:`${wt.diagBadge} ${m.badgeClass}`,children:m.badgeLabel}),r.jsx("h4",{className:wt.diagTitle,children:m.title}),r.jsx("p",{className:wt.diagHint,children:m.hint}),o&&r.jsx("div",{className:wt.actionRow,children:r.jsx(me,{variant:"admin",size:"xs",onClick:o,"aria-label":e?`Edit chart ${e}`:"Edit chart",children:"✎ Edit"})})]}):r.jsxs("div",{className:wt.publicNoticeWrapper,children:[r.jsx("div",{className:wt.logoWrapper,children:r.jsx(_s,{sides:8,waviness:.15,radius:18,fill:"var(--folio-primary)"})}),r.jsx("div",{className:wt.kicker,children:t?`${t} Indicator`:"Official Indicator"}),r.jsx("h3",{className:wt.title,children:l||"Indicator Data Pending"}),r.jsx("p",{className:wt.description,children:c||"The designated coordinator is finalizing official validation and records encoding for this indicator. Data receipts will appear once published."})]})]})},Be={backdrop:"_backdrop_1k8iw_12",backdropOpen:"_backdropOpen_1k8iw_27",drawer:"_drawer_1k8iw_32",positionRight:"_positionRight_1k8iw_49",positionLeft:"_positionLeft_1k8iw_54",drawerOpen:"_drawerOpen_1k8iw_59",size_sm:"_size_sm_1k8iw_64",size_md:"_size_md_1k8iw_68",size_lg:"_size_lg_1k8iw_72",size_xl:"_size_xl_1k8iw_76",size_full:"_size_full_1k8iw_80",companionViewport:"_companionViewport_1k8iw_94",companionLeft:"_companionLeft_1k8iw_108",companionRight:"_companionRight_1k8iw_114",header:"_header_1k8iw_127",headerTitleWrapper:"_headerTitleWrapper_1k8iw_138",kicker:"_kicker_1k8iw_145",title:"_title_1k8iw_154",headerControls:"_headerControls_1k8iw_167",closeButton:"_closeButton_1k8iw_174",tabsContainer:"_tabsContainer_1k8iw_209",tabList:"_tabList_1k8iw_216",tabButton:"_tabButton_1k8iw_224",tabActive:"_tabActive_1k8iw_263",tabCompleted:"_tabCompleted_1k8iw_269",tabBadge:"_tabBadge_1k8iw_279",tabLabel:"_tabLabel_1k8iw_304",body:"_body_1k8iw_311",footer:"_footer_1k8iw_322",footerLeft:"_footerLeft_1k8iw_334",footerRight:"_footerRight_1k8iw_340"},Vl=({isOpen:e,onClose:t,title:n,kicker:s,headerActions:a,showCloseButton:o=!0,closeOnOutsideClick:i=!0,closeOnBackdropClick:l=!0,position:c="right",size:d="md",tabs:h,activeTab:p,onTabChange:f,tabsContent:m,footer:g,footerLeft:b,footerRight:y,children:S,className:v,bodyClassName:k,ariaLabel:x,ariaLabelledBy:I="canonical-drawer-title",ariaDescribedBy:N,onConfirm:_,enableCtrlEnter:T=!0,companionContent:w})=>{const[M,$]=u.useState(!1),A=u.useRef(null);if(u.useEffect(()=>{$(!0)},[]),u.useEffect(()=>{if(e)return Ki(),()=>{Yi()}},[e]),u.useEffect(()=>{if(!e)return;const z=A.current;return z&&Zi(z),()=>{z&&Xi(z)}},[e]),u.useEffect(()=>{if(!e)return;const z=O=>{const U=A.current&&(A.current.contains(document.activeElement)||Ji(A.current));if(O.key==="Escape"&&U){O.preventDefault(),t();return}if(T&&Qi(O)&&U){if(O.preventDefault(),O.stopPropagation(),_){_();return}if(A.current){const Q=Ri(A.current);Q&&el(Q)}return}};return window.addEventListener("keydown",z),()=>window.removeEventListener("keydown",z)},[e,t,T,_]),!M||!e&&typeof document<"u")return null;const P=i&&l,V=z=>{!P&&z.target===z.currentTarget&&z.preventDefault()},D=z=>{P&&z.target===z.currentTarget&&t()},W=!!(g||b||y),H=c==="left"?Be.positionLeft:Be.positionRight,q=Be[`size_${d}`]||Be.size_md,j=r.jsxs("div",{className:`${Be.backdrop} ${e?Be.backdropOpen:""}`,onMouseDown:V,onClick:D,role:"presentation",children:[w&&r.jsx("div",{className:`${Be.companionViewport} ${c==="left"?Be.companionRight:Be.companionLeft}`,onClick:z=>z.stopPropagation(),onMouseDown:z=>z.stopPropagation(),children:w}),r.jsxs("aside",{ref:A,className:`${Be.drawer} ${H} ${q} ${e?Be.drawerOpen:""} ${v||""}`,role:"dialog","aria-modal":"true","aria-label":x,"aria-labelledby":n?I:void 0,"aria-describedby":N,children:[(n||s||o||a)&&r.jsxs("div",{className:Be.header,children:[r.jsxs("div",{className:Be.headerTitleWrapper,children:[s&&r.jsx("span",{className:Be.kicker,children:s}),n&&r.jsx("h2",{id:I,className:Be.title,children:n})]}),r.jsxs("div",{className:Be.headerControls,children:[a,o&&r.jsx("button",{type:"button",className:Be.closeButton,onClick:t,"aria-label":"Close drawer",children:"✕"})]})]}),m?r.jsx("div",{className:Be.tabsContainer,children:m}):h&&h.length>0?r.jsx("nav",{className:Be.tabsContainer,role:"tablist","aria-label":"Drawer sections",children:r.jsx("div",{className:Be.tabList,children:h.map(z=>{const O=p===z.id;return r.jsxs("button",{type:"button",role:"tab",id:`drawer-tab-${z.id}`,"aria-selected":O,"aria-controls":`drawer-panel-${z.id}`,className:`${Be.tabButton} ${O?Be.tabActive:""} ${z.completed?Be.tabCompleted:""}`,onClick:()=>{!z.disabled&&f&&f(z.id)},disabled:z.disabled,children:[z.badge!==void 0&&z.badge!==null&&r.jsx("span",{className:Be.tabBadge,children:z.badge}),r.jsx("span",{className:Be.tabLabel,children:z.label})]},String(z.id))})})}):null,r.jsx("div",{className:`${Be.body} ${k||""}`,children:S}),W&&r.jsx("footer",{className:Be.footer,children:g||r.jsxs(r.Fragment,{children:[r.jsx("div",{className:Be.footerLeft,children:b}),r.jsx("div",{className:Be.footerRight,children:y})]})})]})]});return bs.createPortal(j,document.body)},Dn={accordionSection:"_accordionSection_1dyhk_6",summary:"_summary_1dyhk_12",summaryLeft:"_summaryLeft_1dyhk_35",chevron:"_chevron_1dyhk_41",title:"_title_1dyhk_57",badgeWrapper:"_badgeWrapper_1dyhk_76",caption:"_caption_1dyhk_81",content:"_content_1dyhk_89"},Dt=({id:e,name:t,title:n,defaultOpen:s=!1,isOpen:a,onToggle:o,badge:i,caption:l,children:c,className:d=""})=>{const h=u.useId(),p=e||h,[f,m]=u.useState(s),g=typeof a=="boolean",b=g?a:f;u.useEffect(()=>{if(!t||g)return;const S=v=>{var x,I;const k=v;((x=k.detail)==null?void 0:x.name)===t&&((I=k.detail)==null?void 0:I.id)!==p&&m(!1)};return window.addEventListener("accordion-open",S),()=>{window.removeEventListener("accordion-open",S)}},[t,p,g]);const y=S=>{const v=S.currentTarget.open;g||m(v),t&&v&&window.dispatchEvent(new CustomEvent("accordion-open",{detail:{name:t,id:p}})),o==null||o(v)};return r.jsxs("details",{id:p,name:t,className:`${Dn.accordionSection} ${d}`.trim(),open:b,onToggle:y,children:[r.jsxs("summary",{className:Dn.summary,children:[r.jsxs("div",{className:Dn.summaryLeft,children:[r.jsx("span",{className:Dn.chevron,"aria-hidden":"true",children:r.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:r.jsx("polyline",{points:"9 18 15 12 9 6"})})}),r.jsx("span",{className:Dn.title,children:n})]}),i&&r.jsx("div",{className:Dn.badgeWrapper,children:i})]}),l&&r.jsx("p",{className:Dn.caption,children:l}),r.jsx("div",{className:Dn.content,children:c})]})},ia={tier:"_tier_1t31h_1",tierHeader:"_tierHeader_1t31h_8",tierTitle:"_tierTitle_1t31h_14",tierSubtitle:"_tierSubtitle_1t31h_23",tierContent:"_tierContent_1t31h_30"},_v=({title:e,subtitle:t,children:n,className:s=""})=>r.jsxs("section",{className:`${ia.tier} ${s}`.trim(),"aria-label":e,children:[r.jsxs("div",{className:ia.tierHeader,children:[r.jsx("h3",{className:ia.tierTitle,children:e}),t&&r.jsx("p",{className:ia.tierSubtitle,children:t})]}),r.jsx("div",{className:ia.tierContent,children:n})]}),wv=e=>r.jsx(me,{variant:"revolving-outline",...e});function ft(e){return e==null?"":String(e).trim().replace(/\s+/g," ")}function ql(e){if(e==null)return null;const t=String(e).trim();if(t===""||t==="-"||t.startsWith("#"))return null;const n=t.replace(/[₱$,%]/g,"").trim(),s=Number(n);return Number.isFinite(s)?s:null}function vh(e){const t=e.trim().toLowerCase();return t.startsWith("total")||t.startsWith("grand total")||t.startsWith("average")||t.startsWith("mean")}function bh(e){let t=0;const n=e.trim().toUpperCase();for(let s=0;s<n.length;s++)t=t*26+(n.charCodeAt(s)-64);return t-1}function St(e){let t=e+1,n="";for(;t>0;){const s=(t-1)%26;n=String.fromCharCode(65+s)+n,t=Math.floor((t-s)/26)}return n}function la(e){if(!e||typeof e!="string")return null;const n=e.trim().match(/^(?:(?:'([^']+)'|([A-Za-z0-9_\s-]+))!)?([A-Za-z]+)(\d*):([A-Za-z]+)(\d*)$/);if(!n)return null;const[,s,a,o,i,l,c]=n,d=s||a?ft(s||a):void 0,h=bh(o),p=i?parseInt(i,10)-1:0,f=bh(l),m=c?parseInt(c,10)-1:void 0;return h<0||p<0||f<0||m!==void 0&&m<0||h>f||m!==void 0&&p>m?null:{...d?{sheetName:d}:{},startCol:h,startRow:p,endCol:f,...m!==void 0?{endRow:m}:{}}}function Sv(e){if(!e||e.length===0)return null;let t=-1,n=-1,s=-1,a=-1;for(let l=0;l<e.length;l++){const c=e[l];if(c)for(let d=0;d<c.length;d++){const h=c[d];h!=null&&String(h).trim()!==""&&((t===-1||l<t)&&(t=l),(n===-1||l>n)&&(n=l),(s===-1||d<s)&&(s=d),(a===-1||d>a)&&(a=d))}}if(t===-1||s===-1)return null;const o=`${St(s)}${t+1}`,i=`${St(a)}${n+1}`;return`${o}:${i}`}function yh(e,t,n,s){const a=[];n&&a.push([`# Title: ${ft(n)}${s?` (${ft(s)})`:""}`]);const o=["Category",...t.map(i=>ft(i.name))];a.push(o);for(let i=0;i<e.length;i++){const l=[ft(e[i])];for(const c of t){const d=c.data[i];l.push(d!=null&&Number.isFinite(d)?String(d):"")}a.push(l)}return a.map(i=>i.map(l=>l.includes(",")||l.includes('"')||l.includes(`
35
- `)?`"${l.replace(/"/g,'""')}"`:l).join(",")).join(`
36
- `)}function kv(e=new Date){const t=c=>String(c).padStart(2,"0"),n=e.getFullYear(),s=t(e.getMonth()+1),a=t(e.getDate()),o=t(e.getHours()),i=t(e.getMinutes()),l=t(e.getSeconds());return`${n}-${s}-${a}_${o}${i}${l}`}function jl(e){return!e||typeof e!="string"?"":e.trim().replace(/[/\\:]+/g,"-").replace(/[*?"<>|]+/g,"").replace(/\s+/g," ").trim().replace(/^[.-]+|[.-]+$/g,"")}function Cv(e){const t=jl(e.title||""),n=jl(e.sheetName||""),s=jl(e.chartId||""),a=t||n||s||"chart-data",o=kv(e.date||new Date);return`${a}_${o}.csv`}const Re={formGroup:"_formGroup_kpi19_1",labelRow:"_labelRow_kpi19_8",label:"_label_kpi19_8",selectWrapper:"_selectWrapper_kpi19_23",hiddenSelect:"_hiddenSelect_kpi19_29",trigger:"_trigger_kpi19_43",triggerOpen:"_triggerOpen_kpi19_70",triggerValue:"_triggerValue_kpi19_75",triggerLabel:"_triggerLabel_kpi19_85",chevron:"_chevron_kpi19_90",chevronOpen:"_chevronOpen_kpi19_96",dropdown:"_dropdown_kpi19_101",option:"_option_kpi19_119",optionSelected:"_optionSelected_kpi19_137",checkIcon:"_checkIcon_kpi19_142",optionText:"_optionText_kpi19_154",optionLabel:"_optionLabel_kpi19_164",colCode:"_colCode_kpi19_170",hint:"_hint_kpi19_179"},nr=({id:e,label:t,value:n,onChange:s,columns:a,hint:o,className:i=""})=>{const[l,c]=u.useState(!1),d=u.useRef(null),h=u.useRef(null),p=u.useId(),f=a.find(g=>g.index===n);u.useEffect(()=>{if(!l)return;const g=b=>{d.current&&!d.current.contains(b.target)&&c(!1)};return document.addEventListener("mousedown",g),document.addEventListener("touchstart",g),()=>{document.removeEventListener("mousedown",g),document.removeEventListener("touchstart",g)}},[l]);const m=g=>{if(g.key==="Escape"){c(!1);return}if(g.key==="Enter"||g.key===" "){g.preventDefault(),c(b=>!b);return}if(g.key==="ArrowDown"||g.key==="ArrowUp"){if(g.preventDefault(),!l){c(!0);return}const b=a.findIndex(S=>S.index===n),y=g.key==="ArrowDown"?Math.min(a.length-1,b+1):Math.max(0,b-1);a[y]&&s(a[y].index)}};return r.jsxs("div",{className:`${Re.formGroup} ${i}`.trim(),ref:d,children:[r.jsx("div",{className:Re.labelRow,children:r.jsx("label",{htmlFor:e,className:Re.label,onClick:()=>c(g=>!g),children:t})}),r.jsxs("div",{className:Re.selectWrapper,children:[r.jsx("select",{id:`${e}-native`,className:Re.hiddenSelect,value:n,onChange:g=>s(Number(g.target.value)),tabIndex:-1,"aria-hidden":"true",children:a.map(g=>{const b=g.index>=0?` [${St(g.index)}]`:"";return r.jsxs("option",{value:g.index,children:[g.label,b]},g.index)})}),r.jsxs("button",{type:"button",id:e,className:`${Re.trigger} ${l?Re.triggerOpen:""}`,"aria-haspopup":"listbox","aria-expanded":l,"aria-controls":p,onClick:()=>c(g=>!g),onKeyDown:m,children:[r.jsxs("div",{className:Re.triggerValue,children:[r.jsx("span",{className:Re.triggerLabel,children:(f==null?void 0:f.label)||"Select column..."}),f&&f.index>=0&&r.jsxs("span",{className:Re.colCode,children:["[",St(f.index),"]"]})]}),r.jsx("svg",{className:`${Re.chevron} ${l?Re.chevronOpen:""}`,width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true",children:r.jsx("path",{d:"M2.5 4.5L6 8L9.5 4.5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]}),l&&r.jsx("ul",{id:p,className:Re.dropdown,role:"listbox",ref:h,"aria-label":t,children:a.map(g=>{const b=g.index===n;return r.jsxs("li",{role:"option","aria-selected":b,className:`${Re.option} ${b?Re.optionSelected:""}`,onClick:()=>{s(g.index),c(!1)},children:[r.jsx("span",{className:Re.checkIcon,"aria-hidden":"true",children:b?"✓":""}),r.jsxs("span",{className:Re.optionText,children:[r.jsx("span",{className:Re.optionLabel,children:g.label}),g.index>=0&&r.jsxs("span",{className:Re.colCode,children:["[",St(g.index),"]"]})]})]},g.index)})})]}),o&&r.jsx("span",{className:Re.hint,children:o})]})},Kl={badge:"_badge_14e5p_1",text:"_text_14e5p_16",number:"_number_14e5p_22"},xv=({type:e,className:t=""})=>{const n=e==="number",s=n?"123":"TEXT",a=n?Kl.number:Kl.text;return r.jsx("span",{className:`${Kl.badge} ${a} ${t}`.trim(),title:n?"Numeric metric column":"Categorical text dimension","aria-label":n?"Numeric data":"Text data",children:s})},pn={container:"_container_a3fri_8",row:"_row_a3fri_16",rowDragging:"_rowDragging_a3fri_36",rowDragOver:"_rowDragOver_a3fri_42",dragHandle:"_dragHandle_a3fri_47",content:"_content_a3fri_77",microControls:"_microControls_a3fri_89",microBtn:"_microBtn_a3fri_98"};function _h({items:e,keyExtractor:t,onReorder:n,renderItem:s,showMicroArrows:a=!0,className:o="",ariaLabel:i="Draggable list"}){const[l,c]=u.useState(null),[d,h]=u.useState(null),p=u.useCallback((y,S)=>{c(S),y.dataTransfer.effectAllowed="move",y.dataTransfer.setData("text/plain",String(S))},[]),f=u.useCallback((y,S)=>{y.preventDefault(),y.dataTransfer.dropEffect="move",d!==S&&h(S)},[d]),m=u.useCallback((y,S)=>{if(y.preventDefault(),l===null||l===S){c(null),h(null);return}const v=[...e],[k]=v.splice(l,1);v.splice(S,0,k),n(v),c(null),h(null)},[l,e,n]),g=u.useCallback(()=>{c(null),h(null)},[]),b=u.useCallback((y,S)=>{const v=S==="up"?y-1:y+1;if(v<0||v>=e.length)return;const k=[...e],x=k[y];k[y]=k[v],k[v]=x,n(k)},[e,n]);return r.jsx("div",{className:`${pn.container} ${o}`.trim(),role:"list","aria-label":i,children:e.map((y,S)=>{const v=t(y,S),k=l===S,x=d===S&&l!==S,I=S>0,N=S<e.length-1,_={index:S,isDragging:k,isDragOver:x,moveUp:()=>b(S,"up"),moveDown:()=>b(S,"down"),canMoveUp:I,canMoveDown:N};return r.jsxs("div",{className:`${pn.row} ${k?pn.rowDragging:""} ${x?pn.rowDragOver:""}`,draggable:!0,onDragStart:T=>p(T,S),onDragOver:T=>f(T,S),onDrop:T=>m(T,S),onDragEnd:g,role:"listitem",tabIndex:0,children:[r.jsx("span",{className:pn.dragHandle,title:"Drag to reorder","aria-label":"Drag handle",children:"⋮⋮"}),r.jsx("div",{className:pn.content,children:s(y,_)}),a&&r.jsxs("div",{className:pn.microControls,children:[r.jsx("button",{type:"button",className:pn.microBtn,disabled:!I,onClick:T=>{T.stopPropagation(),b(S,"up")},"aria-label":"Move item up",title:"Move up",children:"↑"}),r.jsx("button",{type:"button",className:pn.microBtn,disabled:!N,onClick:T=>{T.stopPropagation(),b(S,"down")},"aria-label":"Move item down",title:"Move down",children:"↓"})]})]},v)})})}const rr={toolbar:"_toolbar_sg8wo_1",titleRow:"_titleRow_sg8wo_8",title:"_title_sg8wo_8",countBadge:"_countBadge_sg8wo_21",actions:"_actions_sg8wo_30",actionBtn:"_actionBtn_sg8wo_36"},Nv=({title:e="Numbers to Show",selectedCount:t,totalCount:n,onSelectAll:s,onClear:a,className:o=""})=>r.jsxs("div",{className:`${rr.toolbar} ${o}`.trim(),children:[r.jsxs("div",{className:rr.titleRow,children:[r.jsx("span",{className:rr.title,children:e}),t!==void 0&&n!==void 0&&r.jsxs("span",{className:rr.countBadge,title:`${t} of ${n} series selected`,children:[t,"/",n]})]}),r.jsxs("div",{className:rr.actions,children:[r.jsx("button",{type:"button",className:rr.actionBtn,onClick:s,title:"Select all columns with numbers",children:"Select All Numbers"}),r.jsx("button",{type:"button",className:rr.actionBtn,onClick:a,title:"Deselect all series",children:"Clear All"})]})]}),Ht={container:"_container_15sk1_1",header:"_header_15sk1_8",label:"_label_15sk1_14",valueText:"_valueText_15sk1_22",trackWrapper:"_trackWrapper_15sk1_29",rangeInput:"_rangeInput_15sk1_37",tiersRow:"_tiersRow_15sk1_113",tierBtn:"_tierBtn_15sk1_120",tierBtnActive:"_tierBtnActive_15sk1_149",tierNotch:"_tierNotch_15sk1_154",tierNotchActive:"_tierNotchActive_15sk1_161"},wh=({id:e,label:t,value:n,min:s=.2,max:a=.8,step:o=.05,tiers:i=[],badgeFormatter:l,onChange:c,disabled:d=!1})=>{const h=i.reduce((f,m)=>f?Math.abs(m.value-n)<Math.abs(f.value-n)?m:f:m,null),p=l?l(n):`${Math.round(n*100)}%`;return r.jsxs("div",{className:Ht.container,children:[r.jsxs("div",{className:Ht.header,children:[r.jsx("label",{htmlFor:e,className:Ht.label,children:t}),r.jsx("span",{className:Ht.valueText,"aria-live":"polite",children:p})]}),r.jsx("div",{className:Ht.trackWrapper,children:r.jsx("input",{id:e,type:"range",min:s,max:a,step:o,value:n,disabled:d,onChange:f=>c(parseFloat(f.target.value)),className:Ht.rangeInput,"aria-valuemin":s,"aria-valuemax":a,"aria-valuenow":n,"aria-valuetext":p})}),i.length>0&&r.jsx("div",{className:Ht.tiersRow,children:i.map(f=>{const m=h&&Math.abs(h.value-f.value)<.01;return r.jsxs("button",{type:"button",onClick:()=>c(f.value),disabled:d,className:`${Ht.tierBtn} ${m?Ht.tierBtnActive:""}`,title:`Snap to ${f.label} (${Math.round(f.value*100)}%)`,children:[r.jsx("span",{className:`${Ht.tierNotch} ${m?Ht.tierNotchActive:""}`}),r.jsx("span",{children:f.label})]},`tier-${f.value}`)})})]})},wo={container:"_container_1whmk_1",label:"_label_1whmk_7",checkbox:"_checkbox_1whmk_18",hint:"_hint_1whmk_54"},So=({id:e="cfg-show-values",checked:t,onChange:n,label:s="Show values on bars",hint:a,className:o=""})=>r.jsxs("div",{className:`${wo.container} ${o}`.trim(),children:[r.jsxs("label",{htmlFor:e,className:wo.label,children:[r.jsx("input",{id:e,type:"checkbox",className:wo.checkbox,checked:t,onChange:i=>n(i.target.checked)}),r.jsx("span",{children:s})]}),a&&r.jsx("span",{className:wo.hint,children:a})]}),ko=e=>(e||Ae())+"_chart_source_",Yl=ko(),Sh=e=>(e||Ae())+"_chart_sources_manifest",ss=Sh(),Co="engine-chart-source-change";function xo(e,t){if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(Co,{detail:{chartId:e,config:t}}))}catch{}}const as=new Map;function No(e){try{return typeof window<"u"&&window.localStorage?window.localStorage.getItem(e):null}catch{return null}}function kh(e,t){try{return typeof window<"u"&&window.localStorage?(window.localStorage.setItem(e,t),!0):!1}catch{return!1}}function Zl(e){try{typeof window<"u"&&window.localStorage&&window.localStorage.removeItem(e)}catch{}}function Xl(e){const t=e.visual_config??{},n=t.__cached_dataset,s={...t};return delete s.__cached_dataset,{chartId:e.chart_id,nodeId:e.node_id||"access",sheetUrl:e.sheet_url,tabName:e.tab_name??void 0,sheetGid:e.sheet_gid??void 0,range:e.range??void 0,defaultType:e.default_type||"bar",titleOverride:e.title_override??void 0,subtitleOverride:e.subtitle_override??void 0,unitOverride:e.unit_override??void 0,visualConfig:s,cachedDataset:e.cached_dataset??n??null,updatedAt:e.updated_at??new Date().toISOString(),updatedBy:e.updated_by??"coordinator"}}function Ch(e){const t={...e.visualConfig??{},...e.cachedDataset?{__cached_dataset:e.cachedDataset}:{}};return{chart_id:e.chartId,node_id:e.nodeId,sheet_url:e.sheetUrl,tab_name:e.tabName??null,sheet_gid:e.sheetGid??null,range:e.range??null,default_type:e.defaultType||"bar",title_override:e.titleOverride??null,subtitle_override:e.subtitleOverride??null,unit_override:e.unitOverride??null,visual_config:t,cached_dataset:e.cachedDataset??null,updated_at:e.updatedAt||new Date().toISOString(),updated_by:e.updatedBy||"coordinator"}}function Tv(e){const{sheetUrl:t,...n}=e;return n}function os(e){if(as.has(e))return as.get(e);const t=No(`${ko()}${e}`);if(t)try{const n=JSON.parse(t);return as.set(e,n),n}catch{return null}return null}function Rt(e){if(!e||!e.chartId)return!1;as.set(e.chartId,e);const t=kh(`${Yl}${e.chartId}`,JSON.stringify(e));try{const n=No(ss),s=n?JSON.parse(n):[];s.includes(e.chartId)||(s.push(e.chartId),kh(ss,JSON.stringify(s)))}catch{}return xo(e.chartId,e),t||typeof window>"u"}async function xh(e,t){if(!e)return null;if(!(t!=null&&t.forceRefresh)){const s=os(e);if(s)return s}const n=tt();if(n)try{const s=typeof AbortController<"u"?new AbortController:null,a=s?setTimeout(()=>s.abort(),6e3):null,o=`${n.url}/rest/v1/chart_sources?chart_id=eq.${encodeURIComponent(e)}&select=*`,i=await fetch(o,{method:"GET",headers:{apikey:n.anonKey,Authorization:`Bearer ${n.anonKey}`,"Content-Type":"application/json"},signal:s==null?void 0:s.signal});if(a&&clearTimeout(a),i.ok){const l=await i.json();if(Array.isArray(l)&&l.length>0){const c=Xl(l[0]);return Rt(c),c}}}catch{}return os(e)}async function Av(e,t){const n=tt();if(n)try{const a=typeof AbortController<"u"?new AbortController:null,o=a?setTimeout(()=>a.abort(),6e3):null,i=`${n.url}/rest/v1/chart_sources?node_id=eq.${encodeURIComponent(e)}&select=*`,l=await fetch(i,{method:"GET",headers:{apikey:n.anonKey,Authorization:`Bearer ${n.anonKey}`,"Content-Type":"application/json"},signal:a==null?void 0:a.signal});if(o&&clearTimeout(o),l.ok){const c=await l.json();if(Array.isArray(c)){const d=c.map(Xl);for(const h of d)Rt(h);return d}}}catch{}const s=[];try{const a=No(ss),o=a?JSON.parse(a):[];for(const i of o){const l=os(i);l&&l.nodeId===e&&s.push(l)}}catch{}return s}async function is(e,t){if(!e||!e.chartId)return{success:!1,savedLocally:!1,savedToCloud:!1,error:"Chart ID is missing or undefined.",errorCode:"MISSING_CHART_ID"};if(!e.sheetUrl||!e.sheetUrl.trim())return{success:!1,savedLocally:!1,savedToCloud:!1,error:"Google Sheet URL is required.",errorCode:"MISSING_SHEET_URL"};const n={...e,updatedAt:new Date().toISOString()},s=Rt(n),a=tt();if(!a)return{success:s,savedLocally:s,savedToCloud:!1,details:"Offline mode: Supabase cloud is not configured."};try{const o=t||a.anonKey,i=Ch(n),l=typeof AbortController<"u"?new AbortController:null,c=l?setTimeout(()=>l.abort(),8e3):null;let d;try{d=await fetch(`${a.url}/rest/v1/chart_sources`,{method:"POST",headers:{apikey:a.anonKey,Authorization:`Bearer ${o}`,"Content-Type":"application/json",Prefer:"resolution=merge-duplicates,return=representation"},body:JSON.stringify(i),signal:l==null?void 0:l.signal})}finally{c&&clearTimeout(c)}if(d.ok)return{success:!0,savedLocally:s,savedToCloud:!0};let h=null,p="";try{(d.headers.get("content-type")||"").includes("application/json")?h=await d.json():p=await d.text()}catch{}const f=d.status,m=h==null?void 0:h.code,g=(h==null?void 0:h.message)||p||d.statusText;if(f===400&&i.cached_dataset!==void 0&&g.includes("cached_dataset")&&g.includes("column"))try{const{cached_dataset:y,...S}=i,v=typeof AbortController<"u"?new AbortController:null,k=v?setTimeout(()=>v.abort(),8e3):null;let x;try{x=await fetch(`${a.url}/rest/v1/chart_sources`,{method:"POST",headers:{apikey:a.anonKey,Authorization:`Bearer ${o}`,"Content-Type":"application/json",Prefer:"resolution=merge-duplicates,return=representation"},body:JSON.stringify(S),signal:v==null?void 0:v.signal})}finally{k&&clearTimeout(k)}if(x.ok)return{success:!0,savedLocally:s,savedToCloud:!0}}catch{}let b="";return f===404||m==="PGRST205"?b="Supabase table 'chart_sources' not found (HTTP 404, PGRST205). Database migration required.":f===401||f===403||m==="PGRST301"?b=`Supabase write permission denied (HTTP ${f}: Row-Level Security policy).`:f===400||f===422?b=`Database schema rejected payload (HTTP ${f}: ${g||"Constraint violation"}).`:f===409?b=`Database conflict (HTTP 409: ${g||"Duplicate constraint"}).`:f>=500?b=`Supabase cloud server unavailable (HTTP ${f}).`:b=`Supabase rejected request (HTTP ${f}: ${g}).`,{success:s,savedLocally:s,savedToCloud:!1,error:b,errorCode:m,statusCode:f,details:(h==null?void 0:h.details)||(h==null?void 0:h.hint)}}catch(o){const i=o instanceof DOMException&&o.name==="AbortError";return{success:s,savedLocally:s,savedToCloud:!1,error:i?"Request timed out connecting to Supabase cloud.":"Network connection error connecting to Supabase cloud.",errorCode:i?"TIMEOUT":"NETWORK_ERROR",details:o instanceof Error?o.message:String(o)}}}function ls(e,t="save"){if(!e)return t==="deploy"?"Failed to deploy chart configuration: Unknown error.":"Failed to save chart configuration: Unknown error.";if(typeof e=="object"&&e!==null&&"savedLocally"in e){const n=e,s=t==="deploy"?"deploy":"save";if(!n.savedLocally&&!n.savedToCloud)return`Failed to ${s} chart configuration: ${n.error||"Local storage and cloud sync failed."}`;if(n.savedLocally&&!n.savedToCloud)return t==="deploy"?`Failed to deploy to Supabase: ${n.error||"Cloud service unavailable."} (Saved to local browser cache)`:`Saved locally to browser, but cloud sync failed: ${n.error||"Database unavailable."}`}return e instanceof Error?`Failed to ${t} chart configuration: ${e.message}`:`Failed to ${t} chart configuration: ${String(e)}`}async function Iv(e,t){return(await is(e,t)).success}function $v(e){if(e)as.delete(e),Zl(`${ko()}${e}`);else{as.clear();try{const t=No(ss),n=t?JSON.parse(t):[];for(const s of n)Zl(`${Yl}${s}`);Zl(ss)}catch{}}}const Jl={};function mn(e){if(!e||typeof e!="string")return null;const t=e.trim(),n=t.match(/\/spreadsheets\/(?:u\/\d+\/)?d\/([a-zA-Z0-9-_]{20,})/);return n&&n[1]?n[1]:/^[a-zA-Z0-9-_]{25,80}$/.test(t)?t:null}function Nh(e){if(!e||typeof e!="string")return null;const t=e.match(/[#?&]gid=([0-9]+)/);return t&&t[1]?t[1]:null}function Ql(){var t;const e=typeof{url:typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:We&&We.tagName.toUpperCase()==="SCRIPT"&&We.src||new URL("folio.umd.cjs",document.baseURI).href}<"u"&&(Jl==null?void 0:Jl.VITE_GOOGLE_DRIVE_API_KEY)||typeof process<"u"&&((t=process.env)==null?void 0:t.VITE_GOOGLE_DRIVE_API_KEY)||"";return e&&!e.includes("your-google-drive-api-key")&&e.trim().length>10?e.trim():null}function Th(e){if(!e||typeof e!="object")return[];const t=e.sheets;if(!Array.isArray(t))return[];const n=[];for(let s=0;s<t.length;s++){const a=t[s];if(a&&a.properties&&typeof a.properties.title=="string"){const o=a.properties.title.trim(),i=a.properties.sheetId,l=typeof i=="number"?i:Number(i)||0,c=typeof a.properties.index=="number"?a.properties.index:s;n.push({title:o,sheetId:l,index:c})}}return n}function Ev(e){if(!e||typeof e!="string")return[];const t=/items\.push\(\{\s*name:\s*"([^"\\]*(?:\\.[^"\\]*)*)"[^}]*gid:\s*"([0-9-]+)"/g;let n;const s=[];for(;(n=t.exec(e))!==null;){let a=n[1];try{a=JSON.parse(`"${a}"`)}catch{}const o=n[2],i=Number(o)||0;s.push({title:a.trim(),sheetId:i,index:s.length})}return s}async function Ah(e,t,n){const s=mn(e)||e;if(!s)return[];const a=(n==null?void 0:n.timeoutMs)??6e3,o=Ql();if(o){const i=typeof AbortController<"u"?new AbortController:null,l=i?setTimeout(()=>i.abort(),a):null;try{const c=`https://sheets.googleapis.com/v4/spreadsheets/${encodeURIComponent(s)}?fields=properties.title,sheets.properties&key=${encodeURIComponent(o)}`,d=await fetch(c,{method:"GET",headers:{Accept:"application/json"},signal:i==null?void 0:i.signal});if(l&&clearTimeout(l),d.ok){const h=await d.json(),p=Th(h);if(p&&p.length>0)return p}}catch{l&&clearTimeout(l)}}try{const i=typeof AbortController<"u"?new AbortController:null,l=i?setTimeout(()=>i.abort(),a):null,c=`https://docs.google.com/spreadsheets/d/${encodeURIComponent(s)}/htmlview`,d=await fetch(c,{method:"GET",headers:{Accept:"text/html,*/*"},signal:i==null?void 0:i.signal});if(l&&clearTimeout(l),d.ok){const h=await d.text(),p=Ev(h);if(p&&p.length>0)return p}}catch{}return[]}async function Lv(e,t){var i;const n=mn(e);if(!n)return{accessible:!1,spreadsheetId:null,error:"Invalid Google Sheets URL format. Please paste a valid Google Spreadsheet link."};const s=Nh(e),a=Ql(),o=6e3;if(a){const l=typeof AbortController<"u"?new AbortController:null,c=l?setTimeout(()=>l.abort(),o):null;try{const d=`https://sheets.googleapis.com/v4/spreadsheets/${encodeURIComponent(n)}?fields=properties.title,sheets.properties&key=${encodeURIComponent(a)}`,h=await fetch(d,{method:"GET",headers:{Accept:"application/json"},signal:l==null?void 0:l.signal});if(c&&clearTimeout(c),h.ok){const p=await h.json(),f=Th(p);return{accessible:!0,spreadsheetId:n,sheetGid:s,title:(i=p.properties)==null?void 0:i.title,tabs:f}}}catch{c&&clearTimeout(c)}}try{const l=typeof AbortController<"u"?new AbortController:null,c=l?setTimeout(()=>l.abort(),o):null,d=`https://docs.google.com/spreadsheets/d/${encodeURIComponent(n)}/gviz/tq?tqx=out:csv&tq=SELECT+1+LIMIT+1`,h=await fetch(d,{method:"GET",headers:{Accept:"text/csv,text/plain,*/*"},signal:l==null?void 0:l.signal});if(c&&clearTimeout(c),!h.ok)return{accessible:!1,spreadsheetId:n,sheetGid:s,error:"Access Restricted: Please set Google Sheet sharing to 'Anyone with the link can view'."};const p=await h.text();if(p.includes("<!DOCTYPE html")||p.includes("ServiceLogin")||p.includes("accounts.google.com"))return{accessible:!1,spreadsheetId:n,sheetGid:s,error:"Access Restricted: Please set Google Sheet sharing to 'Anyone with the link can view'."};const[f,m]=await Promise.all([Ah(n,t==null?void 0:t.apiKey,{timeoutMs:4e3}),Mv(n,t==null?void 0:t.apiKey,{timeoutMs:4e3})]);return{accessible:!0,spreadsheetId:n,sheetGid:s,tabs:f.length>0?f:void 0,modifiedTime:m||void 0}}catch{return{accessible:!1,spreadsheetId:n,sheetGid:s,error:"Unable to verify sheet access. Ensure the sheet is public and shared with 'Anyone with the link can view'."}}}function Rl(e){if(!e||typeof e!="string")return null;const t=new Date(e);if(isNaN(t.getTime()))return null;try{return new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric",timeZone:"Asia/Manila"}).format(t)}catch{return null}}async function Mv(e,t,n){const s=mn(e)||e;if(!s)return null;const a=Ql();if(!a)return null;const o=n==null?void 0:n.timeoutMs,i=typeof AbortController<"u"?new AbortController:null,l=i?setTimeout(()=>i.abort(),o):null;try{const c=`https://www.googleapis.com/drive/v3/files/${encodeURIComponent(s)}?fields=modifiedTime&key=${encodeURIComponent(a)}`,d={Accept:"application/json"};typeof window>"u"&&(d.Referer="https://engine.example.com");const h=await fetch(c,{method:"GET",headers:d,signal:i==null?void 0:i.signal});if(l&&clearTimeout(l),h.ok){const p=await h.json();if(p&&typeof p.modifiedTime=="string")return p.modifiedTime}return null}catch{return l&&clearTimeout(l),null}}function Ih(e){if(!e||typeof e!="string")return[];const t=[];let n=[],s="",a=!1;for(let o=0;o<e.length;o++){const i=e[o],l=e[o+1];a?i==='"'?l==='"'?(s+='"',o++):a=!1:s+=i:i==='"'?a=!0:i===","?(n.push(s.trim()),s=""):i==="\r"||(i===`
37
- `?(n.push(s.trim()),t.push(n),n=[],s=""):s+=i)}return(s.length>0||n.length>0)&&(n.push(s.trim()),t.push(n)),t.filter(o=>o.some(i=>i.length>0))}function Dv(e,t){if(!e||e.length===0)return[];const n=[],s=t.endRow!==void 0?Math.min(t.endRow,e.length-1):e.length-1;for(let a=t.startRow;a<=s;a++){const o=e[a]||[],i=[],l=Math.min(t.endCol,o.length-1);for(let c=t.startCol;c<=l;c++)i.push(o[c]!==void 0?o[c]:"");n.push(i)}return n}function $h(e){var a;if(!e||e.length===0)return[];const t=e.length,n=Math.max(...e.map(o=>o?o.length:0));if(n===0)return[];const s=[];for(let o=0;o<n;o++){const i=[];for(let l=0;l<t;l++){const c=(a=e[l])==null?void 0:a[o];i.push(c!==void 0?c:"")}s.push(i)}return s}function Bv(e,t,n){if(!n||n==="none"||e.length===0)return{categories:e,series:t};const s=e.map((i,l)=>l);s.sort((i,l)=>{if(n==="category-asc")return(e[i]||"").localeCompare(e[l]||"",void 0,{numeric:!0,sensitivity:"base"});if(n==="category-desc")return(e[l]||"").localeCompare(e[i]||"",void 0,{numeric:!0,sensitivity:"base"});let c=0,d=0;for(const h of t){const p=h.data[i],f=h.data[l];typeof p=="number"&&Number.isFinite(p)&&(c+=p),typeof f=="number"&&Number.isFinite(f)&&(d+=f)}return n==="desc"?d-c:c-d});const a=s.map(i=>e[i]),o=t.map(i=>({...i,data:s.map(l=>i.data[l])}));return{categories:a,series:o}}function cs(e){const{chartId:t,title:n,subtitle:s,unit:a,asOfDate:o="SY 2024-2025",chartType:i="bar",nodeId:l,visualConfig:c={},rawMatrix:d,csvText:h}=e;let p=c.unit||a||"",f=d?[...d]:Ih(h||"");if(c.range){const D=la(c.range);D&&(f=Dv(f,D))}if(c.transpose&&(f=$h(f)),f.length===0)return{chartId:t,title:ft(n),subtitle:s?ft(s):void 0,unit:p,asOfDate:o,chartType:i,nodeId:l,visualConfig:c,categories:[],series:[],sanitizedCsvContent:""};const m=f[0]||[],g=typeof c.categoryColIndex=="number"?c.categoryColIndex:0,b=[],y=[];if(Array.isArray(c.includedSeriesIndices)&&c.includedSeriesIndices.length>0)for(const D of c.includedSeriesIndices)D!==g&&D>=0&&D<m.length&&(b.push(D),y.push(ft(m[D])||`Col ${D+1}`));else for(let D=0;D<m.length;D++)D!==g&&(b.push(D),y.push(ft(m[D])||`Col ${D+1}`));y.length===0&&m.length===1&&(b.push(0),y.push(ft(m[0])||"Value"));const S=c.excludeSummaryRows!==!1;let v=[];const k=y.map(()=>[]);for(let D=1;D<f.length;D++){const W=f[D],H=ft(W[g]||`Row ${D}`);if(!(S&&vh(H))){v.push(H);for(let q=0;q<b.length;q++){const j=b[q],z=W[j],O=ql(z);k[q].push(O)}}}let x=y.map((D,W)=>({name:D,data:k[W]||[]})),I;c.sortField?I=uv(v,x,c.sortField,c.sortDirection||"asc"):I=Bv(v,x,c.sortBy);const N=I.categories,_=I.series;let T=i;T==="auto"&&(T=(_.length>1,"bar"));let w,M;if(T==="histogram"){M=_.flatMap(H=>H.data);const D=M.filter(H=>H!==null&&Number.isFinite(H));w=Gl(D,{strategy:c.binStrategy,binCount:c.binCount,bucketSize:c.bucketSize}).map(H=>({x0:H.x0,x1:H.x1,count:H.count}))}let $;if(T==="scatter"){$=[];const D=typeof c.scatterXColIndex=="number"?c.scatterXColIndex:m.length>1?1:0,W=typeof c.scatterYColIndex=="number"?c.scatterYColIndex:m.length>2?2:m.length>1?1:0,H=typeof c.scatterLabelColIndex=="number"?c.scatterLabelColIndex:g,q=c.scatterGroupColIndex;if(f.length>1)for(let j=1;j<f.length;j++){const z=f[j],O=ft(z[g]||`Row ${j}`);if(S&&vh(O))continue;const U=z[D],Q=z[W],se=ql(U),ae=ql(Q);if(se!==null&&ae!==null){const de=typeof H=="number"&&H>=0&&z[H]?ft(z[H]):O,B=typeof q=="number"&&q>=0&&z[q]?ft(z[q]):void 0;$.push({x:se,y:ae,label:de,group:B})}}if($.length===0&&_.length>=2){const j=N.length;for(let z=0;z<j;z++){const O=_[0].data[z],U=_[1].data[z];O!==null&&U!==null&&$.push({x:O,y:U,label:N[z],group:_[0].name})}}c.sortField&&($=mv($,c.sortField,c.sortDirection||"asc"))}const A=yh(N,_,n,p),V=Rl(c.lastModifiedTime)||o;return{chartId:t,title:ft(n),subtitle:s?ft(s):void 0,unit:p,asOfDate:V,chartType:T,nodeId:l,visualConfig:c,categories:N,series:_,bins:w,rawValues:M,scatterPoints:$,sanitizedCsvContent:A}}async function ec(e){const{sheetUrl:t,tabName:n,sheetGid:s,range:a,timeoutMs:o=8e3}=e;if(!t||typeof t!="string")return[];const i=mn(t);if(!i)return[];const l=s||Nh(t)||void 0;let c=`https://docs.google.com/spreadsheets/d/${encodeURIComponent(i)}/gviz/tq?tqx=out:csv`;l?c+=`&gid=${encodeURIComponent(l)}`:n&&n.trim()&&(c+=`&sheet=${encodeURIComponent(n.trim())}`),a&&a.trim()&&(c+=`&range=${encodeURIComponent(a.trim())}`),c+=`&_folio_t=${Date.now()}`;const d=typeof AbortController<"u"?new AbortController:null,h=d?setTimeout(()=>d.abort(),o):null;try{const p=await fetch(c,{method:"GET",headers:{Accept:"text/csv,text/plain,*/*"},signal:d==null?void 0:d.signal});if(h&&clearTimeout(h),!p.ok)return[];const f=await p.text();return f.includes("<!DOCTYPE html")||f.includes("accounts.google.com")||f.includes("ServiceLogin")?[]:Ih(f)}catch{return h&&clearTimeout(h),[]}}function tc(e){var t,n,s,a,o,i,l,c,d,h,p,f,m,g,b,y,S,v,k,x,I,N,_,T,w,M,$,A,P,V,D,W,H,q,j,z,O,U,Q,se,ae,de,B,Y,ee,X,te,K,J;return{sheetUrl:((e==null?void 0:e.sheetUrl)||"").trim(),tabName:((e==null?void 0:e.tabName)||"").trim(),sheetGid:((e==null?void 0:e.sheetGid)||"").trim(),range:((e==null?void 0:e.range)||"").trim(),chartType:(e==null?void 0:e.defaultType)||"bar",unit:((e==null?void 0:e.unitOverride)||((t=e==null?void 0:e.visualConfig)==null?void 0:t.unit)||"").trim(),titleOverride:((e==null?void 0:e.titleOverride)||"").trim(),subtitleOverride:((e==null?void 0:e.subtitleOverride)||"").trim(),barVariant:((n=e==null?void 0:e.visualConfig)==null?void 0:n.barVariant)||"standard",targetValue:(s=e==null?void 0:e.visualConfig)==null?void 0:s.targetValue,targetLabel:(((a=e==null?void 0:e.visualConfig)==null?void 0:a.targetLabel)||"Target").trim(),categoryColIndex:((o=e==null?void 0:e.visualConfig)==null?void 0:o.categoryColIndex)??0,includedSeriesIndices:(i=e==null?void 0:e.visualConfig)==null?void 0:i.includedSeriesIndices,sortBy:((l=e==null?void 0:e.visualConfig)==null?void 0:l.sortBy)||"none",sortField:((c=e==null?void 0:e.visualConfig)==null?void 0:c.sortField)||((h=(d=e==null?void 0:e.visualConfig)==null?void 0:d.sortBy)!=null&&h.startsWith("category")?"category":"sheet_order"),sortDirection:((p=e==null?void 0:e.visualConfig)==null?void 0:p.sortDirection)||((m=(f=e==null?void 0:e.visualConfig)==null?void 0:f.sortBy)!=null&&m.includes("desc")?"desc":"asc"),orientation:((g=e==null?void 0:e.visualConfig)==null?void 0:g.orientation)||((b=e==null?void 0:e.visualConfig)==null?void 0:b.barOrientation)||"vertical",barOrientation:((y=e==null?void 0:e.visualConfig)==null?void 0:y.barOrientation)||((S=e==null?void 0:e.visualConfig)==null?void 0:S.orientation)||"vertical",stacked:((v=e==null?void 0:e.visualConfig)==null?void 0:v.stacked)||!1,showValues:((k=e==null?void 0:e.visualConfig)==null?void 0:k.showValues)||!1,lastModifiedTime:(x=e==null?void 0:e.visualConfig)==null?void 0:x.lastModifiedTime,excludeSummaryRows:((I=e==null?void 0:e.visualConfig)==null?void 0:I.excludeSummaryRows)??!0,transpose:((N=e==null?void 0:e.visualConfig)==null?void 0:N.transpose)??!1,curveInterpolation:((_=e==null?void 0:e.visualConfig)==null?void 0:_.curveInterpolation)||((e==null?void 0:e.defaultType)==="scatter"?"none":"smooth"),showAreaFill:((T=e==null?void 0:e.visualConfig)==null?void 0:T.showAreaFill)||!1,markerSize:((w=e==null?void 0:e.visualConfig)==null?void 0:w.markerSize)||"regular",autoScaleY:((M=e==null?void 0:e.visualConfig)==null?void 0:M.autoScaleY)||!1,startAtZero:(($=e==null?void 0:e.visualConfig)==null?void 0:$.startAtZero)??!((A=e==null?void 0:e.visualConfig)!=null&&A.autoScaleY),scatterXColIndex:(P=e==null?void 0:e.visualConfig)==null?void 0:P.scatterXColIndex,scatterYColIndex:(V=e==null?void 0:e.visualConfig)==null?void 0:V.scatterYColIndex,scatterLabelColIndex:(D=e==null?void 0:e.visualConfig)==null?void 0:D.scatterLabelColIndex,scatterGroupColIndex:(W=e==null?void 0:e.visualConfig)==null?void 0:W.scatterGroupColIndex,autoScaleX:((H=e==null?void 0:e.visualConfig)==null?void 0:H.autoScaleX)||!1,startAtZeroX:((q=e==null?void 0:e.visualConfig)==null?void 0:q.startAtZeroX)??!((j=e==null?void 0:e.visualConfig)!=null&&j.autoScaleX),loessBandwidth:((z=e==null?void 0:e.visualConfig)==null?void 0:z.loessBandwidth)??.5,showCorrelationChip:((O=e==null?void 0:e.visualConfig)==null?void 0:O.showCorrelationChip)||!1,donutVariant:((U=e==null?void 0:e.visualConfig)==null?void 0:U.donutVariant)||"donut",groupOthers:((Q=e==null?void 0:e.visualConfig)==null?void 0:Q.groupOthers)??!0,binStrategy:((se=e==null?void 0:e.visualConfig)==null?void 0:se.binStrategy)||"auto",customBinMode:((ae=e==null?void 0:e.visualConfig)==null?void 0:ae.bucketSize)!==void 0?"step":"count",binCount:((de=e==null?void 0:e.visualConfig)==null?void 0:de.binCount)||8,bucketSize:((B=e==null?void 0:e.visualConfig)==null?void 0:B.bucketSize)||5,histogramYMode:((Y=e==null?void 0:e.visualConfig)==null?void 0:Y.histogramYMode)||"frequency",showSummaryStats:((ee=e==null?void 0:e.visualConfig)==null?void 0:ee.showSummaryStats)||!1,showMedianMode:((X=e==null?void 0:e.visualConfig)==null?void 0:X.showMedianMode)||!1,showReferenceGuide:((te=e==null?void 0:e.visualConfig)==null?void 0:te.showReferenceGuide)||!1,xLabel:(((K=e==null?void 0:e.visualConfig)==null?void 0:K.xLabel)||"").trim(),yLabel:(((J=e==null?void 0:e.visualConfig)==null?void 0:J.yLabel)||"").trim()}}function Ov(e){const[t,n]=u.useState(()=>(e==null?void 0:e.sheetUrl)||""),[s,a]=u.useState(()=>(e==null?void 0:e.tabName)||""),[o,i]=u.useState(()=>(e==null?void 0:e.sheetGid)||""),[l,c]=u.useState(()=>(e==null?void 0:e.range)||""),[d,h]=u.useState(()=>(e==null?void 0:e.defaultType)||"bar"),[p,f]=u.useState(()=>{var E;return(e==null?void 0:e.unitOverride)||((E=e==null?void 0:e.visualConfig)==null?void 0:E.unit)||""}),[m,g]=u.useState(()=>(e==null?void 0:e.titleOverride)||""),[b,y]=u.useState(()=>(e==null?void 0:e.subtitleOverride)||""),[S,v]=u.useState(()=>{var E;return((E=e==null?void 0:e.visualConfig)==null?void 0:E.xLabel)||""}),[k,x]=u.useState(()=>{var E;return((E=e==null?void 0:e.visualConfig)==null?void 0:E.yLabel)||""}),[I,N]=u.useState(()=>{var E;return((E=e==null?void 0:e.visualConfig)==null?void 0:E.excludeSummaryRows)??!0}),[_,T]=u.useState(()=>{var E;return((E=e==null?void 0:e.visualConfig)==null?void 0:E.transpose)??!1}),[w,M]=u.useState(()=>{var E;return((E=e==null?void 0:e.visualConfig)==null?void 0:E.barVariant)||"standard"}),[$,A]=u.useState(()=>{var E;return(E=e==null?void 0:e.visualConfig)==null?void 0:E.targetValue}),[P,V]=u.useState(()=>{var E;return((E=e==null?void 0:e.visualConfig)==null?void 0:E.targetLabel)||"Target"}),[D,W]=u.useState(()=>{var E;return((E=e==null?void 0:e.visualConfig)==null?void 0:E.categoryColIndex)??0}),[H,q]=u.useState(()=>{var E;return(E=e==null?void 0:e.visualConfig)==null?void 0:E.includedSeriesIndices}),[j,z]=u.useState(()=>{var E;return((E=e==null?void 0:e.visualConfig)==null?void 0:E.sortBy)||"none"}),[O,U]=u.useState(()=>{var E,et,Bt;return((E=e==null?void 0:e.visualConfig)==null?void 0:E.sortField)||((Bt=(et=e==null?void 0:e.visualConfig)==null?void 0:et.sortBy)!=null&&Bt.startsWith("category")?"category":"sheet_order")}),[Q,se]=u.useState(()=>{var E,et,Bt;return((E=e==null?void 0:e.visualConfig)==null?void 0:E.sortDirection)||((Bt=(et=e==null?void 0:e.visualConfig)==null?void 0:et.sortBy)!=null&&Bt.includes("desc")?"desc":"asc")}),[ae,de]=u.useState(()=>{var E,et;return((E=e==null?void 0:e.visualConfig)==null?void 0:E.orientation)||((et=e==null?void 0:e.visualConfig)==null?void 0:et.barOrientation)||"vertical"}),[B,Y]=u.useState(()=>{var E;return((E=e==null?void 0:e.visualConfig)==null?void 0:E.stacked)||!1}),[ee,X]=u.useState(()=>{var E;return((E=e==null?void 0:e.visualConfig)==null?void 0:E.showValues)||!1}),[te,K]=u.useState(()=>{var E;return(E=e==null?void 0:e.visualConfig)==null?void 0:E.lastModifiedTime}),[J,Z]=u.useState(()=>{var E;return((E=e==null?void 0:e.visualConfig)==null?void 0:E.curveInterpolation)||((e==null?void 0:e.defaultType)==="scatter"?"none":"smooth")}),[ne,ie]=u.useState(()=>{var E;return((E=e==null?void 0:e.visualConfig)==null?void 0:E.showAreaFill)||!1}),[F,L]=u.useState(()=>{var E;return((E=e==null?void 0:e.visualConfig)==null?void 0:E.markerSize)||"regular"}),[G,le]=u.useState(()=>{var E;return((E=e==null?void 0:e.visualConfig)==null?void 0:E.autoScaleY)||!1}),[ue,he]=u.useState(()=>{var E,et;return((E=e==null?void 0:e.visualConfig)==null?void 0:E.startAtZero)!==void 0?e.visualConfig.startAtZero:((et=e==null?void 0:e.visualConfig)==null?void 0:et.autoScaleY)!==void 0?!e.visualConfig.autoScaleY:!0}),[oe,ye]=u.useState(()=>{var E;return(E=e==null?void 0:e.visualConfig)==null?void 0:E.scatterXColIndex}),[xe,ke]=u.useState(()=>{var E;return(E=e==null?void 0:e.visualConfig)==null?void 0:E.scatterYColIndex}),[Ze,De]=u.useState(()=>{var E;return(E=e==null?void 0:e.visualConfig)==null?void 0:E.scatterLabelColIndex}),[je,kt]=u.useState(()=>{var E;return(E=e==null?void 0:e.visualConfig)==null?void 0:E.scatterGroupColIndex}),[Bn,Io]=u.useState(()=>{var E;return((E=e==null?void 0:e.visualConfig)==null?void 0:E.autoScaleX)||!1}),[ar,$o]=u.useState(()=>{var E,et;return((E=e==null?void 0:e.visualConfig)==null?void 0:E.startAtZeroX)!==void 0?e.visualConfig.startAtZeroX:((et=e==null?void 0:e.visualConfig)==null?void 0:et.autoScaleX)!==void 0?!e.visualConfig.autoScaleX:!0}),[On,ua]=u.useState(()=>{var E;return((E=e==null?void 0:e.visualConfig)==null?void 0:E.loessBandwidth)??.5}),[yn,ps]=u.useState(()=>{var E;return((E=e==null?void 0:e.visualConfig)==null?void 0:E.showCorrelationChip)||!1}),[or,Eo]=u.useState(()=>{var E;return((E=e==null?void 0:e.visualConfig)==null?void 0:E.donutVariant)||"donut"}),[ir,Lo]=u.useState(()=>{var E;return((E=e==null?void 0:e.visualConfig)==null?void 0:E.groupOthers)??!0}),[lr,Mo]=u.useState(()=>{var E;return((E=e==null?void 0:e.visualConfig)==null?void 0:E.binStrategy)||"auto"}),[Pn,ms]=u.useState(()=>{var E;return((E=e==null?void 0:e.visualConfig)==null?void 0:E.bucketSize)!==void 0?"step":"count"}),[cr,Kh]=u.useState(()=>{var E;return((E=e==null?void 0:e.visualConfig)==null?void 0:E.binCount)||8}),[dr,Yh]=u.useState(()=>{var E;return((E=e==null?void 0:e.visualConfig)==null?void 0:E.bucketSize)||5}),[ha,Zh]=u.useState(()=>{var E;return((E=e==null?void 0:e.visualConfig)==null?void 0:E.histogramYMode)||"frequency"}),[fa,Xh]=u.useState(()=>{var E;return((E=e==null?void 0:e.visualConfig)==null?void 0:E.showSummaryStats)||!1}),[pa,Jh]=u.useState(()=>{var E;return((E=e==null?void 0:e.visualConfig)==null?void 0:E.showMedianMode)||!1}),[ma,Qh]=u.useState(()=>{var E;return((E=e==null?void 0:e.visualConfig)==null?void 0:E.showReferenceGuide)||!1}),[_e,uc]=u.useState(()=>tc(e)),Bb=u.useCallback(E=>{var Bt,gs,vs,Do,Bo,Oo,Po,Fo,Rh,ef,tf,nf,rf,sf,af,of,lf,cf,df,uf,hf,ff,pf,mf,gf,vf,bf,yf,_f,wf,Sf,kf,Cf,xf,Nf,Tf,Af,If,$f,Ef,Lf,Mf,Df,Bf,Of,Pf,Ff;const et=tc(E);uc(et),n((E==null?void 0:E.sheetUrl)||""),a((E==null?void 0:E.tabName)||""),i((E==null?void 0:E.sheetGid)||""),c((E==null?void 0:E.range)||""),h((E==null?void 0:E.defaultType)||"bar"),f((E==null?void 0:E.unitOverride)||((Bt=E==null?void 0:E.visualConfig)==null?void 0:Bt.unit)||""),g((E==null?void 0:E.titleOverride)||""),y((E==null?void 0:E.subtitleOverride)||""),v(((gs=E==null?void 0:E.visualConfig)==null?void 0:gs.xLabel)||""),x(((vs=E==null?void 0:E.visualConfig)==null?void 0:vs.yLabel)||""),M(((Do=E==null?void 0:E.visualConfig)==null?void 0:Do.barVariant)||"standard"),A((Bo=E==null?void 0:E.visualConfig)==null?void 0:Bo.targetValue),V(((Oo=E==null?void 0:E.visualConfig)==null?void 0:Oo.targetLabel)||"Target"),W(((Po=E==null?void 0:E.visualConfig)==null?void 0:Po.categoryColIndex)??0),q((Fo=E==null?void 0:E.visualConfig)==null?void 0:Fo.includedSeriesIndices),z(((Rh=E==null?void 0:E.visualConfig)==null?void 0:Rh.sortBy)||"none"),U(((ef=E==null?void 0:E.visualConfig)==null?void 0:ef.sortField)||((nf=(tf=E==null?void 0:E.visualConfig)==null?void 0:tf.sortBy)!=null&&nf.startsWith("category")?"category":"sheet_order")),se(((rf=E==null?void 0:E.visualConfig)==null?void 0:rf.sortDirection)||((af=(sf=E==null?void 0:E.visualConfig)==null?void 0:sf.sortBy)!=null&&af.includes("desc")?"desc":"asc")),de(((of=E==null?void 0:E.visualConfig)==null?void 0:of.orientation)||((lf=E==null?void 0:E.visualConfig)==null?void 0:lf.barOrientation)||"vertical"),Y(((cf=E==null?void 0:E.visualConfig)==null?void 0:cf.stacked)||!1),X(((df=E==null?void 0:E.visualConfig)==null?void 0:df.showValues)||!1),Z(((uf=E==null?void 0:E.visualConfig)==null?void 0:uf.curveInterpolation)||((E==null?void 0:E.defaultType)==="scatter"?"none":"smooth")),ie(((hf=E==null?void 0:E.visualConfig)==null?void 0:hf.showAreaFill)||!1),L(((ff=E==null?void 0:E.visualConfig)==null?void 0:ff.markerSize)||"regular"),le(((pf=E==null?void 0:E.visualConfig)==null?void 0:pf.autoScaleY)||!1),he(((mf=E==null?void 0:E.visualConfig)==null?void 0:mf.startAtZero)??!((gf=E==null?void 0:E.visualConfig)!=null&&gf.autoScaleY)),ye((vf=E==null?void 0:E.visualConfig)==null?void 0:vf.scatterXColIndex),ke((bf=E==null?void 0:E.visualConfig)==null?void 0:bf.scatterYColIndex),De((yf=E==null?void 0:E.visualConfig)==null?void 0:yf.scatterLabelColIndex),kt((_f=E==null?void 0:E.visualConfig)==null?void 0:_f.scatterGroupColIndex),Io(((wf=E==null?void 0:E.visualConfig)==null?void 0:wf.autoScaleX)||!1),$o(((Sf=E==null?void 0:E.visualConfig)==null?void 0:Sf.startAtZeroX)??!((kf=E==null?void 0:E.visualConfig)!=null&&kf.autoScaleX)),ua(((Cf=E==null?void 0:E.visualConfig)==null?void 0:Cf.loessBandwidth)??.5),ps(((xf=E==null?void 0:E.visualConfig)==null?void 0:xf.showCorrelationChip)||!1),Eo(((Nf=E==null?void 0:E.visualConfig)==null?void 0:Nf.donutVariant)||"donut"),Lo(((Tf=E==null?void 0:E.visualConfig)==null?void 0:Tf.groupOthers)??!0),Mo(((Af=E==null?void 0:E.visualConfig)==null?void 0:Af.binStrategy)||"auto"),ms(((If=E==null?void 0:E.visualConfig)==null?void 0:If.bucketSize)!==void 0?"step":"count"),Kh((($f=E==null?void 0:E.visualConfig)==null?void 0:$f.binCount)||8),Yh(((Ef=E==null?void 0:E.visualConfig)==null?void 0:Ef.bucketSize)||5),Zh(((Lf=E==null?void 0:E.visualConfig)==null?void 0:Lf.histogramYMode)||"frequency"),Xh(((Mf=E==null?void 0:E.visualConfig)==null?void 0:Mf.showSummaryStats)||!1),Jh(((Df=E==null?void 0:E.visualConfig)==null?void 0:Df.showMedianMode)||!1),Qh(((Bf=E==null?void 0:E.visualConfig)==null?void 0:Bf.showReferenceGuide)||!1),K((Of=E==null?void 0:E.visualConfig)==null?void 0:Of.lastModifiedTime),N(((Pf=E==null?void 0:E.visualConfig)==null?void 0:Pf.excludeSummaryRows)??!0),T(((Ff=E==null?void 0:E.visualConfig)==null?void 0:Ff.transpose)??!1)},[]),Ob=u.useCallback(E=>{uc(tc(E))},[]),Pb=u.useMemo(()=>{const E=t.trim(),et=s.trim(),Bt=o.trim(),gs=l.trim(),vs=p.trim(),Do=m.trim(),Bo=b.trim(),Oo=S.trim(),Po=k.trim(),Fo=P.trim();return!_e.sheetUrl&&!E?!1:E!==_e.sheetUrl||et!==_e.tabName||Bt!==_e.sheetGid||gs!==_e.range||d!==_e.chartType||vs!==_e.unit||Do!==_e.titleOverride||Bo!==_e.subtitleOverride||Oo!==_e.xLabel||Po!==_e.yLabel||w!==_e.barVariant||$!==_e.targetValue||Fo!==_e.targetLabel||D!==_e.categoryColIndex||JSON.stringify(H)!==JSON.stringify(_e.includedSeriesIndices)||j!==_e.sortBy||O!==_e.sortField||Q!==_e.sortDirection||ae!==_e.barOrientation||B!==_e.stacked||ee!==_e.showValues||J!==_e.curveInterpolation||ne!==_e.showAreaFill||F!==_e.markerSize||G!==_e.autoScaleY||ue!==_e.startAtZero||oe!==_e.scatterXColIndex||xe!==_e.scatterYColIndex||Ze!==_e.scatterLabelColIndex||je!==_e.scatterGroupColIndex||Bn!==_e.autoScaleX||ar!==_e.startAtZeroX||On!==_e.loessBandwidth||yn!==_e.showCorrelationChip||or!==_e.donutVariant||ir!==_e.groupOthers||lr!==_e.binStrategy||Pn!==_e.customBinMode||cr!==_e.binCount||dr!==_e.bucketSize||ha!==_e.histogramYMode||fa!==_e.showSummaryStats||pa!==_e.showMedianMode||ma!==_e.showReferenceGuide||te!==_e.lastModifiedTime||I!==_e.excludeSummaryRows||_!==_e.transpose},[t,s,o,l,d,p,m,b,S,k,w,$,P,D,H,j,O,Q,ae,B,ee,J,ne,F,G,ue,oe,xe,Ze,je,Bn,ar,On,yn,or,ir,lr,Pn,cr,dr,ha,fa,pa,ma,te,I,_,_e]),Fb=u.useCallback((E,et,Bt,gs,vs)=>({chartId:E,nodeId:et,sheetUrl:t.trim(),tabName:s.trim()||void 0,sheetGid:o.trim()||void 0,range:l.trim(),defaultType:d,titleOverride:m.trim()||void 0,subtitleOverride:b.trim()||void 0,unitOverride:p.trim()||void 0,visualConfig:{unit:p.trim()||void 0,xLabel:S.trim()||void 0,yLabel:k.trim()||void 0,range:l.trim(),tabName:s.trim()||void 0,sheetGid:o.trim()||void 0,excludeSummaryRows:I,transpose:_,barVariant:d==="bar"?w:void 0,targetValue:d==="bar"&&w==="progress"?$:void 0,targetLabel:d==="bar"&&w==="progress"?P:void 0,categoryColIndex:D,includedSeriesIndices:H,sortBy:d==="donut"?void 0:j,sortField:d==="donut"?void 0:O,sortDirection:d==="donut"?void 0:Q,orientation:d==="bar"?ae:void 0,barOrientation:d==="bar"?ae:void 0,stacked:d==="bar"?B:void 0,showValues:d==="bar"||d==="line"||d==="donut"?ee:void 0,curveInterpolation:d==="line"||d==="histogram"||d==="scatter"?J:void 0,showAreaFill:d==="line"||d==="scatter"?ne:void 0,markerSize:d==="line"||d==="scatter"?F:void 0,autoScaleY:d==="line"||d==="bar"||d==="scatter"?G:void 0,startAtZero:d==="line"||d==="scatter"?ue:void 0,startAtZeroX:d==="scatter"?ar:void 0,loessBandwidth:d==="scatter"?On:void 0,scatterXColIndex:d==="scatter"?Bt??oe:void 0,scatterYColIndex:d==="scatter"?gs??xe:void 0,scatterLabelColIndex:d==="scatter"?vs??Ze:void 0,scatterGroupColIndex:d==="scatter"?je:void 0,autoScaleX:d==="scatter"?Bn:void 0,showCorrelationChip:d==="scatter"?yn:void 0,donutVariant:d==="donut"?or:void 0,groupOthers:d==="donut"?ir:void 0,binStrategy:d==="histogram"?lr:void 0,binCount:d==="histogram"&&Pn==="count"?typeof cr=="number"&&cr>=2?Math.min(50,cr):8:void 0,bucketSize:d==="histogram"&&Pn==="step"?typeof dr=="number"&&dr>=1?dr:5:void 0,histogramYMode:d==="histogram"?ha:void 0,showSummaryStats:d==="histogram"?fa:void 0,showMedianMode:d==="histogram"?pa:void 0,showReferenceGuide:d==="histogram"||d==="scatter"?ma:void 0,lastModifiedTime:te},updatedAt:new Date().toISOString(),updatedBy:"coordinator"}),[t,s,o,l,d,m,b,S,k,p,I,_,w,$,P,D,H,j,O,Q,ae,B,ee,J,ne,F,G,ue,ar,On,oe,xe,Ze,je,Bn,yn,or,ir,lr,Pn,cr,dr,ha,fa,pa,ma,te]);return{sheetUrl:t,setSheetUrl:n,tabName:s,setTabName:a,sheetGid:o,setSheetGid:i,range:l,setRange:c,chartType:d,setChartType:h,unit:p,setUnit:f,titleOverride:m,setTitleOverride:g,subtitleOverride:b,setSubtitleOverride:y,xLabel:S,setXLabel:v,yLabel:k,setYLabel:x,excludeSummaryRows:I,setExcludeSummaryRows:N,transpose:_,setTranspose:T,barVariant:w,setBarVariant:M,targetValue:$,setTargetValue:A,targetLabel:P,setTargetLabel:V,categoryColIndex:D,setCategoryColIndex:W,includedSeriesIndices:H,setIncludedSeriesIndices:q,sortBy:j,setSortBy:z,sortField:O,setSortField:U,sortDirection:Q,setSortDirection:se,barOrientation:ae,setBarOrientation:de,stacked:B,setStacked:Y,showValues:ee,setShowValues:X,lastModifiedTime:te,setLastModifiedTime:K,curveInterpolation:J,setCurveInterpolation:Z,showAreaFill:ne,setShowAreaFill:ie,markerSize:F,setMarkerSize:L,autoScaleY:G,setAutoScaleY:le,startAtZero:ue,setStartAtZero:he,scatterXColIndex:oe,setScatterXColIndex:ye,scatterYColIndex:xe,setScatterYColIndex:ke,scatterLabelColIndex:Ze,setScatterLabelColIndex:De,scatterGroupColIndex:je,setScatterGroupColIndex:kt,autoScaleX:Bn,setAutoScaleX:Io,startAtZeroX:ar,setStartAtZeroX:$o,loessBandwidth:On,setLoessBandwidth:ua,showCorrelationChip:yn,setShowCorrelationChip:ps,donutVariant:or,setDonutVariant:Eo,groupOthers:ir,setGroupOthers:Lo,binStrategy:lr,setBinStrategy:Mo,customBinMode:Pn,setCustomBinMode:ms,binCount:cr,setBinCount:Kh,bucketSize:dr,setBucketSize:Yh,histogramYMode:ha,setHistogramYMode:Zh,showSummaryStats:fa,setShowSummaryStats:Xh,showMedianMode:pa,setShowMedianMode:Jh,showReferenceGuide:ma,setShowReferenceGuide:Qh,savedSnapshot:_e,setSavedSnapshot:uc,hasUnsavedChanges:Pb,resetForm:Bb,markAsSaved:Ob,buildConfigPayload:Fb}}function Pv({sheetUrl:e,tabName:t,sheetGid:n,initialConfig:s,setTabName:a,setSheetGid:o,setLastModifiedTime:i,onAutoSelectTab:l}){var I;const[c,d]=u.useState(()=>s!=null&&s.sheetUrl?"public":"idle"),[h,p]=u.useState(()=>s!=null&&s.sheetUrl?"Public Access Verified":""),[f,m]=u.useState(()=>s!=null&&s.tabName?[{title:s.tabName,sheetId:Number(s.sheetGid)||0,index:0}]:[]),g=u.useRef(t);g.current=t;const b=u.useRef(n);b.current=n;const y=u.useRef(((I=s==null?void 0:s.sheetUrl)==null?void 0:I.trim())||null),S=u.useCallback(async N=>{const _=N.trim();if(!_){y.current=null,d("idle"),p(""),m([]);return}if(!mn(_)){y.current=_,d("invalid"),p("Invalid Google Sheet link"),m([]);return}d("checking"),p("Verifying link access…");try{const[w,M]=await Promise.all([Lv(_),Ah(_)]);y.current=_,w.accessible?(d("public"),p("Public Access Verified"),w.sheetGid&&!b.current&&o(w.sheetGid),w.modifiedTime&&i(w.modifiedTime)):(d("restricted"),p("Link Sharing Restricted"));const $=(M&&M.length>0?M:w.tabs)||[];if($.length>0){m($);const A=g.current?$.find(P=>P.title===g.current):null;if(A)a(A.title),o(String(A.sheetId));else{const P=w.sheetGid||b.current,V=P?$.find(D=>String(D.sheetId)===P):null;if(V)a(V.title),o(String(V.sheetId)),l==null||l(V.title,String(V.sheetId));else{const D=$[0];a(D.title),o(String(D.sheetId)),l==null||l(D.title,String(D.sheetId))}}}else g.current||a("Sheet1")}catch{y.current=_,d("restricted"),p("Link Sharing Restricted")}},[a,o,i,l]);u.useEffect(()=>{const N=e.trim();if(!N){d("idle"),p(""),m([]),y.current=null;return}if(!mn(N)){d("invalid"),p("Invalid Google Sheet link"),m([]);return}y.current&&y.current!==N&&(d("idle"),p(""),m([]))},[e]);const v=u.useCallback(N=>{const _=N.target.value;a(_);const T=f.find(w=>w.title===_);T&&o(String(T.sheetId))},[f,a,o]),k=u.useMemo(()=>{var T;return!mn(e)?!1:!!(s!=null&&s.sheetUrl)&&e.trim()===((T=s==null?void 0:s.sheetUrl)==null?void 0:T.trim())?!0:c==="public"},[e,c,s]),x=u.useCallback((N,_,T)=>{d(N?"public":"idle"),p(N?"Public Access Verified":""),y.current=(N==null?void 0:N.trim())||null,m(_?[{title:_,sheetId:Number(T)||0,index:0}]:[])},[]);return{accessStatus:c,setAccessStatus:d,statusMessage:h,setStatusMessage:p,discoveredTabs:f,setDiscoveredTabs:m,isStep1Valid:k,executeVerification:S,handleTabChange:v,resetVerification:x}}function Fv({sheetUrl:e,tabName:t,sheetGid:n,range:s,previewMatrix:a}){const[o,i]=u.useState([]),[l,c]=u.useState(!1),d=u.useCallback(async(y=e,S=t,v=n)=>{const k=y.trim();if(!k||!mn(k)){i([]);return}c(!0);try{const x=await ec({sheetUrl:k,tabName:S?S.trim():void 0,sheetGid:v?v.trim():void 0,timeoutMs:8e3});i(x||[])}catch{i([])}finally{c(!1)}},[e,t,n]),h=u.useMemo(()=>o,[o]),p=u.useMemo(()=>Sv(h),[h]),f=u.useMemo(()=>{if(o&&o.length>0){const y=la(s);if(!y)return o;const S=Math.max(0,y.startRow),v=typeof y.endRow=="number"?Math.min(o.length-1,y.endRow):o.length-1,k=Math.max(0,y.startCol),x=Math.max(k,y.endCol),I=[];for(let N=S;N<=v&&N<o.length;N++){const _=o[N]||[],T=[];for(let w=k;w<=x;w++)T.push(_[w]!==void 0?_[w]:null);I.push(T)}return I}return a&&a.length>0?a:[]},[o,a,s]),m=f.length>0?f:a||[],g=m[0]||[],b=u.useMemo(()=>g.map((y,S)=>({index:S,label:y!=null&&String(y).trim()!==""?String(y).trim():`Col ${S+1}`})),[g]);return{fetchedMatrix:o,fullMatrix:h,isSyncing:l,liveMatrix:f,activeMatrix:m,detectedColumns:b,detectedRange:p,executeSync:d}}const Ne={stepPanel:"_stepPanel_12c72_1",sectionGroup:"_sectionGroup_12c72_20",formGroup:"_formGroup_12c72_42",label:"_label_12c72_48",labelTitle:"_labelTitle_12c72_58",verifiedCheck:"_verifiedCheck_12c72_64",labelRow:"_labelRow_12c72_81",goToSourceBtn:"_goToSourceBtn_12c72_88",input:"_input_12c72_122",inputSuccess:"_inputSuccess_12c72_143",inputError:"_inputError_12c72_147",select:"_select_12c72_151",fieldWithActionRow:"_fieldWithActionRow_12c72_177",inlineActionBtn:"_inlineActionBtn_12c72_191",rangeRow:"_rangeRow_12c72_288",rangeDisplayWrapper:"_rangeDisplayWrapper_12c72_295",rangeBadge:"_rangeBadge_12c72_300",rangeBadgeEmpty:"_rangeBadgeEmpty_12c72_314",selectRangeBtn:"_selectRangeBtn_12c72_332",errorText:"_errorText_12c72_336",guidanceCard:"_guidanceCard_12c72_344",guidanceHeader:"_guidanceHeader_12c72_354",guidanceTitleWrapper:"_guidanceTitleWrapper_12c72_360",guidanceIcon:"_guidanceIcon_12c72_366",guidanceTitle:"_guidanceTitle_12c72_360",guidanceText:"_guidanceText_12c72_377",guidanceSteps:"_guidanceSteps_12c72_385",guidanceStepItem:"_guidanceStepItem_12c72_391",stepNum:"_stepNum_12c72_400",guidanceActions:"_guidanceActions_12c72_415"},Uv=({sheetUrl:e,setSheetUrl:t,accessStatus:n,statusMessage:s,discoveredTabs:a,tabName:o,sheetGid:i,setTabName:l,executeVerification:c,handleTabChange:d,onResync:h,isSyncing:p=!1,range:f,isRangeValid:m,isSelectingRange:g,setIsSelectingRange:b,executeSync:y})=>{var k;const S=!!mn(e.trim()),v=u.useMemo(()=>{if(a.length>0){const x=a.some(I=>I.title===o);return o&&!x?[{title:o,sheetId:"current"},...a]:a}return[{title:o||"Sheet1",sheetId:"default"}]},[a,o]);return r.jsxs("div",{className:Ne.stepPanel,children:[r.jsx("div",{className:Ne.sectionGroup,children:r.jsxs("div",{className:Ne.formGroup,children:[r.jsxs("div",{className:Ne.labelRow,children:[r.jsx("label",{className:Ne.label,htmlFor:"cfg-sheet-url",children:r.jsxs("span",{className:Ne.labelTitle,children:[r.jsx("span",{children:"1. Paste your Google Sheets Link"}),n==="public"&&r.jsx("span",{className:Ne.verifiedCheck,"aria-label":"Verified",title:"Verified",children:"✓"})]})}),e&&r.jsx("a",{href:e,target:"_blank",rel:"noopener noreferrer",className:Ne.goToSourceBtn,title:"Open spreadsheet in new tab",children:r.jsx("span",{children:"Open ↗"})})]}),r.jsxs("div",{className:Ne.fieldWithActionRow,children:[r.jsx("input",{id:"cfg-sheet-url",type:"url",className:`${Ne.input} ${n==="invalid"?Ne.inputError:""} ${n==="public"?Ne.inputSuccess:""}`,placeholder:"https://docs.google.com/spreadsheets/d/.../edit",value:e,onChange:x=>t(x.target.value),autoComplete:"off"}),r.jsx(me,{type:"button",variant:"primary",size:"sm",onClick:()=>c(e.trim()),disabled:!S||n==="checking",className:Ne.inlineActionBtn,"aria-label":"Verify",children:"Verify"})]}),n==="restricted"&&r.jsxs("div",{className:Ne.guidanceCard,role:"alert",children:[r.jsx("div",{className:Ne.guidanceHeader,children:r.jsxs("div",{className:Ne.guidanceTitleWrapper,children:[r.jsx("span",{className:Ne.guidanceIcon,"aria-hidden":"true",children:r.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[r.jsx("rect",{x:"3",y:"11",width:"18",height:"11",rx:"2",ry:"2"}),r.jsx("path",{d:"M7 11V7a5 5 0 0 1 10 0v4"})]})}),r.jsx("span",{className:Ne.guidanceTitle,children:"Enable Link Sharing"})]})}),r.jsx("p",{className:Ne.guidanceText,children:"Google Sheets must be set to public view for live indicator charts to render."}),r.jsxs("div",{className:Ne.guidanceSteps,children:[r.jsxs("div",{className:Ne.guidanceStepItem,children:[r.jsx("span",{className:Ne.stepNum,children:"1"}),r.jsxs("span",{children:["Click ",r.jsx("strong",{children:"Share"})," in Google Sheet"]})]}),r.jsxs("div",{className:Ne.guidanceStepItem,children:[r.jsx("span",{className:Ne.stepNum,children:"2"}),r.jsxs("span",{children:["Change access to ",r.jsx("strong",{children:"Anyone with the link"})]})]}),r.jsxs("div",{className:Ne.guidanceStepItem,children:[r.jsx("span",{className:Ne.stepNum,children:"3"}),r.jsxs("span",{children:["Keep role set to ",r.jsx("strong",{children:"Viewer"})]})]})]}),r.jsxs("div",{className:Ne.guidanceActions,children:[e&&r.jsx(me,{as:"a",href:e,target:"_blank",rel:"noopener noreferrer",variant:"secondary",size:"sm",children:"Open Sheet ↗"}),r.jsx(me,{type:"button",variant:"secondary",size:"sm",onClick:()=>c(e),children:"Re-verify Link"})]})]})]})}),(e.trim()||n==="public")&&r.jsx("div",{className:Ne.sectionGroup,children:r.jsxs("div",{className:Ne.formGroup,children:[r.jsx("div",{className:Ne.labelRow,children:r.jsx("label",{className:Ne.label,htmlFor:"cfg-tab-name",children:r.jsx("span",{children:"2. Select a Tab"})})}),r.jsxs("div",{className:Ne.fieldWithActionRow,children:[r.jsx("select",{id:"cfg-tab-name",className:Ne.select,value:o||(((k=v[0])==null?void 0:k.title)??"Sheet1"),onChange:d,disabled:v.length===0,"aria-label":"Select Sheet Tab",children:v.map(x=>r.jsx("option",{value:x.title,children:x.title},String(x.sheetId??x.title)))}),r.jsx(me,{type:"button",variant:"primary",size:"sm",onClick:()=>y(e,o,i),disabled:n!=="public"||!o||p,className:Ne.inlineActionBtn,"aria-label":"Refresh",children:"Refresh"})]})]})}),r.jsx("div",{className:Ne.sectionGroup,children:r.jsxs("div",{className:Ne.formGroup,children:[r.jsx("div",{className:Ne.labelRow,children:r.jsx("label",{className:Ne.label,children:r.jsxs("span",{children:["3. Select Range",r.jsx(Xn,{text:"The box of cells to use for this chart, like A1:D10.",label:"Data Range"})]})})}),r.jsxs("div",{className:Ne.rangeRow,children:[r.jsx("div",{className:Ne.rangeDisplayWrapper,children:r.jsx("span",{className:f?Ne.rangeBadge:Ne.rangeBadgeEmpty,children:f||"—"})}),r.jsx(me,{type:"button",variant:"primary",size:"sm",onClick:()=>b(x=>!x),className:Ne.selectRangeBtn,"aria-label":g?"Finish range selection":"Select range on sheet",children:g?"Done":"Select"})]}),!m&&f&&r.jsx("p",{className:Ne.errorText,children:"Invalid range"})]})})]})},ze={container:"_container_1reoz_7",table:"_table_1reoz_20",headerCell:"_headerCell_1reoz_30",cornerCell:"_cornerCell_1reoz_46",rowNumberCell:"_rowNumberCell_1reoz_58",dataCell:"_dataCell_1reoz_75",dataCellSelecting:"_dataCellSelecting_1reoz_91",nullCell:"_nullCell_1reoz_99",cellSelected:"_cellSelected_1reoz_105",cellBorderTop:"_cellBorderTop_1reoz_109",cellBorderBottom:"_cellBorderBottom_1reoz_113",cellBorderLeft:"_cellBorderLeft_1reoz_117",cellBorderRight:"_cellBorderRight_1reoz_121",cellActiveDrag:"_cellActiveDrag_1reoz_126",cellActiveDragBorderTop:"_cellActiveDragBorderTop_1reoz_130",cellActiveDragBorderBottom:"_cellActiveDragBorderBottom_1reoz_134",cellActiveDragBorderLeft:"_cellActiveDragBorderLeft_1reoz_138",cellActiveDragBorderRight:"_cellActiveDragBorderRight_1reoz_142",selectionHintBar:"_selectionHintBar_1reoz_147",selectionHintChip:"_selectionHintChip_1reoz_157",emptySheet:"_emptySheet_1reoz_172",bufferColumnHeader:"_bufferColumnHeader_1reoz_184",bufferColumnCell:"_bufferColumnCell_1reoz_196",bufferRow:"_bufferRow_1reoz_205",bufferRowHeader:"_bufferRowHeader_1reoz_209",bufferRowCell:"_bufferRowCell_1reoz_221"},Eh=({matrix:e,range:t,isSelecting:n=!1,onRangeSelect:s,className:a})=>{const[o,i]=u.useState(null),[l,c]=u.useState(null),[d,h]=u.useState(null),p=u.useMemo(()=>!e||e.length===0?0:Math.max(...e.map(k=>k?k.length:0),1),[e]),f=u.useMemo(()=>t?la(t):null,[t]),m=u.useMemo(()=>!o||!l?null:{minR:Math.min(o.r,l.r),maxR:Math.max(o.r,l.r),minC:Math.min(o.c,l.c),maxC:Math.max(o.c,l.c)},[o,l]),g=u.useCallback(()=>{if(o&&l){const k=Math.min(o.r,l.r),x=Math.max(o.r,l.r),I=Math.min(o.c,l.c),N=Math.max(o.c,l.c),_=`${St(I)}${k+1}`,T=`${St(N)}${x+1}`,w=`${_}:${T}`;s==null||s(w),i(null),c(null),h(null)}},[o,l,s]);u.useEffect(()=>{if(o)return window.addEventListener("mouseup",g),()=>window.removeEventListener("mouseup",g)},[o,g]);const b=(k,x,I)=>{if(I.button!==0)return;if(I.preventDefault(),d&&!o){const T=Math.min(d.r,k),w=Math.max(d.r,k),M=Math.min(d.c,x),$=Math.max(d.c,x),A=`${St(M)}${T+1}:${St($)}${w+1}`;s==null||s(A),h(null);return}i({r:k,c:x}),c({r:k,c:x}),h({r:k,c:x});const N=`${St(x)}${k+1}`,_=`${N}:${N}`;s==null||s(_)},y=(k,x)=>{o&&c({r:k,c:x})};if(!e||e.length===0)return r.jsx("div",{className:`${ze.emptySheet} ${a||""}`,children:r.jsx("span",{children:"No sheet data loaded. Link a Google Sheet in the drawer."})});const S=Array.from({length:p},(k,x)=>St(x)),v=o!==null;return r.jsxs("div",{className:`${ze.container} ${a||""}`,tabIndex:-1,children:[n&&r.jsx("div",{className:ze.selectionHintBar,children:r.jsx("div",{className:ze.selectionHintChip,children:r.jsx("span",{children:"🎯 Click and drag across the sheet to highlight your cell range"})})}),r.jsxs("table",{className:ze.table,"aria-label":"Full Google Sheet Spreadsheet Grid",children:[r.jsx("thead",{children:r.jsxs("tr",{children:[r.jsx("th",{className:ze.cornerCell,"aria-label":"Row / Column Index"}),S.map((k,x)=>r.jsx("th",{className:ze.headerCell,scope:"col",children:k},x)),r.jsx("th",{className:ze.bufferColumnHeader,"aria-hidden":"true"})]})}),r.jsxs("tbody",{children:[e.map((k,x)=>r.jsxs("tr",{children:[r.jsx("th",{className:ze.rowNumberCell,scope:"row",children:x+1}),S.map((I,N)=>{const _=k?k[N]:void 0;let T=!1,w=!1,M=!1,$=!1,A=!1;if(!v&&f){const{startCol:j,startRow:z,endCol:O,endRow:U}=f,Q=typeof U=="number"?U:e.length-1,se=Math.min(z,Q),ae=Math.max(z,Q),de=Math.min(j,O),B=Math.max(j,O);x>=se&&x<=ae&&N>=de&&N<=B&&(T=!0,w=x===se,M=x===ae,$=N===de,A=N===B)}let P=!1,V=!1,D=!1,W=!1,H=!1;if(m){const{minR:j,maxR:z,minC:O,maxC:U}=m;x>=j&&x<=z&&N>=O&&N<=U&&(P=!0,V=x===j,D=x===z,W=N===O,H=N===U)}const q=[ze.dataCell,n?ze.dataCellSelecting:"",T&&!P?ze.cellSelected:"",T&&w&&!P?ze.cellBorderTop:"",T&&M&&!P?ze.cellBorderBottom:"",T&&$&&!P?ze.cellBorderLeft:"",T&&A&&!P?ze.cellBorderRight:"",P?ze.cellActiveDrag:"",V?ze.cellActiveDragBorderTop:"",D?ze.cellActiveDragBorderBottom:"",W?ze.cellActiveDragBorderLeft:"",H?ze.cellActiveDragBorderRight:""].filter(Boolean).join(" ");return r.jsx("td",{className:q,onMouseDown:j=>b(x,N,j),onMouseEnter:()=>y(x,N),title:`Cell ${St(N)}${x+1}`,children:_==null||_===""?r.jsx("span",{className:ze.nullCell,children:"—"}):String(_)},N)}),r.jsx("td",{className:ze.bufferColumnCell,"aria-hidden":"true"})]},x)),r.jsxs("tr",{className:ze.bufferRow,children:[r.jsx("th",{className:ze.bufferRowHeader,"aria-hidden":"true"}),r.jsx("td",{colSpan:S.length+1,className:ze.bufferRowCell,"aria-hidden":"true"})]})]})]})]})},re={formGroup:"_formGroup_1iatw_217",label:"_label_1iatw_223",input:"_input_1iatw_297",select:"_select_1iatw_298",checkboxLabel:"_checkboxLabel_1iatw_528",checkbox:"_checkbox_1iatw_528",twoColRow:"_twoColRow_1iatw_548",titlesSection:"_titlesSection_1iatw_564",sectionBlock:"_sectionBlock_1iatw_565",sectionHeader:"_sectionHeader_1iatw_572",sectionEyebrow:"_sectionEyebrow_1iatw_579",spinner:"_spinner_1iatw_616",seriesSwatch:"_seriesSwatch_1iatw_696",draggableRowLabel:"_draggableRowLabel_1iatw_704",draggableRowText:"_draggableRowText_1iatw_718",draggableColLetter:"_draggableColLetter_1iatw_727",saveButton:"_saveButton_1iatw_943",companionChartViewport:"_companionChartViewport_1iatw_1178"},zv=({barOrientation:e,setBarOrientation:t,stacked:n,setStacked:s})=>r.jsxs("div",{className:re.twoColRow,children:[r.jsxs("div",{className:re.formGroup,children:[r.jsx("label",{className:re.label,htmlFor:"cfg-orientation",children:r.jsx("span",{children:"Orientation"})}),r.jsxs("select",{id:"cfg-orientation",className:re.select,value:e,onChange:a=>t(a.target.value),children:[r.jsx("option",{value:"vertical",children:"Vertical Columns"}),r.jsx("option",{value:"horizontal",children:"Horizontal Bars"})]})]}),r.jsxs("div",{className:re.formGroup,children:[r.jsx("label",{className:re.label,htmlFor:"cfg-series-mode",children:r.jsx("span",{children:"Grouping Mode"})}),r.jsxs("select",{id:"cfg-series-mode",className:re.select,value:n?"stacked":"clustered",onChange:a=>s(a.target.value==="stacked"),children:[r.jsx("option",{value:"clustered",children:"Clustered (Side by Side)"}),r.jsx("option",{value:"stacked",children:"Stacked"})]})]})]}),Gv=({curveInterpolation:e,setCurveInterpolation:t,markerSize:n,setMarkerSize:s,showAreaFill:a,setShowAreaFill:o,startAtZero:i,setStartAtZero:l,setAutoScaleY:c})=>r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:re.twoColRow,children:[r.jsxs("div",{className:re.formGroup,children:[r.jsx("label",{className:re.label,htmlFor:"cfg-line-style",children:r.jsx("span",{children:"Line Interpolation"})}),r.jsxs("select",{id:"cfg-line-style",className:re.select,value:e,onChange:d=>t(d.target.value),children:[r.jsx("option",{value:"smooth",children:"Smooth Curve"}),r.jsx("option",{value:"straight",children:"Straight Lines"})]})]}),r.jsxs("div",{className:re.formGroup,children:[r.jsx("label",{className:re.label,htmlFor:"cfg-marker-size",children:r.jsx("span",{children:"Point Marker Size"})}),r.jsxs("select",{id:"cfg-marker-size",className:re.select,value:n,onChange:d=>s(d.target.value),children:[r.jsx("option",{value:"compact",children:"Small"}),r.jsx("option",{value:"regular",children:"Medium"}),r.jsx("option",{value:"prominent",children:"Large"})]})]})]}),r.jsx("div",{className:re.formGroup,children:r.jsxs("label",{htmlFor:"cfg-line-area-fill",className:re.checkboxLabel,children:[r.jsx("input",{id:"cfg-line-area-fill",type:"checkbox",className:re.checkbox,checked:a,onChange:d=>o(d.target.checked)}),r.jsx("span",{children:"Shade area under line"})]})}),r.jsx("div",{className:re.formGroup,children:r.jsxs("label",{htmlFor:"cfg-line-start-at-zero",className:re.checkboxLabel,children:[r.jsx("input",{id:"cfg-line-start-at-zero",type:"checkbox",className:re.checkbox,checked:i,onChange:d=>{const h=d.target.checked;l(h),c(!h)}}),r.jsx("span",{children:"Start vertical axis at zero"})]})})]}),Wv=({donutVariant:e,setDonutVariant:t})=>r.jsxs("div",{className:re.formGroup,children:[r.jsx("label",{className:re.label,htmlFor:"cfg-donut-variant",children:r.jsx("span",{children:"Display Variant"})}),r.jsxs("select",{id:"cfg-donut-variant",className:re.select,value:e,onChange:n=>t(n.target.value),children:[r.jsx("option",{value:"donut",children:"Donut Ring"}),r.jsx("option",{value:"pie",children:"Solid Pie"})]})]}),Hv=({curveInterpolation:e,setCurveInterpolation:t,showReferenceGuide:n,setShowReferenceGuide:s,showSummaryStats:a,setShowSummaryStats:o,showMedianMode:i,setShowMedianMode:l})=>r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:re.twoColRow,children:[r.jsx("div",{className:re.formGroup,children:r.jsxs("label",{htmlFor:"cfg-histogram-curve",className:re.checkboxLabel,children:[r.jsx("input",{id:"cfg-histogram-curve",type:"checkbox",className:re.checkbox,checked:e==="smooth",onChange:c=>t(c.target.checked?"smooth":"none")}),r.jsx("span",{children:"Overlay Smooth Distribution Curve"})]})}),r.jsx("div",{className:re.formGroup,children:r.jsxs("label",{htmlFor:"cfg-show-reference-guide",className:re.checkboxLabel,children:[r.jsx("input",{id:"cfg-show-reference-guide",type:"checkbox",className:re.checkbox,checked:n,onChange:c=>s(c.target.checked)}),r.jsx("span",{children:"Show Mean (Average) Reference Line"})]})})]}),r.jsxs("div",{className:re.twoColRow,children:[r.jsx("div",{className:re.formGroup,children:r.jsxs("label",{htmlFor:"cfg-show-summary-stats",className:re.checkboxLabel,children:[r.jsx("input",{id:"cfg-show-summary-stats",type:"checkbox",className:re.checkbox,checked:a,onChange:c=>o(c.target.checked)}),r.jsx("span",{children:"Show Summary Statistics Card"})]})}),r.jsx("div",{className:re.formGroup,children:r.jsxs("label",{htmlFor:"cfg-show-median-mode",className:re.checkboxLabel,children:[r.jsx("input",{id:"cfg-show-median-mode",type:"checkbox",className:re.checkbox,checked:i,onChange:c=>l(c.target.checked)}),r.jsx("span",{children:"Include Median & Mode"})]})})]})]}),Vv=({curveInterpolation:e,setCurveInterpolation:t,markerSize:n,setMarkerSize:s,loessBandwidth:a,setLoessBandwidth:o,showAreaFill:i,setShowAreaFill:l,showCorrelationChip:c,setShowCorrelationChip:d,showReferenceGuide:h,setShowReferenceGuide:p,startAtZero:f,setStartAtZero:m,setAutoScaleY:g,startAtZeroX:b,setStartAtZeroX:y,setAutoScaleX:S})=>r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:re.twoColRow,children:[r.jsxs("div",{className:re.formGroup,children:[r.jsx("label",{className:re.label,htmlFor:"cfg-scatter-trendline",children:r.jsx("span",{children:"Trendline (Regression)"})}),r.jsxs("select",{id:"cfg-scatter-trendline",className:re.select,value:e,onChange:v=>t(v.target.value),children:[r.jsx("option",{value:"none",children:"None (Points Only)"}),r.jsx("option",{value:"linear",children:"Linear Trendline"}),r.jsx("option",{value:"smooth",children:"Smooth LOESS Curve"}),r.jsx("option",{value:"polynomial",children:"Polynomial Curve"})]})]}),r.jsxs("div",{className:re.formGroup,children:[r.jsx("label",{className:re.label,htmlFor:"cfg-scatter-marker-size",children:r.jsx("span",{children:"Point Marker Size"})}),r.jsxs("select",{id:"cfg-scatter-marker-size",className:re.select,value:n,onChange:v=>s(v.target.value),children:[r.jsx("option",{value:"compact",children:"Small"}),r.jsx("option",{value:"regular",children:"Medium"}),r.jsx("option",{value:"prominent",children:"Large"})]})]})]}),e==="smooth"&&r.jsx("div",{children:r.jsx(wh,{id:"cfg-loess-bandwidth",label:"LOESS Curve Smoothness",value:a,min:.2,max:.8,step:.05,tiers:[{value:.25,label:"Responsive",sublabel:"Local dips and bumps"},{value:.5,label:"Balanced",sublabel:"Editorial balance"},{value:.75,label:"Broad",sublabel:"Sweeping macro trend"}],onChange:v=>o(v)})}),r.jsxs("div",{className:re.twoColRow,children:[(e==="linear"||e==="smooth"||e==="polynomial")&&r.jsx("div",{className:re.formGroup,children:r.jsxs("label",{htmlFor:"cfg-scatter-confidence",className:re.checkboxLabel,children:[r.jsx("input",{id:"cfg-scatter-confidence",type:"checkbox",className:re.checkbox,checked:i,onChange:v=>l(v.target.checked)}),r.jsx("span",{children:"Show Confidence Band (Shaded)"})]})}),r.jsx("div",{className:re.formGroup,children:r.jsxs("label",{htmlFor:"cfg-scatter-correlation",className:re.checkboxLabel,children:[r.jsx("input",{id:"cfg-scatter-correlation",type:"checkbox",className:re.checkbox,checked:c,onChange:v=>d(v.target.checked)}),r.jsx("span",{children:"Show Correlation (r) Badge"})]})})]}),r.jsx("div",{className:re.formGroup,children:r.jsxs("label",{htmlFor:"cfg-scatter-crosshairs",className:re.checkboxLabel,children:[r.jsx("input",{id:"cfg-scatter-crosshairs",type:"checkbox",className:re.checkbox,checked:h,onChange:v=>p(v.target.checked)}),r.jsx("span",{children:"Show Mean Quadrant Crosshairs"})]})}),r.jsxs("div",{className:re.twoColRow,children:[r.jsx("div",{className:re.formGroup,children:r.jsxs("label",{htmlFor:"cfg-scatter-start-at-zero-y",className:re.checkboxLabel,children:[r.jsx("input",{id:"cfg-scatter-start-at-zero-y",type:"checkbox",className:re.checkbox,checked:f,onChange:v=>{const k=v.target.checked;m(k),g(!k)}}),r.jsx("span",{children:"Start Vertical (Y) Axis at Zero"})]})}),r.jsx("div",{className:re.formGroup,children:r.jsxs("label",{htmlFor:"cfg-scatter-start-at-zero-x",className:re.checkboxLabel,children:[r.jsx("input",{id:"cfg-scatter-start-at-zero-x",type:"checkbox",className:re.checkbox,checked:b,onChange:v=>{const k=v.target.checked;y(k),S(!k)}}),r.jsx("span",{children:"Start Horizontal (X) Axis at Zero"})]})})]})]}),qv=({titleOverride:e,setTitleOverride:t,subtitleOverride:n,setSubtitleOverride:s,xLabel:a="",setXLabel:o,yLabel:i="",setYLabel:l,chartType:c})=>{const d=c!=="donut";return r.jsxs("div",{className:re.titlesSection,children:[r.jsxs("div",{className:re.formGroup,children:[r.jsx("label",{className:re.label,htmlFor:"cfg-title",children:r.jsx("span",{children:"Chart Title"})}),r.jsx("input",{id:"cfg-title",type:"text",className:re.input,placeholder:"Leave blank to use default sheet title",value:e,onChange:h=>t(h.target.value)})]}),r.jsxs("div",{className:re.formGroup,children:[r.jsx("label",{className:re.label,htmlFor:"cfg-subtitle",children:r.jsx("span",{children:"Subtitle / Description"})}),r.jsx("input",{id:"cfg-subtitle",type:"text",className:re.input,placeholder:"Summary of metrics, timeline, or scope",value:n,onChange:h=>s(h.target.value)})]}),d&&o&&l&&r.jsxs("div",{className:re.twoColRow,children:[r.jsxs("div",{className:re.formGroup,children:[r.jsx("label",{className:re.label,htmlFor:"cfg-xlabel",children:r.jsx("span",{children:"X-Axis Label (Horizontal)"})}),r.jsx("input",{id:"cfg-xlabel",type:"text",className:re.input,placeholder:"e.g. Period, Category",value:a,onChange:h=>o(h.target.value)})]}),r.jsxs("div",{className:re.formGroup,children:[r.jsx("label",{className:re.label,htmlFor:"cfg-ylabel",children:r.jsx("span",{children:"Y-Axis Label (Vertical)"})}),r.jsx("input",{id:"cfg-ylabel",type:"text",className:re.input,placeholder:"e.g. Enrolled Learners, %",value:i,onChange:h=>l(h.target.value)})]})]})]})},jv=({effectiveScatterX:e,setScatterXColIndex:t,effectiveScatterY:n,setScatterYColIndex:s,effectiveScatterLabel:a,setScatterLabelColIndex:o,scatterGroupColIndex:i,setScatterGroupColIndex:l,detectedColumns:c})=>r.jsxs(r.Fragment,{children:[r.jsxs(Dt,{name:"chart-data",title:"Axes Mapping",defaultOpen:!0,children:[r.jsx(nr,{id:"cfg-scatter-x-col",label:"X-Axis Metric (Horizontal)",value:e,onChange:d=>t(d),columns:c.map(d=>({index:d.index,label:d.label,type:"number"}))}),r.jsx(nr,{id:"cfg-scatter-y-col",label:"Y-Axis Metric (Vertical)",value:n,onChange:d=>s(d),columns:c.map(d=>({index:d.index,label:d.label,type:"number"}))})]}),r.jsxs(Dt,{name:"chart-data",title:"Point Labels & Grouping",defaultOpen:!1,children:[r.jsx(nr,{id:"cfg-scatter-label-col",label:"Point Tooltip Label",value:a,onChange:d=>o(d),columns:c.map(d=>({index:d.index,label:d.label,type:"text"}))}),r.jsx(nr,{id:"cfg-scatter-group-col",label:"Grouping Category (Color)",value:i??-1,onChange:d=>l(d>=0?d:void 0),columns:[{index:-1,label:"Single Color",type:"text"},...c.map(d=>({index:d.index,label:d.label,type:"text"}))]})]})]}),Kv=({chartType:e,categoryColIndex:t,setCategoryColIndex:n,detectedColumns:s,includedSeriesIndices:a,setIncludedSeriesIndices:o,binStrategy:i,setBinStrategy:l,customBinMode:c,setCustomBinMode:d,bucketSize:h,setBucketSize:p,binCount:f,setBinCount:m,histogramYMode:g,setHistogramYMode:b,groupOthers:y,setGroupOthers:S,sortField:v,setSortField:k,accentColor:x,handleToggleSeries:I})=>{var N;return r.jsxs(r.Fragment,{children:[r.jsx(Dt,{name:"chart-data",title:e==="line"?"Category / Date (X-Axis)":e==="donut"?"Slice Categories":e==="histogram"?"Values to Group (X-Axis)":"Category (X-Axis)",defaultOpen:!0,children:r.jsx(nr,{id:"cfg-category-col",label:"Source Column",value:t,onChange:_=>{if(n(_),e==="donut"){const T=s.filter(w=>w.index!==_);a!=null&&a.includes(_)&&o(T.length>0?[T[0].index]:[])}else a!=null&&a.includes(_)&&o(a.filter(T=>T!==_))},columns:s.map(_=>({index:_.index,label:_.label,type:e==="histogram"?"number":"text"}))})}),e==="histogram"&&r.jsxs(Dt,{name:"chart-data",title:"Binning & Distribution",defaultOpen:!1,children:[i==="custom"?r.jsxs("div",{className:re.twoColRow,children:[r.jsxs("div",{className:re.formGroup,children:[r.jsx("label",{className:re.label,htmlFor:"cfg-bin-strategy",children:r.jsx("span",{children:"Grouping Method"})}),r.jsxs("select",{id:"cfg-bin-strategy",className:re.select,value:i,onChange:_=>l(_.target.value),children:[r.jsx("option",{value:"auto",children:"Automatic Best Fit"}),r.jsx("option",{value:"custom",children:"Custom Ranges"})]})]}),r.jsxs("div",{className:re.formGroup,children:[r.jsx("label",{className:re.label,htmlFor:"cfg-custom-bin-mode",children:r.jsx("span",{children:"Custom Range By"})}),r.jsxs("select",{id:"cfg-custom-bin-mode",className:re.select,value:c,onChange:_=>d(_.target.value),children:[r.jsx("option",{value:"step",children:"Range Size"}),r.jsx("option",{value:"count",children:"Number of Groups"})]})]})]}):r.jsxs("div",{className:re.formGroup,children:[r.jsx("label",{className:re.label,htmlFor:"cfg-bin-strategy",children:r.jsx("span",{children:"Grouping Method"})}),r.jsxs("select",{id:"cfg-bin-strategy",className:re.select,value:i,onChange:_=>l(_.target.value),children:[r.jsx("option",{value:"auto",children:"Automatic Best Fit"}),r.jsx("option",{value:"custom",children:"Custom Ranges"})]})]}),i==="custom"&&r.jsxs("div",{className:re.formGroup,children:[r.jsx("label",{className:re.label,htmlFor:c==="step"?"cfg-bucket-size":"cfg-bin-count",children:r.jsx("span",{children:c==="step"?"Range Size":"Number of Groups"})}),c==="step"?r.jsx("input",{id:"cfg-bucket-size",type:"number",className:re.input,min:1,step:1,value:h,onChange:_=>{const T=_.target.value;if(T==="")p("");else{const w=parseInt(T,10);p(isNaN(w)?"":w)}},onBlur:()=>{(h===""||h<1)&&p(1)}}):r.jsx("input",{id:"cfg-bin-count",type:"number",className:re.input,min:2,max:50,step:1,value:f,onChange:_=>{const T=_.target.value;if(T==="")m("");else{const w=parseInt(T,10);m(isNaN(w)?"":w)}},onBlur:()=>{f===""||f<2?m(2):f>50&&m(50)}})]}),r.jsx("div",{className:re.formGroup,children:r.jsxs("label",{htmlFor:"cfg-histogram-ymode",className:re.checkboxLabel,children:[r.jsx("input",{id:"cfg-histogram-ymode",type:"checkbox",className:re.checkbox,checked:g==="relative",onChange:_=>b(_.target.checked?"relative":"frequency")}),r.jsx("span",{children:"Show as Percentage instead of Count"})]})})]}),e==="donut"?r.jsxs(Dt,{name:"chart-data",title:"Slice Values",defaultOpen:!1,children:[r.jsx(nr,{id:"cfg-donut-metric-col",label:"Slice Values (Metric)",value:a&&a.length>0?a[0]:((N=s.find(_=>_.index!==t))==null?void 0:N.index)??1,onChange:_=>{o([_]);const T=s.find(w=>w.index===_);T&&v!=="sheet"&&v!=="category"&&k(T.label)},columns:s.filter(_=>_.index!==t).map(_=>({index:_.index,label:_.label,type:"number"}))}),r.jsx("div",{className:re.formGroup,children:r.jsxs("label",{htmlFor:"cfg-group-others",className:re.checkboxLabel,children:[r.jsx("input",{id:"cfg-group-others",type:"checkbox",className:re.checkbox,checked:y,onChange:_=>S(_.target.checked)}),r.jsx("span",{children:"Group smaller slices into 'Other' (Top 5)"})]})})]}):s.filter(_=>_.index!==t).length>0&&(()=>{const _=s.filter(A=>A.index!==t),T=_.map(A=>A.index),w=a??T,M=[..._].sort((A,P)=>{const V=w.indexOf(A.index),D=w.indexOf(P.index);return V!==-1&&D!==-1?V-D:V!==-1?-1:D!==-1?1:A.index-P.index}),$=es({count:_.length,accentColor:x,tierMode:"bright"});return r.jsx(Dt,{name:"chart-data",title:e==="histogram"?"Subgroup Frequencies":"Metric Series (Y-Axis)",defaultOpen:!1,badge:r.jsxs("span",{className:re.seriesCountBadge,children:[w.length," / ",_.length]}),children:r.jsx("div",{className:re.formGroup,children:r.jsx(_h,{items:M,keyExtractor:A=>A.index,showMicroArrows:!1,onReorder:A=>{const P=A.filter(V=>w.includes(V.index)).map(V=>V.index);o(P)},renderItem:(A,P)=>{const V=w.includes(A.index),D=$[P.index]||"var(--folio-primary)";return r.jsxs("label",{className:re.draggableRowLabel,children:[r.jsx("input",{type:"checkbox",className:re.checkbox,checked:V,onChange:()=>I(A.index)}),r.jsx("span",{className:re.seriesSwatch,style:{backgroundColor:D}}),r.jsxs("span",{className:re.draggableRowText,children:[A.label," ",r.jsxs("span",{className:re.draggableColLetter,children:["[",St(A.index),"]"]})]})]})}})})})})()]})},gn={sortingGrid:"_sortingGrid_4c2fd_1",formGroup:"_formGroup_4c2fd_7",label:"_label_4c2fd_13",selectWrapper:"_selectWrapper_4c2fd_20",select:"_select_4c2fd_20"},Lh=({sortField:e,sortDirection:t,categoryLabel:n="Category Name",seriesOptions:s=[],onSortFieldChange:a,onSortDirectionChange:o,className:i=""})=>r.jsxs("div",{className:`${gn.sortingGrid} ${i}`.trim(),children:[r.jsxs("div",{className:gn.formGroup,children:[r.jsx("label",{htmlFor:"cfg-sort-field",className:gn.label,children:"Sort By"}),r.jsx("div",{className:gn.selectWrapper,children:r.jsxs("select",{id:"cfg-sort-field",className:gn.select,value:e,onChange:l=>a(l.target.value),children:[r.jsx("option",{value:"sheet",children:"Original Sheet Order"}),r.jsx("option",{value:"category",children:n}),s.map(l=>r.jsx("option",{value:l.id,children:l.name},l.id))]})})]}),r.jsxs("div",{className:gn.formGroup,children:[r.jsx("label",{htmlFor:"cfg-sort-dir",className:gn.label,children:"Sort Order"}),r.jsx("div",{className:gn.selectWrapper,children:r.jsxs("select",{id:"cfg-sort-dir",className:gn.select,value:t,onChange:l=>o(l.target.value),children:[r.jsx("option",{value:"asc",children:"Lowest to Highest"}),r.jsx("option",{value:"desc",children:"Highest to Lowest"})]})})]})]}),Yv=({chartType:e,sortBy:t,setSortBy:n,sortField:s,setSortField:a,sortDirection:o,setSortDirection:i,categoryColIndex:l,detectedColumns:c})=>{const d=e==="donut"?r.jsxs("div",{className:re.formGroup,children:[r.jsx("label",{className:re.label,htmlFor:"cfg-donut-sort",children:r.jsx("span",{children:"Slice Order"})}),r.jsxs("div",{className:re.twoColRow,children:[r.jsxs("select",{id:"cfg-donut-sort",className:re.select,value:t==="none"?"sheet":"value",onChange:h=>{h.target.value==="sheet"?(n("none"),a("sheet")):(n(o==="desc"?"desc":"asc"),a("value"))},children:[r.jsx("option",{value:"value",children:"Largest Slices First (Clockwise)"}),r.jsx("option",{value:"sheet",children:"Original Sheet Order"})]}),r.jsxs("select",{id:"cfg-donut-sort-dir",className:re.select,value:o,onChange:h=>{const p=h.target.value;i(p),t!=="none"&&n(p==="desc"?"desc":"asc")},disabled:t==="none",children:[r.jsx("option",{value:"desc",children:"Highest to Lowest"}),r.jsx("option",{value:"asc",children:"Lowest to Highest"})]})]})]}):e==="scatter"?r.jsxs("div",{className:re.formGroup,children:[r.jsx("label",{className:re.label,htmlFor:"cfg-scatter-sort",children:r.jsx("span",{children:"Sort Points By"})}),r.jsxs("div",{className:re.twoColRow,children:[r.jsxs("select",{id:"cfg-scatter-sort",className:re.select,value:s,onChange:h=>{const p=h.target.value;a(p),n(p==="sheet"?"none":o==="desc"?"desc":"asc")},children:[r.jsx("option",{value:"sheet",children:"Original Sheet Order"}),r.jsx("option",{value:"x",children:"Horizontal Axis (X)"}),r.jsx("option",{value:"y",children:"Vertical Axis (Y)"})]}),r.jsxs("select",{id:"cfg-scatter-sort-dir",className:re.select,value:o,onChange:h=>{const p=h.target.value;i(p),s!=="sheet"&&n(p==="desc"?"desc":"asc")},disabled:s==="sheet",children:[r.jsx("option",{value:"asc",children:"Lowest to Highest"}),r.jsx("option",{value:"desc",children:"Highest to Lowest"})]})]})]}):r.jsx(Lh,{sortField:s,sortDirection:o,categoryLabel:e==="histogram"?"Range Interval":"Category Name",seriesOptions:e==="histogram"?[{id:"frequency",name:"Group Count"}]:c.filter(h=>h.index!==l).map(h=>({id:h.label,name:`${h.label} [${St(h.index)}]`})),onSortFieldChange:h=>{a(h),n(h==="category"?o==="desc"?"category-desc":"category-asc":h==="sheet_order"||h==="sheet"?"none":o==="desc"?"desc":"asc")},onSortDirectionChange:h=>{i(h),n(s==="category"?h==="desc"?"category-desc":"category-asc":s==="sheet_order"||s==="sheet"?"none":h==="desc"?"desc":"asc")}});return r.jsxs("div",{className:re.sectionBlock,children:[r.jsx("div",{className:re.sectionHeader,children:r.jsx("span",{className:re.sectionEyebrow,children:"Data Order & Direction"})}),d]})},pt={stepPanel:"_stepPanel_1v17w_1",formGroup:"_formGroup_1v17w_20",label:"_label_1v17w_26",select:"_select_1v17w_36",subTabGroup:"_subTabGroup_1v17w_59",subTabButton:"_subTabButton_1v17w_70",subTabActive:"_subTabActive_1v17w_86",subTabPanel:"_subTabPanel_1v17w_98",subTabPanelHidden:"_subTabPanelHidden_1v17w_105",checkboxLabel:"_checkboxLabel_1v17w_109",checkbox:"_checkbox_1v17w_109"},Zv=({form:e,detectedColumns:t,accentColor:n,setupSubTab:s,setSetupSubTab:a,handleSubTabKeyDown:o,handleToggleSeries:i})=>{const{transpose:l,setTranspose:c,chartType:d,setChartType:h,barOrientation:p,setBarOrientation:f,stacked:m,setStacked:g,curveInterpolation:b,setCurveInterpolation:y,markerSize:S,setMarkerSize:v,showAreaFill:k,setShowAreaFill:x,startAtZero:I,setStartAtZero:N,setAutoScaleY:_,startAtZeroX:T,setStartAtZeroX:w,setAutoScaleX:M,donutVariant:$,setDonutVariant:A,showReferenceGuide:P,setShowReferenceGuide:V,showSummaryStats:D,setShowSummaryStats:W,showMedianMode:H,setShowMedianMode:q,loessBandwidth:j,setLoessBandwidth:z,showCorrelationChip:O,setShowCorrelationChip:U,titleOverride:Q,setTitleOverride:se,subtitleOverride:ae,setSubtitleOverride:de,xLabel:B,setXLabel:Y,yLabel:ee,setYLabel:X,scatterXColIndex:te,setScatterXColIndex:K,scatterYColIndex:J,setScatterYColIndex:Z,scatterLabelColIndex:ne,setScatterLabelColIndex:ie,scatterGroupColIndex:F,setScatterGroupColIndex:L,categoryColIndex:G,setCategoryColIndex:le,includedSeriesIndices:ue,setIncludedSeriesIndices:he,binStrategy:oe,setBinStrategy:ye,customBinMode:xe,setCustomBinMode:ke,bucketSize:Ze,setBucketSize:De,binCount:je,setBinCount:kt,histogramYMode:Bn,setHistogramYMode:Io,groupOthers:ar,setGroupOthers:$o,sortField:On,setSortField:ua,showValues:yn,setShowValues:ps,sortBy:or,setSortBy:Eo,sortDirection:ir,setSortDirection:Lo}=e,lr=typeof te=="number"?te:t.length>1?1:0,Mo=typeof J=="number"?J:t.length>2?2:t.length>1?1:0,Pn=typeof ne=="number"?ne:0;return r.jsxs("div",{className:pt.stepPanel,children:[r.jsxs("div",{className:pt.formGroup,children:[r.jsx("label",{className:pt.label,htmlFor:"cfg-chart-type",children:r.jsx("span",{children:"Chart Type"})}),r.jsxs("select",{id:"cfg-chart-type",className:pt.select,value:d,onChange:ms=>h(ms.target.value),children:[r.jsx("option",{value:"bar",children:"Bar Chart"}),r.jsx("option",{value:"line",children:"Line Chart"}),r.jsx("option",{value:"donut",children:"Donut Chart"}),r.jsx("option",{value:"scatter",children:"Scatter Plot"}),r.jsx("option",{value:"histogram",children:"Histogram"})]})]}),r.jsxs("div",{className:pt.subTabGroup,role:"tablist","aria-label":"Chart Setup Sections",onKeyDown:o,children:[r.jsx("button",{id:"setup-tab-data",role:"tab",type:"button","aria-selected":s==="data","aria-controls":"setup-panel-data",tabIndex:s==="data"?0:-1,className:`${pt.subTabButton} ${s==="data"?pt.subTabActive:""}`,onClick:()=>a("data"),children:"Data"}),r.jsx("button",{id:"setup-tab-style",role:"tab",type:"button","aria-selected":s==="style","aria-controls":"setup-panel-style",tabIndex:s==="style"?0:-1,className:`${pt.subTabButton} ${s==="style"?pt.subTabActive:""}`,onClick:()=>a("style"),children:"Appearance"})]}),r.jsxs("div",{id:"setup-panel-data",role:"tabpanel","aria-labelledby":"setup-tab-data",className:`${pt.subTabPanel} ${s!=="data"?pt.subTabPanelHidden:""}`,hidden:s!=="data",children:[r.jsx(Dt,{name:"chart-data",title:"Table Orientation",defaultOpen:!1,children:r.jsx("div",{className:pt.formGroup,children:r.jsxs("label",{className:pt.checkboxLabel,children:[r.jsx("input",{type:"checkbox",className:pt.checkbox,checked:l,onChange:ms=>c(ms.target.checked)}),r.jsx("span",{children:"Transpose data: Swap rows and columns"})]})})}),d==="scatter"?r.jsx(jv,{effectiveScatterX:lr,setScatterXColIndex:K,effectiveScatterY:Mo,setScatterYColIndex:Z,effectiveScatterLabel:Pn,setScatterLabelColIndex:ie,scatterGroupColIndex:F,setScatterGroupColIndex:L,detectedColumns:t}):r.jsx(Kv,{chartType:d,categoryColIndex:G,setCategoryColIndex:le,detectedColumns:t,includedSeriesIndices:ue,setIncludedSeriesIndices:he,binStrategy:oe,setBinStrategy:ye,customBinMode:xe,setCustomBinMode:ke,bucketSize:Ze,setBucketSize:De,binCount:je,setBinCount:kt,histogramYMode:Bn,setHistogramYMode:Io,groupOthers:ar,setGroupOthers:$o,sortField:On,setSortField:ua,accentColor:n,handleToggleSeries:i})]}),r.jsxs("div",{id:"setup-panel-style",role:"tabpanel","aria-labelledby":"setup-tab-style",className:`${pt.subTabPanel} ${s!=="style"?pt.subTabPanelHidden:""}`,hidden:s!=="style",children:[r.jsx(Dt,{name:"chart-appearance",title:"Titles & Axis Labels",defaultOpen:!0,children:r.jsx(qv,{titleOverride:Q,setTitleOverride:se,subtitleOverride:ae,setSubtitleOverride:de,xLabel:B,setXLabel:Y,yLabel:ee,setYLabel:X,chartType:d})}),r.jsxs(Dt,{name:"chart-appearance",title:"Geometry & Visual Style",defaultOpen:!1,children:[d==="bar"&&r.jsx(zv,{barOrientation:p,setBarOrientation:f,stacked:m,setStacked:g}),d==="line"&&r.jsx(Gv,{curveInterpolation:b,setCurveInterpolation:y,markerSize:S,setMarkerSize:v,showAreaFill:k,setShowAreaFill:x,startAtZero:I,setStartAtZero:N,setAutoScaleY:_}),d==="donut"&&r.jsx(Wv,{donutVariant:$,setDonutVariant:A}),d==="histogram"&&r.jsx(Hv,{curveInterpolation:b,setCurveInterpolation:y,showReferenceGuide:P,setShowReferenceGuide:V,showSummaryStats:D,setShowSummaryStats:W,showMedianMode:H,setShowMedianMode:q}),d==="scatter"&&r.jsx(Vv,{curveInterpolation:b,setCurveInterpolation:y,markerSize:S,setMarkerSize:v,loessBandwidth:j,setLoessBandwidth:z,showAreaFill:k,setShowAreaFill:x,showCorrelationChip:O,setShowCorrelationChip:U,showReferenceGuide:P,setShowReferenceGuide:V,startAtZero:I,setStartAtZero:N,setAutoScaleY:_,startAtZeroX:T,setStartAtZeroX:w,setAutoScaleX:M})]}),(d==="bar"||d==="line"||d==="donut")&&r.jsxs(Dt,{name:"chart-appearance",title:"Data Labels",defaultOpen:!1,children:[d==="bar"&&r.jsx(So,{id:"cfg-show-values-bar-app",checked:yn,onChange:ps,label:"Show numbers on bars"}),d==="line"&&r.jsx(So,{id:"cfg-show-values-line-app",checked:yn,onChange:ps,label:"Show numbers on points"}),d==="donut"&&r.jsx(So,{id:"cfg-show-values-donut-app",checked:yn,onChange:ps,label:"Show percentages or values on slices"})]}),r.jsx(Dt,{name:"chart-appearance",title:"Order & Direction",defaultOpen:!1,children:r.jsx(Yv,{chartType:d,sortBy:or,setSortBy:Eo,sortField:On,setSortField:ua,sortDirection:ir,setSortDirection:Lo,categoryColIndex:G,detectedColumns:t})})]})]})},nc=({isOpen:e,onClose:t,chartId:n,nodeId:s,initialConfig:a,previewMatrix:o,onDeployed:i,mode:l="edit"})=>{const[c,d]=u.useState(1),[h,p]=u.useState("data"),[f,m]=u.useState(!1),[g,b]=u.useState(!1),[y,S]=u.useState(!1),[v,k]=u.useState(null),{showToast:x}=Oe(),I=u.useRef(!1),N=u.useRef(null),_=Ov(a);eo(e&&_.hasUnsavedChanges,`chart-config-${n}`);const T=Pv({sheetUrl:_.sheetUrl,tabName:_.tabName,sheetGid:_.sheetGid,initialConfig:a,setTabName:_.setTabName,setSheetGid:_.setSheetGid,setLastModifiedTime:_.setLastModifiedTime,onAutoSelectTab:(K,J)=>{_.setSavedSnapshot(Z=>Z.sheetUrl===_.sheetUrl.trim()&&!Z.tabName?{...Z,tabName:K,sheetGid:J}:Z)}}),w=Fv({sheetUrl:_.sheetUrl,tabName:_.tabName,sheetGid:_.sheetGid,range:_.range,previewMatrix:o||(a==null?void 0:a.cachedDataset)||void 0});u.useEffect(()=>{e&&(!I.current||N.current!==n)&&(d(1),p("data"),_.resetForm(a),T.resetVerification(a==null?void 0:a.sheetUrl,a==null?void 0:a.tabName,a==null?void 0:a.sheetGid)),I.current=e,N.current=n},[e,n,a,_,T]);const M=u.useRef(_.tabName),$=u.useRef(!1);u.useEffect(()=>{_.tabName!==M.current&&(M.current=_.tabName,$.current=!1)},[_.tabName]),u.useEffect(()=>{if(!w.detectedRange)return;const K=!!(a!=null&&a.range&&a.range.trim()!==""&&a.range.trim()!=="A1:D6"&&(!a.tabName||a.tabName===_.tabName));$.current||(!K||l==="add"||_.tabName!==(a==null?void 0:a.tabName))&&_.setRange(w.detectedRange)},[w.detectedRange,a,_,l]);const A=K=>{var ne,ie,F,L;const J=["data","style"],Z=J.indexOf(h);if(K.key==="ArrowRight"){K.preventDefault();const G=J[(Z+1)%J.length];p(G),(ne=document.getElementById(`setup-tab-${G}`))==null||ne.focus()}else if(K.key==="ArrowLeft"){K.preventDefault();const G=J[(Z-1+J.length)%J.length];p(G),(ie=document.getElementById(`setup-tab-${G}`))==null||ie.focus()}else K.key==="Home"?(K.preventDefault(),p("data"),(F=document.getElementById("setup-tab-data"))==null||F.focus()):K.key==="End"&&(K.preventDefault(),p("style"),(L=document.getElementById("setup-tab-style"))==null||L.focus())},P=u.useMemo(()=>!w.liveMatrix||w.liveMatrix.length===0?w.liveMatrix:_.transpose?$h(w.liveMatrix):w.liveMatrix,[w.liveMatrix,_.transpose]),V=u.useMemo(()=>((P.length>0?P:o||[])[0]||[]).map((Z,ne)=>({index:ne,label:Z!=null&&String(Z).trim()!==""?String(Z).trim():`Col ${ne+1}`})),[P,o]),D=u.useCallback(K=>{const J=V.filter(ne=>ne.index!==_.categoryColIndex).map(ne=>ne.index),Z=_.includedSeriesIndices??J;Z.includes(K)?Z.length>1&&_.setIncludedSeriesIndices(Z.filter(ne=>ne!==K)):_.setIncludedSeriesIndices([...Z,K])},[V,_]),H=!!u.useMemo(()=>la(_.range),[_.range]),q=u.useCallback(K=>K===1?!0:K===2?T.isStep1Valid&&H:!1,[T.isStep1Valid,H]),j=sh[s]||"var(--folio-primary)",z=typeof _.scatterXColIndex=="number"?_.scatterXColIndex:V.length>1?1:0,O=typeof _.scatterYColIndex=="number"?_.scatterYColIndex:V.length>2?2:V.length>1?1:0,U=typeof _.scatterLabelColIndex=="number"?_.scatterLabelColIndex:0,Q=u.useMemo(()=>{if(!w.liveMatrix||w.liveMatrix.length===0)return null;try{const K=w.liveMatrix.map(Z=>Z.map(ne=>ne==null?"":String(ne))),J=_.buildConfigPayload(n,s,z,O,U);return cs({chartId:n,title:_.titleOverride.trim()||"",subtitle:_.subtitleOverride.trim()||void 0,unit:_.unit.trim()||void 0,chartType:_.chartType,nodeId:s,visualConfig:J.visualConfig,rawMatrix:K})}catch{return null}},[w.liveMatrix,_,n,s,z,O,U]),se=u.useCallback(async()=>{if(!_.sheetUrl.trim()){k({message:"Please enter a Google Sheet URL first.",type:"error"});return}try{await T.executeVerification(_.sheetUrl),w.executeSync(),$.current=!1,k({message:"Google Sheet source and tabs resynced.",type:"info"})}catch{k({message:"Failed to resync Google Sheet source.",type:"error"})}},[_.sheetUrl,T,w]),ae=u.useCallback(async()=>{if(!_.sheetUrl.trim()){k({message:"Google Sheet URL is required.",type:"error"});return}if(!H){k({message:"Please provide a valid cell range such as A1:D6.",type:"error"});return}m(!0);const J={..._.buildConfigPayload(n,s,z,O,U),cachedDataset:w.liveMatrix&&w.liveMatrix.length>0?w.liveMatrix:w.fetchedMatrix&&w.fetchedMatrix.length>0?w.fetchedMatrix:a==null?void 0:a.cachedDataset};try{const Z=await is(J);Z.savedToCloud?(Rt(J),_.markAsSaved(J),k({message:"Chart configuration saved.",type:"success"}),i==null||i(J)):Z.savedLocally?(Rt(J),_.markAsSaved(J),i==null||i(J),k({message:ls(Z,"save"),type:Z.error?"error":"info"})):k({message:ls(Z,"save"),type:"error"})}catch(Z){k({message:ls(Z,"save"),type:"error"})}finally{m(!1)}},[_,n,s,H,z,O,U,w.liveMatrix,w.fetchedMatrix,a==null?void 0:a.cachedDataset,i]),de=u.useCallback(async()=>{if(!_.sheetUrl.trim()){k({message:"Google Sheet URL is required.",type:"error"});return}if(!H){k({message:"Please provide a valid cell range such as A5:D12.",type:"error"});return}b(!0);const J={..._.buildConfigPayload(n,s,z,O,U),cachedDataset:w.liveMatrix&&w.liveMatrix.length>0?w.liveMatrix:w.fetchedMatrix&&w.fetchedMatrix.length>0?w.fetchedMatrix:a==null?void 0:a.cachedDataset};try{const Z=await is(J);if(Z.savedToCloud){Rt(J),_.markAsSaved(J);const ne=l==="add"?"Chart added to canvas and saved to draft.":"Chart saved to draft successfully.";k({message:ne,type:"success"}),x(ne,"success"),i==null||i(J),t()}else Z.savedLocally&&(Rt(J),_.markAsSaved(J),i==null||i(J),t()),k({message:ls(Z,"deploy"),type:"error"})}catch(Z){k({message:ls(Z,"deploy"),type:"error"})}finally{b(!1)}},[_,n,s,H,z,O,U,w.liveMatrix,w.fetchedMatrix,a==null?void 0:a.cachedDataset,l,i,t,x]),B=u.useMemo(()=>({..._.buildConfigPayload(n,s,z,O,U),cachedDataset:w.liveMatrix&&w.liveMatrix.length>0?w.liveMatrix:a==null?void 0:a.cachedDataset}),[_,n,s,z,O,U,w.liveMatrix,a==null?void 0:a.cachedDataset]),Y=u.useMemo(()=>[{id:1,label:"Source & Range",badge:T.isStep1Valid&&H&&c!==1?"✓":"1",completed:T.isStep1Valid&&H},{id:2,label:"Chart Setup",badge:"2",disabled:!q(2)}],[c,T.isStep1Valid,H,q]),ee=u.useMemo(()=>{if(c===1){const K=w.fullMatrix&&w.fullMatrix.length>0?w.fullMatrix:P;return r.jsx(Eh,{matrix:K,range:_.range,isSelecting:y,onRangeSelect:J=>{$.current=!0,_.setRange(J)}})}return c===2?r.jsx("div",{className:re.companionChartViewport,children:r.jsx("div",{children:r.jsx(rc,{chartId:n,dataset:Q,config:B,nodeId:s,accentColor:j,editTriggerId:n,hideEditButton:!0,status:w.isSyncing?"syncing":Q?"success":"pending_data"})})}):null},[c,w.fullMatrix,P,_.range,_.setRange,y,n,Q,B,s,j,w.isSyncing]),X=r.jsx(r.Fragment,{children:c===1?r.jsx(me,{variant:"secondary",size:"sm",type:"button",onClick:t,children:"Cancel"}):r.jsx(me,{variant:"secondary",size:"sm",type:"button",onClick:()=>d(1),children:"← Back"})}),te=r.jsxs(r.Fragment,{children:[c===1&&r.jsxs(r.Fragment,{children:[_.hasUnsavedChanges&&r.jsx(me,{variant:"secondary",size:"sm",type:"button",className:re.saveButton,onClick:ae,disabled:f||!T.isStep1Valid||!H,children:f?r.jsxs(r.Fragment,{children:[r.jsx("span",{className:re.spinner,"aria-hidden":"true"}),r.jsx("span",{children:"Saving..."})]}):"Save"}),r.jsx(me,{variant:"primary",size:"sm",type:"button",disabled:!T.isStep1Valid||!H,onClick:()=>d(2),children:"Next: Chart Setup →"})]}),c===2&&r.jsxs(r.Fragment,{children:[_.hasUnsavedChanges&&r.jsx(me,{variant:"secondary",size:"sm",type:"button",className:re.saveButton,onClick:ae,disabled:f,children:f?r.jsxs(r.Fragment,{children:[r.jsx("span",{className:re.spinner,"aria-hidden":"true"}),r.jsx("span",{children:"Saving..."})]}):"Save Draft"}),r.jsx(me,{variant:"primary",size:"sm",type:"button",disabled:g||!T.isStep1Valid||!H,onClick:de,children:g?r.jsxs(r.Fragment,{children:[r.jsx("span",{className:re.spinner,"aria-hidden":"true"}),r.jsx("span",{children:"Deploying…"})]}):l==="add"?"Add to Canvas & Save ":"Save in Draft"})]})]});return r.jsxs(r.Fragment,{children:[r.jsxs(Vl,{isOpen:e,onClose:t,title:"Chart Setup",tabs:Y,activeTab:c,onTabChange:K=>{q(K)&&d(K)},footerLeft:X,footerRight:te,closeOnOutsideClick:!1,companionContent:ee,children:[c===1&&r.jsx(Uv,{sheetUrl:_.sheetUrl,setSheetUrl:_.setSheetUrl,accessStatus:T.accessStatus,statusMessage:T.statusMessage,discoveredTabs:T.discoveredTabs,tabName:_.tabName,sheetGid:_.sheetGid,setTabName:_.setTabName,executeVerification:T.executeVerification,handleTabChange:T.handleTabChange,onResync:se,isSyncing:w.isSyncing,range:_.range,isRangeValid:H,isSelectingRange:y,setIsSelectingRange:S,executeSync:w.executeSync}),c===2&&r.jsx(Zv,{form:_,detectedColumns:V,accentColor:j,setupSubTab:h,setSetupSubTab:p,handleSubTabKeyDown:A,handleToggleSeries:D})]}),v&&r.jsx(Zt,{message:v.message,type:v.type,durationMs:v.type==="error"?5500:3500,onDismiss:()=>k(null)})]})},be={modalCard:"_modalCard_hh7jb_8",header:"_header_hh7jb_28",headerInfo:"_headerInfo_hh7jb_37",title:"_title_hh7jb_44",subtitleRow:"_subtitleRow_hh7jb_54",asOfCaption:"_asOfCaption_hh7jb_61",headerActions:"_headerActions_hh7jb_71",closeButton:"_closeButton_hh7jb_78",tableWrapper:"_tableWrapper_hh7jb_107",table:"_table_hh7jb_107",headerCell:"_headerCell_hh7jb_128",indexColHeader:"_indexColHeader_hh7jb_144",indexCell:"_indexCell_hh7jb_153",categoryCell:"_categoryCell_hh7jb_167",dataCell:"_dataCell_hh7jb_178",numCell:"_numCell_hh7jb_187",headerNumCell:"_headerNumCell_hh7jb_194",tableRow:"_tableRow_hh7jb_198",nullCell:"_nullCell_hh7jb_204",emptyState:"_emptyState_hh7jb_209"},Mh=({isOpen:e,onClose:t,dataset:n,title:s,asOfDate:a,onDownloadCsv:o})=>{if(!e)return null;const i=n.chartType==="scatter"&&n.scatterPoints&&n.scatterPoints.length>0,l=n.chartType==="histogram"&&n.bins&&n.bins.length>0,c=!!(n.categories&&n.categories.length>0&&n.series&&n.series.length>0),d=()=>{var h,p;if(i&&n.scatterPoints){const f=((h=n.visualConfig)==null?void 0:h.xLabel)||"X",m=((p=n.visualConfig)==null?void 0:p.yLabel)||"Y",g=n.scatterPoints.some(k=>!!k.group),b=g?4:3,y=g?34:40,S=(100-y)/(b-1),v=208+(b-1)*130;return r.jsxs("table",{className:be.table,style:{minWidth:`${v}px`},"aria-label":`Tabular data for ${s}`,children:[r.jsxs("colgroup",{children:[r.jsx("col",{style:{width:"48px"}}),r.jsx("col",{style:{width:`${y}%`}}),r.jsx("col",{style:{width:`${S}%`}}),r.jsx("col",{style:{width:`${S}%`}}),g&&r.jsx("col",{style:{width:`${S}%`}})]}),r.jsx("thead",{children:r.jsxs("tr",{children:[r.jsx("th",{className:`${be.headerCell} ${be.indexColHeader}`,scope:"col",children:"#"}),r.jsx("th",{className:be.headerCell,scope:"col",children:"Label"}),r.jsx("th",{className:`${be.headerCell} ${be.headerNumCell}`,scope:"col",children:f}),r.jsx("th",{className:`${be.headerCell} ${be.headerNumCell}`,scope:"col",children:m}),g&&r.jsx("th",{className:be.headerCell,scope:"col",children:"Group"})]})}),r.jsx("tbody",{children:n.scatterPoints.map((k,x)=>r.jsxs("tr",{className:be.tableRow,children:[r.jsx("td",{className:be.indexCell,children:x+1}),r.jsx("td",{className:be.categoryCell,title:k.label||"",children:k.label||"—"}),r.jsx("td",{className:`${be.dataCell} ${be.numCell}`,children:Number.isFinite(k.x)?k.x:"—"}),r.jsx("td",{className:`${be.dataCell} ${be.numCell}`,children:Number.isFinite(k.y)?k.y:"—"}),g&&r.jsx("td",{className:be.dataCell,children:k.group||"—"})]},x))})]})}if(l&&n.bins)return r.jsxs("table",{className:be.table,style:{minWidth:"398px"},"aria-label":`Tabular data for ${s}`,children:[r.jsxs("colgroup",{children:[r.jsx("col",{style:{width:"48px"}}),r.jsx("col",{style:{width:"55%"}}),r.jsx("col",{style:{width:"45%"}})]}),r.jsx("thead",{children:r.jsxs("tr",{children:[r.jsx("th",{className:`${be.headerCell} ${be.indexColHeader}`,scope:"col",children:"#"}),r.jsx("th",{className:be.headerCell,scope:"col",children:"Range (Bins)"}),r.jsx("th",{className:`${be.headerCell} ${be.headerNumCell}`,scope:"col",children:"Frequency Count"})]})}),r.jsx("tbody",{children:n.bins.map((m,g)=>r.jsxs("tr",{className:be.tableRow,children:[r.jsx("td",{className:be.indexCell,children:g+1}),r.jsx("td",{className:be.categoryCell,children:`${m.x0} – ${m.x1}`}),r.jsx("td",{className:`${be.dataCell} ${be.numCell}`,children:m.count})]},g))})]});if(c&&n.categories&&n.series){const f=n.categories,m=n.series,g=m.length,b=g<=2?34:g<=4?26:20,y=(100-b)/g,S=208+g*130;return r.jsxs("table",{className:be.table,style:{minWidth:`${S}px`},"aria-label":`Tabular data for ${s}`,children:[r.jsxs("colgroup",{children:[r.jsx("col",{style:{width:"48px"}}),r.jsx("col",{style:{width:`${b}%`}}),m.map((v,k)=>r.jsx("col",{style:{width:`${y}%`}},k))]}),r.jsx("thead",{children:r.jsxs("tr",{children:[r.jsx("th",{className:`${be.headerCell} ${be.indexColHeader}`,scope:"col",children:"#"}),r.jsx("th",{className:be.headerCell,scope:"col",children:"Category"}),m.map((v,k)=>r.jsx("th",{className:`${be.headerCell} ${be.headerNumCell}`,scope:"col",title:v.name||`Series ${k+1}`,children:v.name||`Series ${k+1}`},k))]})}),r.jsx("tbody",{children:f.map((v,k)=>r.jsxs("tr",{className:be.tableRow,children:[r.jsx("td",{className:be.indexCell,children:k+1}),r.jsx("td",{className:be.categoryCell,title:v||"",children:v||"—"}),m.map((x,I)=>{const N=x.data[k],_=N!=null&&Number.isFinite(N);return r.jsx("td",{className:`${be.dataCell} ${be.numCell}`,children:_?r.jsx("span",{children:N}):r.jsx("span",{className:be.nullCell,children:"—"})},I)})]},k))})]})}return r.jsx("div",{className:be.emptyState,children:r.jsx("p",{children:"No tabular data available for this chart visualization."})})};return r.jsxs(bt,{isOpen:e,onClose:t,cardClassName:be.modalCard,showCloseButton:!1,ariaLabel:`Data table for ${s}`,children:[r.jsxs("header",{className:be.header,children:[r.jsxs("div",{className:be.headerInfo,children:[r.jsx("h3",{className:be.title,children:s}),r.jsx("div",{className:be.subtitleRow,children:a&&r.jsxs("span",{className:be.asOfCaption,children:["As of ",a]})})]}),r.jsxs("div",{className:be.headerActions,children:[o&&r.jsx(me,{variant:"secondary",size:"xs",onClick:o,"aria-label":`Download CSV data for ${s}`,children:r.jsx("span",{children:"Download Data (CSV)"})}),r.jsx("button",{type:"button",className:be.closeButton,onClick:t,"aria-label":"Close data table modal",children:"✕"})]})]}),r.jsx("div",{className:be.tableWrapper,tabIndex:-1,children:d()})]})},ct={cardOuterWrapper:"_cardOuterWrapper_85koo_8",card:"_card_85koo_8",sideEditWrapper:"_sideEditWrapper_85koo_37",sideEditBtn:"_sideEditBtn_85koo_46",sideSyncBtn:"_sideSyncBtn_85koo_47",syncIcon:"_syncIcon_85koo_54",spinning:"_spinning_85koo_59",highlightedCard:"_highlightedCard_85koo_72",title:"_title_85koo_78",subtitle:"_subtitle_85koo_90",contentWrapper:"_contentWrapper_85koo_108",footer:"_footer_85koo_122",asOfCaption:"_asOfCaption_85koo_132",footerActions:"_footerActions_85koo_141",viewTableAction:"_viewTableAction_85koo_149",downloadAction:"_downloadAction_85koo_150"},rc=({chartId:e,dataset:t,config:n,nodeId:s="access",nodeTitle:a,accentColor:o,status:i,errorMessage:l,onConfigUpdated:c,onSync:d,isSyncing:h=!1,className:p,editTriggerId:f,hideEditButton:m=!1})=>{var O,U,Q;const{isDevMode:g,isDesktop:b}=Oe(),y=g&&b&&!m,[S,v]=u.useState(!1),[k,x]=u.useState(!1),[I,N]=u.useState(!1),_=h||i==="syncing"||I,[T,w]=u.useState(null),M=u.useCallback(async()=>{if(!_){if(!(n!=null&&n.sheetUrl)){w({message:"No Google Sheet linked yet. Opening drawer to configure...",type:"info"}),v(!0);return}N(!0);try{if(d)await d(),w({message:"Chart synced successfully from Google Sheet.",type:"success"});else{const se=await ec({sheetUrl:n.sheetUrl,tabName:n.tabName,sheetGid:n.sheetGid,range:n.range,timeoutMs:8e3});if(se&&se.length>0){const ae={...n,cachedDataset:se,updatedAt:new Date().toISOString()};await is(ae),xo(e,ae),c==null||c(ae),w({message:"Chart synced successfully from Google Sheet.",type:"success"})}else w({message:"Synced from Google Sheet, but no rows were found.",type:"info"})}}catch(se){const ae=se instanceof Error?se.message:"Failed to sync chart from Google Sheet.";w({message:ae,type:"error"})}finally{N(!1)}}},[_,n,d,e,c]),$=(n==null?void 0:n.titleOverride)||(t==null?void 0:t.title)||"",A=(n==null?void 0:n.subtitleOverride)||(t==null?void 0:t.subtitle),V=Rl((O=n==null?void 0:n.visualConfig)==null?void 0:O.lastModifiedTime)||Rl((U=t==null?void 0:t.visualConfig)==null?void 0:U.lastModifiedTime)||(t==null?void 0:t.asOfDate)||"Current SY",D=(n==null?void 0:n.unitOverride)||(t==null?void 0:t.unit)||((Q=t==null?void 0:t.visualConfig)==null?void 0:Q.unit),W=u.useMemo(()=>t?!!(t.categories&&t.categories.length>0||t.series&&t.series.length>0||t.scatterPoints&&t.scatterPoints.length>0||t.rawValues&&t.rawValues.length>0):!1,[t]),H=u.useMemo(()=>W?"none":i==="error"||l?"connection_error":n!=null&&n.sheetUrl?"data_format":"unlinked",[W,i,l,n==null?void 0:n.sheetUrl]),q=u.useCallback(()=>{var X,te,K;let se=t==null?void 0:t.sanitizedCsvContent;if(!se&&(t!=null&&t.categories)&&(t!=null&&t.series)&&(se=yh(t.categories,t.series,$,D)),!se)return;const ae=(n==null?void 0:n.tabName)||((X=n==null?void 0:n.visualConfig)==null?void 0:X.tabName)||((te=t==null?void 0:t.visualConfig)==null?void 0:te.tabName)||(n!=null&&n.range?(K=la(n.range))==null?void 0:K.sheetName:void 0),de=Cv({title:$,sheetName:ae,chartId:e}),B=new Blob([se],{type:"text/csv;charset=utf-8;"}),Y=URL.createObjectURL(B),ee=document.createElement("a");ee.setAttribute("href",Y),ee.setAttribute("download",de),document.body.appendChild(ee),ee.click(),document.body.removeChild(ee),URL.revokeObjectURL(Y)},[t,$,D,e,n]),[j,z]=u.useState(!1);return r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:ct.cardOuterWrapper,children:[r.jsxs("article",{className:`${ct.card} ${j?ct.highlightedCard:""} ${p||""}`,"aria-labelledby":`chart-title-${e}`,tabIndex:-1,children:[r.jsxs("header",{className:ct.header,children:[$&&r.jsx("h3",{id:`chart-title-${e}`,className:ct.title,children:$}),A&&r.jsx("p",{className:ct.subtitle,children:A})]}),r.jsx("div",{className:ct.contentWrapper,children:W&&t?r.jsx(mh,{dataset:t,accentColor:o}):r.jsx(gh,{chartId:e,nodeTitle:a,category:H,errorMessage:l,hasSheetUrl:!!(n!=null&&n.sheetUrl),onEdit:()=>v(!0)})}),W&&r.jsxs("footer",{className:ct.footer,children:[r.jsxs("span",{className:ct.asOfCaption,children:["As of ",V]}),r.jsxs("div",{className:ct.footerActions,children:[r.jsx(me,{variant:"secondary",size:"xs",className:ct.viewTableAction,onClick:()=>x(!0),"aria-label":`View data table for ${$}`,children:r.jsx("span",{children:"View Table"})}),r.jsx(me,{variant:"secondary",size:"xs",className:ct.downloadAction,onClick:q,"aria-label":`Download CSV data for ${$}`,children:r.jsx("span",{children:"Download Data (CSV)"})})]})]})]}),y&&r.jsxs("div",{className:ct.sideEditWrapper,children:[r.jsx(me,{type:"button",variant:"admin",size:"xs","data-dev-edit-trigger":"true","data-canvas-edit-trigger":f,onClick:()=>v(!0),onMouseEnter:()=>z(!0),onMouseLeave:()=>z(!1),"aria-label":`Edit chart ${e}`,title:`Edit chart ${e}`,className:ct.sideEditBtn,children:"✎ Edit"}),r.jsxs(me,{type:"button",variant:"admin",size:"xs",onClick:M,onMouseEnter:()=>z(!0),onMouseLeave:()=>z(!1),disabled:_,className:ct.sideSyncBtn,title:"Sync chart data from Google Sheet","aria-label":`Sync chart data for ${e}`,children:[r.jsx("span",{className:`${ct.syncIcon} ${_?ct.spinning:""}`,"aria-hidden":"true",children:"↻"}),r.jsx("span",{children:_?"Syncing…":"Sync"})]})]})]}),y&&r.jsx(nc,{isOpen:S,onClose:()=>v(!1),chartId:e,nodeId:s,initialConfig:n||void 0,onDeployed:se=>{c==null||c(se)}}),W&&t&&r.jsx(Mh,{isOpen:k,onClose:()=>x(!1),dataset:t,title:$,asOfDate:V,onDownloadCsv:q}),T&&r.jsx(Zt,{message:T.message,type:T.type,durationMs:T.type==="error"?5500:3500,onDismiss:()=>w(null)})]})},To=Di,Dh="folio_chart_matrix_";function sr(e,t){var n,s;return t?{...e,title:t.titleOverride||e.title,subtitle:t.subtitleOverride!==void 0?t.subtitleOverride:e.subtitle,unit:t.unitOverride||e.unit,chartType:t.defaultType||e.chartType,visualConfig:{...e.visualConfig,...t.visualConfig,unit:t.unitOverride||((n=t.visualConfig)==null?void 0:n.unit)||((s=e.visualConfig)==null?void 0:s.unit)}}:e}function Ao(e){return e.map(t=>Array.isArray(t)?t.map(n=>n==null?"":String(n)):[])}function Xv({chartId:e,nodeId:t,initialDataset:n,pollIntervalMs:s,isDevMode:a=!1}){const[o]=u.useState(()=>os(e)),[i]=u.useState(()=>{try{if(typeof window<"u"&&window.localStorage){const w=window.localStorage.getItem(`${Dh}${e}`);if(w){const M=JSON.parse(w);if(Array.isArray(M)&&M.length>0)return cs({chartId:e,title:(o==null?void 0:o.titleOverride)||"",subtitle:o==null?void 0:o.subtitleOverride,unit:o==null?void 0:o.unitOverride,chartType:o==null?void 0:o.defaultType,nodeId:t,visualConfig:o==null?void 0:o.visualConfig,rawMatrix:M})}}}catch{}if(o!=null&&o.cachedDataset&&o.cachedDataset.length>0)return cs({chartId:e,title:(o==null?void 0:o.titleOverride)||"",subtitle:o==null?void 0:o.subtitleOverride,unit:o==null?void 0:o.unitOverride,chartType:o==null?void 0:o.defaultType,nodeId:t,visualConfig:o==null?void 0:o.visualConfig,rawMatrix:Ao(o.cachedDataset)});if(n)return sr(n,o);const T=To.find(w=>w.chartId===e);if(T)return sr(T,o);if(t){const w=To.find(M=>M.nodeId===t);if(w)return sr(w,o)}return null}),[l,c]=u.useState(i),[d,h]=u.useState(o),[p,f]=u.useState(null),[m,g]=u.useState(()=>i?"success":"pending_data"),[b,y]=u.useState(),[S,v]=u.useState(()=>(o==null?void 0:o.updatedAt)||(i?new Date().toISOString():void 0)),k=u.useRef(!0),x=u.useCallback(async()=>{if(e)try{const T=await xh(e,{forceRefresh:!0});if(!k.current)return;if(T){if(h(T),Rt(T),v(T.updatedAt||new Date().toISOString()),T.cachedDataset&&T.cachedDataset.length>0){const w=cs({chartId:e,title:T.titleOverride||"",subtitle:T.subtitleOverride,unit:T.unitOverride,chartType:T.defaultType,nodeId:t,visualConfig:T.visualConfig,rawMatrix:Ao(T.cachedDataset)});k.current&&(c(w),g("success"));return}c(w=>{if(!w){const M=To.find($=>$.chartId===e);return M?sr(M,T):null}return sr(w,T)}),g("success")}else c(w=>{if(w)return w;const M=To.find($=>$.chartId===e);return M?sr(M,os(e)):null}),g(w=>w==="syncing"?"success":w)}catch(T){if(!k.current)return;const w=T instanceof Error?T.message:"Failed to sync chart configuration";y(w),g(M=>M==="syncing"?"success":M)}},[e,t]),I=u.useCallback(async()=>{if(!e)return null;const T=d||o;if(!(T!=null&&T.sheetUrl))throw new Error("No Google Sheet linked to this chart.");g("syncing"),y(void 0);try{const w=await ec({sheetUrl:T.sheetUrl,tabName:T.tabName,sheetGid:T.sheetGid,range:T.range,timeoutMs:8e3});if(!k.current)return null;if(w&&w.length>0){try{typeof window<"u"&&window.localStorage&&window.localStorage.setItem(`${Dh}${e}`,JSON.stringify(w))}catch{}const M=cs({chartId:e,title:T.titleOverride||"",subtitle:T.subtitleOverride,unit:T.unitOverride,chartType:T.defaultType,nodeId:t,visualConfig:T.visualConfig,rawMatrix:Ao(w)}),$={...T,cachedDataset:w,updatedAt:new Date().toISOString()};return await is($),Rt($),xo(e,$),c(M),h($),v($.updatedAt),g("success"),w}else return g("success"),[]}catch(w){if(!k.current)return null;const M=w instanceof Error?w.message:"Failed to sync live sheet data";throw y(M),g("error"),w}},[e,d,o,t]);u.useEffect(()=>{k.current=!0,x();let T=null;return a&&s&&s>0&&(T=window.setInterval(x,s)),()=>{k.current=!1,T&&clearInterval(T)}},[x,s,a]),u.useEffect(()=>{if(typeof window>"u")return;const T=w=>{const M=w;if(M.detail&&M.detail.chartId===e){if(M.detail.config){const $=M.detail.config;if(h($),$.cachedDataset&&$.cachedDataset.length>0){const A=cs({chartId:e,title:$.titleOverride||"",subtitle:$.subtitleOverride,unit:$.unitOverride,chartType:$.defaultType,nodeId:t,visualConfig:$.visualConfig,rawMatrix:Ao($.cachedDataset)});c(A),g("success");return}}x()}};return window.addEventListener(Co,T),()=>{window.removeEventListener(Co,T)}},[e,t,x]);const N=u.useMemo(()=>l?p?sr(l,p):l:null,[l,p]),_=u.useMemo(()=>!d&&!p?null:{...d||{},...p||{}},[d,p]);return{dataset:N,config:_,status:m,errorMessage:b,lastSyncedAt:S,reload:x,syncLiveSheet:I,setOverrideConfig:f}}const sc=u.memo(({element:e,nodeId:t,nodeTitle:n,accentColor:s,isDevMode:a,className:o})=>{const{isDevMode:i}=Oe(),l=a??i,{dataset:c,config:d,reload:h,status:p,errorMessage:f,syncLiveSheet:m}=Xv({chartId:e.chartId,nodeId:t,isDevMode:l});return r.jsx("div",{className:`${rt.chartContainer} ${o||""}`.trim(),children:r.jsx(rc,{chartId:e.chartId,dataset:c,config:d,status:p,errorMessage:f,nodeId:t,nodeTitle:n,accentColor:s,editTriggerId:e.id,onConfigUpdated:()=>{h()},onSync:m,isSyncing:p==="syncing"})})});sc.displayName="CanvasChart";const Se={addBarGutter:"_addBarGutter_1q43h_15",hoverGuideLine:"_hoverGuideLine_1q43h_25",addBarActive:"_addBarActive_1q43h_37",addPillButton:"_addPillButton_1q43h_48",plusIcon:"_plusIcon_1q43h_115",paletteMenu:"_paletteMenu_1q43h_125",dropdownMenu:"_dropdownMenu_1q43h_153",dropupMenu:"_dropupMenu_1q43h_158",paletteOptionWrapper:"_paletteOptionWrapper_1q43h_164",paletteOption:"_paletteOption_1q43h_164",paletteIcon:"_paletteIcon_1q43h_209",chevronIcon:"_chevronIcon_1q43h_224",paletteOptionActive:"_paletteOptionActive_1q43h_241",subMenu:"_subMenu_1q43h_255",dropupSubMenu:"_dropupSubMenu_1q43h_298",subOption:"_subOption_1q43h_311",subOptionIcon:"_subOptionIcon_1q43h_346",addBarSuppressed:"_addBarSuppressed_1q43h_362",starterContainer:"_starterContainer_1q43h_373",starterButton:"_starterButton_1q43h_384",itemControlsWrapper:"_itemControlsWrapper_1q43h_427",itemControlsFloatingBar:"_itemControlsFloatingBar_1q43h_431",sectionFloatingBar:"_sectionFloatingBar_1q43h_458",suppressHover:"_suppressHover_1q43h_474",dragHandle:"_dragHandle_1q43h_479",dropTargetHighlight:"_dropTargetHighlight_1q43h_501",isDragging:"_isDragging_1q43h_506",controlButton:"_controlButton_1q43h_510",editButton:"_editButton_1q43h_548",deleteButton:"_deleteButton_1q43h_572",editIcon:"_editIcon_1q43h_582",deleteIcon:"_deleteIcon_1q43h_583",modalBody:"_modalBody_1q43h_593",modalMessage:"_modalMessage_1q43h_600",modalWarning:"_modalWarning_1q43h_608",modalActions:"_modalActions_1q43h_619",modalDeleteButton:"_modalDeleteButton_1q43h_627"},Bh=({className:e})=>r.jsxs("svg",{className:e,width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[r.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),r.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),Jv=({className:e})=>r.jsxs("svg",{className:e,width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[r.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),r.jsx("path",{d:"M3 9h18"}),r.jsx("path",{d:"M7 15h10"})]}),Qv=({className:e})=>r.jsxs("svg",{className:e,width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[r.jsx("path",{d:"M4 5h16"}),r.jsx("path",{d:"M9 12h11"}),r.jsx("path",{d:"M9 18h8"}),r.jsx("polyline",{points:"4 9 4 15 7 15"})]}),Rv=({className:e})=>r.jsxs("svg",{className:e,width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[r.jsx("polyline",{points:"4 7 4 4 20 4 20 7"}),r.jsx("line",{x1:"9",y1:"20",x2:"15",y2:"20"}),r.jsx("line",{x1:"12",y1:"4",x2:"12",y2:"20"})]}),Oh=({className:e})=>r.jsxs("svg",{className:e,width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[r.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),r.jsx("circle",{cx:"8.5",cy:"8.5",r:"1.5"}),r.jsx("polyline",{points:"21 15 16 10 5 21"})]}),eb=({className:e})=>r.jsxs("svg",{className:e,width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[r.jsx("rect",{x:"3",y:"3",width:"7",height:"7",rx:"1.5"}),r.jsx("rect",{x:"14",y:"3",width:"7",height:"7",rx:"1.5"}),r.jsx("rect",{x:"3",y:"14",width:"7",height:"7",rx:"1.5"}),r.jsx("rect",{x:"14",y:"14",width:"7",height:"7",rx:"1.5"})]}),tb=({className:e})=>r.jsx("svg",{className:e,width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:r.jsx("polyline",{points:"9 18 15 12 9 6"})}),nb=[{type:"section",label:"Section",IconComponent:Jv},{type:"subsection",label:"Subsection",IconComponent:Qv},{type:"text",label:"Text",IconComponent:Rv},{type:"photo",label:"Photo",IconComponent:Oh},{type:"chart",label:"Chart",IconComponent:({className:e})=>r.jsxs("svg",{className:e,width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[r.jsx("line",{x1:"18",y1:"20",x2:"18",y2:"10"}),r.jsx("line",{x1:"12",y1:"20",x2:"12",y2:"4"}),r.jsx("line",{x1:"6",y1:"20",x2:"6",y2:"14"})]})}],vn=u.memo(({onAddElement:e,isInitialStarter:t=!1,accentColor:n,className:s,label:a="Click to add the first Section",barId:o,activeBarId:i,onToggleActive:l})=>{const{isDevMode:c,isDesktop:d}=Oe(),[h,p]=u.useState(!1),[f,m]=u.useState(!1),[g,b]=u.useState(!1),[y,S]=u.useState(!1),v=u.useRef(null),k=u.useRef(null),x=u.useRef(null),I=o&&i!==void 0?i===o:h,N=!!(i&&o&&i!==o),_=u.useCallback(()=>{x.current&&(clearTimeout(x.current),x.current=null)},[]),T=u.useCallback(()=>{_(),b(!0)},[_]),w=u.useCallback(()=>{_(),y||(x.current=setTimeout(()=>{b(!1)},350))},[_,y]),M=u.useCallback(V=>{V.stopPropagation(),_(),S(D=>!D),b(D=>!D)},[_]),$=u.useCallback(()=>{y||(_(),b(!1))},[y,_]),A=u.useCallback(()=>{_(),p(!1),b(!1),S(!1),o&&l&&l(o,!1)},[o,l,_]),P=u.useCallback(()=>{var V;if(I)A();else{_();const D=(V=k.current)==null?void 0:V.getBoundingClientRect(),W=D?window.innerHeight-D.bottom:300;m(W<240),p(!0),b(!1),S(!1),o&&l&&l(o,!0)}},[I,A,o,l,_]);return u.useEffect(()=>()=>{_()},[_]),u.useEffect(()=>{if(!I)return;const V=W=>{const H=W.target;v.current&&!v.current.contains(H)&&k.current&&!k.current.contains(H)&&A()},D=W=>{var H;W.key==="Escape"&&(A(),(H=k.current)==null||H.focus())};return document.addEventListener("mousedown",V),document.addEventListener("keydown",D),()=>{document.removeEventListener("mousedown",V),document.removeEventListener("keydown",D)}},[I,A]),!c||!d?null:t?r.jsx("div",{className:`${Se.starterContainer} ${s||""}`.trim(),children:r.jsxs("button",{type:"button",className:Se.starterButton,onClick:()=>e("section"),children:[r.jsx("span",{className:Se.plusIcon,children:r.jsx(Bh,{})}),r.jsx("span",{children:a})]})}):r.jsxs("div",{className:`${Se.addBarGutter} ${I?Se.addBarActive:""} ${N?Se.addBarSuppressed:""} ${s||""}`.trim(),role:"region","aria-label":"Insert element",children:[r.jsx("div",{className:Se.hoverGuideLine,"aria-hidden":"true"}),r.jsxs("button",{ref:k,type:"button",className:Se.addPillButton,onClick:P,"aria-expanded":I,"aria-haspopup":"menu",children:[r.jsx("span",{className:Se.plusIcon,children:r.jsx(Bh,{})}),r.jsx("span",{children:"Add Element"})]}),I&&r.jsx("div",{ref:v,role:"menu","aria-label":"Add Element Palette",className:`${Se.paletteMenu} ${f?Se.dropupMenu:Se.dropdownMenu}`,children:nb.map(V=>{const D=V.IconComponent;return V.type==="photo"?r.jsxs("div",{className:Se.paletteOptionWrapper,onMouseEnter:T,onMouseLeave:w,children:[r.jsxs("button",{role:"menuitem",type:"button",className:`${Se.paletteOption} ${g?Se.paletteOptionActive:""}`.trim(),onClick:M,"aria-haspopup":"menu","aria-expanded":g,children:[r.jsx("span",{className:Se.paletteIcon,"aria-hidden":"true",children:r.jsx(D,{})}),r.jsx("span",{children:V.label}),r.jsx("span",{className:Se.chevronIcon,"aria-hidden":"true",children:r.jsx(tb,{})})]}),g&&r.jsxs("div",{role:"menu","aria-label":"Photo Element Options",className:`${Se.subMenu} ${f?Se.dropupSubMenu:""}`,onMouseEnter:T,onMouseLeave:w,children:[r.jsxs("button",{role:"menuitem",type:"button",className:Se.subOption,onClick:()=>{e("photo"),A()},children:[r.jsx("span",{className:Se.subOptionIcon,"aria-hidden":"true",children:r.jsx(Oh,{})}),r.jsx("span",{children:"Single Photo"})]}),r.jsxs("button",{role:"menuitem",type:"button",className:Se.subOption,onClick:()=>{e("gallery"),A()},children:[r.jsx("span",{className:Se.subOptionIcon,"aria-hidden":"true",children:r.jsx(eb,{})}),r.jsx("span",{children:"Photo Gallery"})]})]})]},V.type):r.jsxs("button",{role:"menuitem",type:"button",className:Se.paletteOption,onMouseEnter:$,onClick:()=>{e(V.type),A()},children:[r.jsx("span",{className:Se.paletteIcon,"aria-hidden":"true",children:r.jsx(D,{})}),r.jsx("span",{children:V.label})]},V.type)})})]})});vn.displayName="CanvasAddBar";function rb(e){switch(e){case"section":return{title:"Delete Section",noun:"section"};case"subsection":return{title:"Delete Subsection",noun:"subsection"};case"text":return{title:"Delete Text Block",noun:"text block"};case"photo":return{title:"Delete Photo",noun:"photo"};case"gallery":return{title:"Delete Photo Gallery",noun:"photo gallery"};case"chart":return{title:"Delete Chart",noun:"chart"};default:return{title:"Delete Item",noun:"item"}}}const ac=u.memo(({isOpen:e,itemType:t,hasChildren:n=!1,onClose:s,onConfirm:a})=>{const{title:o,noun:i}=rb(t);return r.jsx(bt,{isOpen:e,onClose:s,onConfirm:a,role:"alertdialog",ariaLabel:o,title:o,maxWidth:440,children:r.jsxs("div",{className:Se.modalBody,children:[r.jsxs("p",{className:Se.modalMessage,children:["Are you sure you want to delete this ",i,"?"]}),n&&r.jsxs("p",{className:Se.modalWarning,children:["Warning: Everything inside this ",i," will also be deleted."]}),r.jsxs("div",{className:Se.modalActions,children:[r.jsx(me,{variant:"ghost",size:"sm",onClick:s,children:"Cancel"}),r.jsx(me,{variant:"admin",size:"sm",onClick:a,className:Se.modalDeleteButton,children:"Delete"})]})]})})});ac.displayName="CanvasDeleteConfirmModal";const ds=u.memo(({itemId:e,itemType:t,canMoveUp:n,canMoveDown:s,onMoveUp:a,onMoveDown:o,onDelete:i,onEdit:l,children:c,className:d,suppressHover:h=!1,sourceParentId:p,sourceIndex:f,hasChildren:m=!1,onDropItem:g})=>{const{isDevMode:b,isDesktop:y}=Oe(),S=u.useRef(null),[v,k]=u.useState(!1),[x,I]=u.useState(!1),[N,_]=u.useState(!1),T=u.useCallback(()=>{k(!1),i()},[i]);if(!b||!y)return r.jsx(r.Fragment,{children:c});const w=q=>{q.stopPropagation(),I(!0),q.dataTransfer.setData("application/json",JSON.stringify({itemId:e,itemType:t,sourceParentId:p,sourceIndex:f})),q.dataTransfer.effectAllowed="move"},M=()=>{I(!1),_(!1)},$=q=>{g&&(q.preventDefault(),q.stopPropagation(),q.dataTransfer.dropEffect="move",N||_(!0))},A=q=>{q.stopPropagation(),_(!1)},P=q=>{if(g){q.preventDefault(),q.stopPropagation(),_(!1);try{const j=q.dataTransfer.getData("application/json");if(j){const z=JSON.parse(j);z.itemId&&z.itemId!==e&&g(z.itemId,p||e,f)}}catch{}}},V=q=>{q.stopPropagation(),k(!0)},D=q=>{q.stopPropagation(),l&&l()},W=t==="section"?`${Se.itemControlsFloatingBar} ${Se.sectionFloatingBar}`:Se.itemControlsFloatingBar,H=h||v;return r.jsxs(r.Fragment,{children:[r.jsxs("div",{ref:S,className:`${Se.itemControlsWrapper} ${H?Se.suppressHover:""} ${N?Se.dropTargetHighlight:""} ${x?Se.isDragging:""} ${d||""}`.trim(),"data-canvas-item-id":e,"data-canvas-item-type":t,onDragOver:$,onDragLeave:A,onDrop:P,children:[r.jsxs("div",{className:W,role:"toolbar","aria-label":"Item authoring controls",children:[r.jsx("span",{className:Se.dragHandle,title:"Drag to reorder","aria-label":"Drag to reorder",draggable:!0,onDragStart:w,onDragEnd:M,role:"button",tabIndex:0,children:"⋮⋮"}),r.jsx("button",{type:"button",className:Se.controlButton,onClick:q=>{q.stopPropagation(),a()},disabled:!n,title:n?"Move Up":"First element in canvas — cannot move up further","aria-label":"Move Up",children:"↑"}),r.jsx("button",{type:"button",className:Se.controlButton,onClick:q=>{q.stopPropagation(),o()},disabled:!s,title:s?"Move Down":"Last element in canvas — cannot move down further","aria-label":"Move Down",children:"↓"}),r.jsx("button",{type:"button",className:`${Se.controlButton} ${Se.editButton}`,onClick:D,title:"Edit","aria-label":"Edit",children:r.jsxs("svg",{className:Se.editIcon,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[r.jsx("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),r.jsx("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]})}),r.jsx("button",{type:"button",className:`${Se.controlButton} ${Se.deleteButton}`,onClick:V,title:"Delete","aria-label":"Delete",children:r.jsxs("svg",{className:Se.deleteIcon,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[r.jsx("polyline",{points:"3 6 5 6 21 6"}),r.jsx("path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"}),r.jsx("line",{x1:"10",y1:"11",x2:"10",y2:"17"}),r.jsx("line",{x1:"14",y1:"11",x2:"14",y2:"17"})]})})]}),c]}),v&&r.jsx(ac,{isOpen:v,itemType:t,hasChildren:m,onClose:()=>k(!1),onConfirm:T})]})});ds.displayName="CanvasItemControls";function sb(e){let t=1;const n={};for(const s of e)s.isNumbered?(n[s.id]=String(t).padStart(2,"0"),t++):n[s.id]=null;return n}function ab(e,t){const{isDevMode:n}=Oe(),[s,a]=u.useState(0);return u.useEffect(()=>ai(o=>{const i=o==null?void 0:o.key;(!i||i==="*"||typeof i=="string"&&i.includes(".isNumbered"))&&a(l=>l+1)},n),[n]),u.useMemo(()=>{const o=t.map(i=>{const c=`${i.titlePointId||`node.${e}.section.${i.id}.title`}.isNumbered`,d=wn(c,"",n),h=i.isNumbered!==void 0?i.isNumbered:i.number!==void 0&&i.number!==null,p=d!==""?d==="true":h;return{id:i.id,isNumbered:p}});return sb(o)},[e,t,s,n])}function Ph(e,t,n,s,a,o){switch(e.type){case"text":return r.jsx(vl,{element:e,nodeId:t,accentColor:s,onEdit:o?()=>o(e):void 0});case"photo":return r.jsx(xl,{element:e,nodeId:t,accentColor:s,onEdit:a?()=>a(e):void 0});case"gallery":return r.jsx(Al,{element:e,nodeId:t,accentColor:s});case"chart":return r.jsx(sc,{element:e,nodeId:t,nodeTitle:n,accentColor:s});default:return null}}const oc=u.memo(({nodeId:e,nodeTitle:t,accentColor:n,className:s})=>{const{isDevMode:a,isDesktop:o}=Oe(),i=a&&o,{document:l,addElement:c,restoreSection:d,restoreSubsection:h,restoreElement:p,moveItem:f,relocateItem:m,removeItem:g,updateItem:b,saveError:y,clearSaveError:S}=pl(e),v=ab(e,l.sections),[k,x]=u.useState(null),[I,N]=u.useState(!1),[_,T]=u.useState(null),[w,M]=u.useState(null),[$,A]=u.useState(null),P=u.useCallback((B,Y)=>{T(Y?B:null)},[]),V=u.useCallback((B,Y)=>{x({type:"section",section:B,index:Y}),g(B.id),N(!0)},[g]),D=u.useCallback((B,Y,ee)=>{x({type:"subsection",subsection:Y,sectionId:B,index:ee}),g(Y.id,B),N(!0)},[g]),W=u.useCallback((B,Y,ee,X)=>{x({type:"leaf",leaf:Y,sectionId:B,subsectionId:X,index:ee}),g(Y.id,X||B),N(!0)},[g]),H=u.useCallback(()=>{k&&(k.type==="section"&&k.section?d(k.section,k.index):k.type==="subsection"&&k.subsection&&k.sectionId?h(k.sectionId,k.subsection,k.index):k.type==="leaf"&&k.leaf&&k.sectionId&&p(k.sectionId,k.leaf,k.index,k.subsectionId),x(null),N(!1))},[k,d,h,p]),q=u.useCallback((B,Y,ee,X)=>{if(B==="chart"){const te="chart-"+e+"-"+Vt("chart");A({isOpen:!0,mode:"add",chartId:te,targetSectionId:Y,targetIndex:ee,targetSubsectionId:X});return}M({isOpen:!0,mode:"add",elementType:B,targetSectionId:Y,targetIndex:ee,targetSubsectionId:X})},[e]),j=u.useCallback(B=>{const Y=B.titlePointId||`node.${e}.section.${B.id}.title`;M({isOpen:!0,mode:"edit",elementType:"section",itemId:B.id,pointId:Y,initialData:{title:B.title,isNumbered:B.isNumbered!==!1}})},[e]),z=u.useCallback(B=>{const Y=B.titlePointId||`node.${e}.subsection.${B.id}.title`;M({isOpen:!0,mode:"edit",elementType:"subsection",itemId:B.id,pointId:Y,initialData:{title:B.title}})},[e]),O=u.useCallback(B=>{M({isOpen:!0,mode:"edit",elementType:"photo",itemId:B.id,pointId:B.pointId,initialData:{src:B.src,alt:B.alt,caption:B.caption,driveUrl:B.driveUrl}})},[]),U=u.useCallback(B=>{if(B.type==="chart"){A({isOpen:!0,mode:"edit",chartId:B.chartId});return}if(B.type==="photo"){O(B);return}let Y={},ee;B.type==="text"?(ee=B.pointId,Y={content:B.content,as:B.as||"p"}):B.type==="gallery"&&(ee=B.pointId||B.titlePointId,Y={title:B.title||"",driveUrl:B.driveUrl||""}),M({isOpen:!0,mode:"edit",elementType:B.type,itemId:B.id,pointId:ee,initialData:Y})},[O]),Q=u.useCallback((B,Y,ee,X,te)=>{var J,Z,ne,ie,F,L,G,le,ue;if(B==="section"){const he=Vt("section"),oe=`node.${e}.section.${he}.title`,ye=Y.isNumbered!==!1,xe={id:he,type:"section",title:((J=Y.title)==null?void 0:J.trim())||"Section",titlePointId:oe,isNumbered:ye,elements:[]};if(ee){const ke=l.sections.findIndex(Ze=>Ze.id===ee);if(ke!==-1){d(xe,ke+1);return}}d(xe,X);return}if(B==="subsection"){const he=Vt("subsection"),oe=`node.${e}.subsection.${he}.title`,ye={id:he,type:"subsection",title:((Z=Y.title)==null?void 0:Z.trim())||"Subsection",titlePointId:oe,elements:[]};if(ee)h(ee,ye,X);else if(l.sections.length>0){const xe=typeof X=="number"&&X===0?l.sections[0]:l.sections[Math.min((X??1)-1,l.sections.length-1)];h(xe.id,ye)}else{const xe=Vt("section"),ke={id:xe,type:"section",title:"Section 1",titlePointId:`node.${e}.section.${xe}.title`,isNumbered:!0,elements:[ye]};d(ke,0)}return}let K;if(B==="text"){const he=Vt("text"),oe=`node.${e}.text.${he}`;K={id:he,type:"text",pointId:oe,content:((ne=Y.content)==null?void 0:ne.trim())||"",as:Y.as||"p"}}else if(B==="photo"){const he=Vt("photo"),oe=`node.${e}.photo.${he}`;K={id:he,type:"photo",pointId:oe,src:((ie=Y.src)==null?void 0:ie.trim())||void 0,alt:((F=Y.alt)==null?void 0:F.trim())||void 0,caption:((L=Y.caption)==null?void 0:L.trim())||void 0,driveUrl:((G=Y.driveUrl)==null?void 0:G.trim())||void 0}}else{const he=Vt("gallery"),oe=`node.${e}.gallery.${he}.title`;K={id:he,type:"gallery",pointId:`node.${e}.gallery.${he}`,title:((le=Y.title)==null?void 0:le.trim())||void 0,titlePointId:oe,driveUrl:((ue=Y.driveUrl)==null?void 0:ue.trim())||void 0}}if(ee)c(ee,K,X,te);else if(l.sections.length===0){const he=Ro(0,e);he.elements.push(K),d(he,0)}else{const he=typeof X=="number"&&X===0?l.sections[0]:l.sections[Math.min((X??1)-1,l.sections.length-1)],oe=typeof X=="number"&&X===0?0:void 0;c(he.id,K,oe)}},[e,l.sections,d,h,c]),se=u.useCallback(B=>{var Z,ne,ie,F,L,G,le,ue,he;if(!w)return;const{mode:Y,elementType:ee,itemId:X,targetSectionId:te,targetIndex:K,targetSubsectionId:J}=w;if(Y==="add"){Q(ee,B,te,K,J),M(null);return}ee==="section"&&X?b(X,{title:(Z=B.title)==null?void 0:Z.trim(),isNumbered:B.isNumbered!==!1}):ee==="subsection"&&X?b(X,{title:(ne=B.title)==null?void 0:ne.trim()}):ee==="text"&&X?b(X,{content:(ie=B.content)==null?void 0:ie.trim(),as:B.as||"p"}):ee==="photo"&&X?b(X,{src:((F=B.src)==null?void 0:F.trim())||void 0,alt:((L=B.alt)==null?void 0:L.trim())||void 0,caption:((G=B.caption)==null?void 0:G.trim())||void 0,driveUrl:((le=B.driveUrl)==null?void 0:le.trim())||void 0}):ee==="gallery"&&X&&b(X,{title:((ue=B.title)==null?void 0:ue.trim())||void 0,driveUrl:((he=B.driveUrl)==null?void 0:he.trim())||void 0}),M(null)},[w,b,Q]),ae=u.useCallback(()=>{M(null)},[]),de=u.useCallback((B,Y,ee)=>{m(B,Y,ee)},[m]);return l.sections.length===0&&!i?null:r.jsxs("div",{className:s,style:{opacity:1,transition:"opacity var(--duration-normal) var(--ease-out)"},children:[l.sections.length===0?r.jsx(vn,{isInitialStarter:!0,barId:"starter-bar",activeBarId:_,onToggleActive:P,onAddElement:()=>q("section"),label:"Click to add the first Section",accentColor:n}):r.jsxs(r.Fragment,{children:[i&&r.jsx(vn,{barId:"top-bar",activeBarId:_,onToggleActive:P,onAddElement:B=>q(B,void 0,0),accentColor:n}),l.sections.map((B,Y)=>{const ee=Y>0,X=Y<l.sections.length-1,te=v[B.id];return r.jsx(u.Fragment,{children:r.jsx(ds,{itemId:B.id,itemType:"section",canMoveUp:ee,canMoveDown:X,onMoveUp:()=>f(B.id,"up"),onMoveDown:()=>f(B.id,"down"),onDelete:()=>V(B,Y),onEdit:()=>j(B),suppressHover:!!_,sourceParentId:e,sourceIndex:Y,hasChildren:B.elements.length>0,onDropItem:de,children:r.jsxs(ml,{section:B,nodeId:e,nodeTitle:t,accentColor:n,computedNumber:te,onEdit:()=>j(B),children:[i&&(B.elements||[]).length===0&&r.jsx(vn,{barId:`sec-top-${B.id}`,activeBarId:_,onToggleActive:P,onAddElement:K=>q(K,B.id,0),accentColor:n}),(B.elements||[]).filter(K=>!!(K&&K.id&&K.type)).map((K,J,Z)=>{const ne=!(Y===0&&J===0),ie=!(Y===l.sections.length-1&&J===Z.length-1);if(K.type==="subsection"){const F=(K.elements||[]).filter(L=>!!(L&&L.id&&L.type));return r.jsxs(u.Fragment,{children:[r.jsx(ds,{itemId:K.id,itemType:"subsection",canMoveUp:ne,canMoveDown:ie,onMoveUp:()=>f(K.id,"up",B.id),onMoveDown:()=>f(K.id,"down",B.id),onDelete:()=>D(B.id,K,J),onEdit:()=>z(K),suppressHover:!!_,sourceParentId:B.id,sourceIndex:J,hasChildren:F.length>0,onDropItem:de,children:r.jsxs(gl,{subsection:K,nodeId:e,accentColor:n,onEdit:()=>z(K),children:[i&&F.length===0&&r.jsx(vn,{barId:`sub-top-${K.id}`,activeBarId:_,onToggleActive:P,onAddElement:L=>q(L,B.id,0,K.id),accentColor:n}),F.map((L,G)=>{const le=!(Y===0&&J===0&&G===0),ue=!(Y===l.sections.length-1&&J===Z.length-1&&G===F.length-1);return r.jsxs(u.Fragment,{children:[r.jsx(ds,{itemId:L.id,itemType:L.type,canMoveUp:le,canMoveDown:ue,onMoveUp:()=>f(L.id,"up",K.id),onMoveDown:()=>f(L.id,"down",K.id),onDelete:()=>W(B.id,L,G,K.id),onEdit:()=>U(L),suppressHover:!!_,sourceParentId:K.id,sourceIndex:G,onDropItem:de,children:Ph(L,e,t,n,O,U)}),i&&r.jsx(vn,{barId:`leaf-${L.id}`,activeBarId:_,onToggleActive:P,onAddElement:he=>q(he,B.id,G+1,K.id),accentColor:n})]},L.id)})]})}),i&&r.jsx(vn,{barId:`sub-${K.id}`,activeBarId:_,onToggleActive:P,onAddElement:L=>q(L,B.id,J+1),accentColor:n})]},K.id)}return r.jsxs(u.Fragment,{children:[r.jsx(ds,{itemId:K.id,itemType:K.type,canMoveUp:ne,canMoveDown:ie,onMoveUp:()=>f(K.id,"up",B.id),onMoveDown:()=>f(K.id,"down",B.id),onDelete:()=>W(B.id,K,J),onEdit:()=>U(K),suppressHover:!!_,sourceParentId:B.id,sourceIndex:J,onDropItem:de,children:Ph(K,e,t,n,O,U)}),i&&r.jsx(vn,{barId:`direct-leaf-${K.id}`,activeBarId:_,onToggleActive:P,onAddElement:F=>q(F,B.id,J+1),accentColor:n})]},K.id)})]})})},B.id)})]}),I&&r.jsx(Zt,{message:"Item deleted",type:"info",durationMs:5e3,actionLabel:"Undo",onAction:H,onDismiss:()=>{N(!1),x(null)}}),y&&r.jsx(Zt,{message:y,type:"error",durationMs:4e3,onDismiss:S}),r.jsx(Jn,{isOpen:!!w,mode:(w==null?void 0:w.mode)??"add",elementType:(w==null?void 0:w.elementType)??null,nodeId:e,itemId:w==null?void 0:w.itemId,pointId:w==null?void 0:w.pointId,initialData:w==null?void 0:w.initialData,targetSectionId:w==null?void 0:w.targetSectionId,targetIndex:w==null?void 0:w.targetIndex,targetSubsectionId:w==null?void 0:w.targetSubsectionId,onClose:()=>M(null),onSubmit:se,onResetToDefault:ae}),$&&r.jsx(nc,{isOpen:$.isOpen,mode:$.mode,chartId:$.chartId,nodeId:e,onClose:()=>A(null),onDeployed:B=>{if($.mode==="add"){const Y={id:Vt("chart"),type:"chart",chartId:$.chartId,title:B.titleOverride||"Indicator Chart",subtitle:B.subtitleOverride};if($.targetSectionId)c($.targetSectionId,Y,$.targetIndex,$.targetSubsectionId);else if(l.sections.length===0){const ee=Ro(0,e);ee.elements.push(Y),d(ee,0)}else{const ee=typeof $.targetIndex=="number"&&$.targetIndex===0?l.sections[0]:l.sections[Math.min(($.targetIndex??1)-1,l.sections.length-1)],X=typeof $.targetIndex=="number"&&$.targetIndex===0?0:void 0;c(ee.id,Y,X)}}A(null)}})]})});oc.displayName="DocumentCanvas";const us={notFoundWrapper:"_notFoundWrapper_4997g_12",errorCode:"_errorCode_4997g_26",title:"_title_4997g_35",description:"_description_4997g_45",returnButton:"_returnButton_4997g_54",returnIcon:"_returnIcon_4997g_79"},ob=({onReturn:e,title:t="Pathway Uncharted in Registry",description:n="The requested resource or document view could not be located in this registry.",errorCode:s="[HTTP 404 · ROUTE UNRESOLVED]",returnLabel:a="Return to Overview",className:o})=>r.jsxs("main",{className:`${us.notFoundWrapper} ${o??""}`.trim(),role:"main",children:[r.jsx("div",{className:us.errorCode,children:s}),r.jsx("h1",{className:us.title,children:t}),r.jsx("p",{className:us.description,children:n}),e&&r.jsxs("button",{type:"button",className:us.returnButton,onClick:e,children:[r.jsx("svg",{className:us.returnIcon,viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:r.jsx("path",{d:"M10 13L5 8l5-5"})}),r.jsx("span",{children:a})]})]}),ib=["access","equity","quality","resiliency","governance"],ic={access:1,equity:2,quality:3,resiliency:4,governance:5},lb={1:"access",2:"equity",3:"quality",4:"resiliency",5:"governance"};function hs(e="/",t="",n){const s=e.trim().replace(/\/+$/,"")+"/",a=t.replace(/^#\/?/,"").trim(),o=s.match(/^\/(node|page)\/([a-zA-Z0-9_-]+)\/?$/);if(o){const d=o[2].toLowerCase();if(n?n.includes(d):!0){const p=d;return{type:"node",nodeId:p,pageId:p,targetStage:ic[p]??null,rawHash:t,pathname:"/node/"+p+"/"}}return{type:"not-found",nodeId:null,pageId:null,targetStage:null,rawHash:t,pathname:s}}if(a.startsWith("node/")||a.startsWith("page/")){const d=a.startsWith("node/")?"node/":"page/",h=a.slice(d.length).replace(/\/$/,"").toLowerCase();if(n?n.includes(h):!0){const f=h;return{type:"node",nodeId:f,pageId:f,targetStage:ic[f]??null,rawHash:t,pathname:"/node/"+f+"/"}}return{type:"not-found",nodeId:null,pageId:null,targetStage:null,rawHash:t,pathname:s}}const i=a.match(/^stage-(\d+)$/);return i?{type:"home",nodeId:null,pageId:null,targetStage:parseInt(i[1],10),rawHash:t,pathname:"/"}:(s==="/"||s==="/index.html/")&&(!a||a==="home"||a==="main-content"||a==="roadmap"||a==="sequence-roadmap")?{type:"home",nodeId:null,pageId:null,targetStage:null,rawHash:t,pathname:"/"}:{type:"not-found",nodeId:null,pageId:null,targetStage:null,rawHash:t,pathname:s}}function cb(e,t){return hs(typeof window<"u"?window.location.pathname:"/",e,t)}function lc(e){const[t,n]=u.useState(()=>hs(typeof window<"u"?window.location.pathname:"/",typeof window<"u"?window.location.hash:"",e));u.useEffect(()=>{if(typeof window<"u"){const i=window.location.hash.replace(/^#\/?/,"").trim();if(i.startsWith("node/")||i.startsWith("page/")){const l=i.startsWith("node/")?"node/":"page/",c=i.slice(l.length).replace(/\/$/,"").toLowerCase();(e?e.includes(c):!0)&&window.history.replaceState(null,"","/node/"+c+"/")}}const o=()=>{n(hs(window.location.pathname,window.location.hash,e))};return window.addEventListener("popstate",o),window.addEventListener("hashchange",o),()=>{window.removeEventListener("popstate",o),window.removeEventListener("hashchange",o)}},[e]);const s=u.useCallback(o=>{no();const i="/node/"+o+"/";typeof window<"u"&&(window.location.pathname!==i&&window.history.pushState(null,"",i),window.scrollTo({top:0,left:0,behavior:"instant"}),n(hs(window.location.pathname,window.location.hash,e)))},[e]),a=u.useCallback(o=>{no();const i=o&&o>=1?"/#stage-"+o:"/";typeof window<"u"&&(window.history.pushState(null,"",i),o||window.scrollTo({top:0,left:0,behavior:"instant"}),n(hs(window.location.pathname,window.location.hash,e)))},[e]);return{route:t.type,nodeId:t.nodeId,pageId:t.pageId,targetStage:t.targetStage,rawHash:t.rawHash,pathname:t.pathname,navigateToNode:s,navigateToPage:s,navigateToHome:a}}const db=lc,ub=35,hb=45,fb=180;function pb({enabled:e,activeStage:t,scrollZone:n,onNextStage:s,onPrevStage:a,onScrollToTop:o,onScrollToFooter:i,onDirectStage:l,cooldownMs:c=200}){const d=u.useRef(!1),h=u.useRef(null),p=u.useRef(0),f=u.useRef(null),m=u.useRef(0),g=u.useRef(0),b=u.useRef(!1),y=u.useRef(t);y.current=t;const S=u.useRef(n);S.current=n;const v=u.useRef({onNextStage:s,onPrevStage:a,onScrollToTop:o,onScrollToFooter:i,onDirectStage:l});v.current={onNextStage:s,onPrevStage:a,onScrollToTop:o,onScrollToFooter:i,onDirectStage:l};const k=u.useCallback((_=1200)=>{d.current=!0,h.current&&clearTimeout(h.current),h.current=setTimeout(()=>{d.current=!1,h.current=null},_+c)},[c]),x=u.useCallback(()=>{h.current&&(clearTimeout(h.current),h.current=null),h.current=setTimeout(()=>{d.current=!1,h.current=null},c)},[c]),I=u.useCallback(()=>{if(d.current)return;k();const _=S.current,T=y.current;_==="above"?v.current.onDirectStage(1):_==="inside"&&(T<5?v.current.onNextStage():v.current.onScrollToFooter())},[k]),N=u.useCallback(()=>{if(d.current)return;k();const _=S.current,T=y.current;_==="below"?v.current.onDirectStage(5):_==="inside"&&(T>1?v.current.onPrevStage():v.current.onScrollToTop())},[k]);return u.useEffect(()=>{if(!e||typeof window>"u")return;const _=document.documentElement,T=document.body;_.classList.add("landing-scroll-locked"),T.classList.add("landing-scroll-locked");const w=D=>!D||!(D instanceof HTMLElement)?!1:D.tagName==="INPUT"||D.tagName==="TEXTAREA"||D.tagName==="SELECT"||D.isContentEditable,M=D=>{if(!w(D.target)){if(D.preventDefault(),d.current){p.current=0;return}if(p.current+=D.deltaY,f.current&&clearTimeout(f.current),f.current=setTimeout(()=>{p.current=0},fb),Math.abs(p.current)>=ub){const W=p.current;p.current=0,W>0?I():N()}}},$=D=>{w(D.target)||D.touches.length===1&&(m.current=D.touches[0].clientY,g.current=D.touches[0].clientX,b.current=!0)},A=D=>{w(D.target)||D.preventDefault()},P=D=>{if(!b.current||(b.current=!1,d.current)||D.changedTouches.length===0)return;const W=m.current-D.changedTouches[0].clientY,H=g.current-D.changedTouches[0].clientX;Math.abs(W)>Math.abs(H)&&Math.abs(W)>=hb&&(W>0?I():N())},V=D=>{if(!w(D.target)){if(D.key==="ArrowDown"||D.key==="PageDown"||D.key==="ArrowRight")D.preventDefault(),I();else if(D.key==="ArrowUp"||D.key==="PageUp"||D.key==="ArrowLeft")D.preventDefault(),N();else if(D.key==="Home")D.preventDefault(),d.current||(k(),v.current.onScrollToTop());else if(D.key==="End")D.preventDefault(),d.current||(k(),v.current.onScrollToFooter());else if(["1","2","3","4","5"].includes(D.key)){D.preventDefault();const W=parseInt(D.key,10);d.current||(k(),v.current.onDirectStage(W))}}};return window.addEventListener("wheel",M,{passive:!1}),window.addEventListener("touchstart",$,{passive:!0}),window.addEventListener("touchmove",A,{passive:!1}),window.addEventListener("touchend",P,{passive:!0}),window.addEventListener("keydown",V,{passive:!1}),()=>{_.classList.remove("landing-scroll-locked"),T.classList.remove("landing-scroll-locked"),window.removeEventListener("wheel",M),window.removeEventListener("touchstart",$),window.removeEventListener("touchmove",A),window.removeEventListener("touchend",P),window.removeEventListener("keydown",V),h.current&&(clearTimeout(h.current),h.current=null),f.current&&(clearTimeout(f.current),f.current=null)}},[e,I,N,k]),{isTransitioning:d.current,lockTransition:k,unlockTransition:x}}function Fh(e){const t=e.replace(/^(node|page|section|sec)-/,"");return t==="source"||t==="source-proof"?"Evidence & Proof":t==="overview"?"Overview":t.split(/[-_]/).filter(Boolean).map(n=>n.charAt(0).toUpperCase()+n.slice(1).toLowerCase()).join(" ")}function mb(e,t='section[id], [data-toc-title][id], [data-toc="true"][id]',n=Fh){var i,l,c;const s=Array.from(e.querySelectorAll(t)),a=new Set,o=[];for(const d of s){const h=(i=d.id)==null?void 0:i.trim();if(!h||a.has(h))continue;a.add(h);const p=d.getAttribute("data-toc-title")||d.getAttribute("data-title"),f=d.getAttribute("aria-label"),m=d.querySelector('h1, h2, h3, [class*="sectionTitle"], [class*="SectionTitle"]'),g=(l=m==null?void 0:m.textContent)==null?void 0:l.trim(),b=p||f||g||n(h),y=d.getAttribute("data-toc-numbered")==="false"||d.getAttribute("data-numbered")==="false"||d.getAttribute("data-toc-number")==="false"||d.getAttribute("data-toc-number")==="none"||d.getAttribute("data-toc-number")==="";let S;if(!y){const v=d.getAttribute("data-toc-number")||d.getAttribute("data-number"),k=d.querySelector('[class*="sectionNumber"], [class*="SectionNumber"]'),x=(c=k==null?void 0:k.textContent)==null?void 0:c.replace(/^Section\s*/i,"").trim();S=v&&v!=="false"?v:x||void 0}o.push({id:h,label:b,number:S,href:`#${h}`})}return o}function gb(e={}){const{containerId:t="node-content",containerRef:n,sectionSelector:s,formatIdToTitle:a=Fh}=e,[o,i]=u.useState([]),l=u.useRef(null);return u.useEffect(()=>{if(typeof window>"u")return;const c=()=>n!=null&&n.current?n.current:t?document.getElementById(t):null,d=()=>{const m=c();if(!m){i([]);return}const g=mb(m,s,a);i(b=>b.length===g.length&&b.every((y,S)=>y.id===g[S].id&&y.label===g[S].label&&y.number===g[S].number&&y.href===g[S].href)?b:g)},h=()=>{l.current===null&&(l.current=requestAnimationFrame(()=>{d(),l.current=null}))};d();const p=c();if(!p){h();return}const f=new MutationObserver(()=>{h()});return f.observe(p,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["id","data-toc-title","data-title","data-toc-number","data-toc-numbered","data-number","data-numbered","aria-label"]}),()=>{f.disconnect(),l.current!==null&&(cancelAnimationFrame(l.current),l.current=null)}},[t,n,s,a]),o}const vb=JSON.parse('[{"id":"access","index":0,"nodeNumber":1,"title":"Foundation & Core Access","subtitle":"Architectural Baselines & Universal Access","summary":"Establishing resilient foundational scaffolding, token infrastructure, and zero-compromise accessibility contracts across distributed endpoints.","tagline":"Stage 01 · Baseline Protocol","accentColor":"#0284c7","accentTint":"#e0f2fe","heroImage":{"src":"https://images.unsplash.com/photo-1451187580459-43490279c0fa?w=1200&q=80&auto=format&fit=crop","alt":"Global network grid symbolizing universal access and infrastructural foundation","caption":"Foundational architectural baseline providing universal access and type-safe contracts.","showCaption":true},"annotation":"Stage 01 establishes core design tokens and foundational data pipelines.","stages":[{"step":1,"stageName":"Where We Are","narrative":"Heterogeneous legacy systems often suffer from fragmented styling tokens and unverified endpoints, creating brittle client integration boundaries."},{"step":2,"stageName":"What We Need","narrative":"A decoupled, token-first design infrastructure with deterministic schema verification and strict mathematical coordinate scaling."},{"step":3,"stageName":"What We Are Doing","narrative":"Isolating layout engines, compiling SVG Bézier tracks, and standardizing AST document models with zero institutional hardwiring."},{"step":4,"stageName":"What We Are Achieving","narrative":"Sub-millisecond edge resolution, 100% token purity across 247 components, and strict WCAG 2.1 AA keyboard accessibility."},{"step":5,"stageName":"How We Serve Users","narrative":"Empowering operators and technical teams to explore dynamic data sequences with complete confidence and evaluative ease."}],"sourceItems":[{"id":"src-acc-01","title":"Core Architecture Topology Blueprint","dateStamp":"2026-01-15","photo":{"src":"https://images.unsplash.com/photo-1504639725590-34d0984388bd?w=800&q=80","alt":"System architecture topology diagram on terminal","caption":"Baseline system architecture topology specification.","showCaption":false},"imageSrc":"https://images.unsplash.com/photo-1504639725590-34d0984388bd?w=800&q=80","reference":"RFC-1014 Architecture Specification"},{"id":"src-acc-02","title":"Design Token Distribution Matrix","dateStamp":"2026-02-10","photo":{"src":"https://images.unsplash.com/photo-1551288049-bebda4e38f71?w=800&q=80","alt":"Design system token verification dashboard","caption":"Mathematical color space tokens and semantic alias hierarchy.","showCaption":false},"imageSrc":"https://images.unsplash.com/photo-1551288049-bebda4e38f71?w=800&q=80","reference":"Design System RFC-880"}],"metadata":{"category":"infrastructure","stability":"stable","version":"2.4.0"}},{"id":"equity","index":1,"nodeNumber":2,"title":"Discovery & Data Equity","subtitle":"Democratic Inspection & Balanced Distribution","summary":"Delivering transparent exploration channels and equal information density for both mobile handhelds and ultra-wide workstations.","tagline":"Stage 02 · Exploratory Protocol","accentColor":"#881337","accentTint":"#ffe4e6","heroImage":{"src":"https://images.unsplash.com/photo-1518770660439-4636190af475?w=1200&q=80&auto=format&fit=crop","alt":"Microprocessor circuitry illustrating distributed data equity and telemetry flows","caption":"Transparent exploration channels distributing balanced telemetry across user touchpoints.","showCaption":true},"annotation":"Stage 02 ensures equal visual ergonomics across diverse client form factors.","stages":[{"step":1,"stageName":"Where We Are","narrative":"Dense technical metrics often overload non-specialist users, while mobile layouts frequently strip essential context or truncate data series."},{"step":2,"stageName":"What We Need","narrative":"Progressive disclosure models that present high-level clarity first, followed by effortless drill-downs to raw CSV records and mathematical proofs."},{"step":3,"stageName":"What We Are Doing","narrative":"Implementing adaptive 2-column editorial grids with sticky rail TOCs on desktop and non-intrusive mobile capsule navigators."},{"step":4,"stageName":"What We Are Achieving","narrative":"Zero cognitive friction, single unified breakpoint transitions at 1024px, and tactile touch interaction on high-density displays."},{"step":5,"stageName":"How We Serve Users","narrative":"Ensuring every stakeholder, from field inspectors to executive coordinators, inspects identical verified truth."}],"sourceItems":[{"id":"src-eq-01","title":"Responsive Viewport Parity Audit","dateStamp":"2026-03-01","photo":{"src":"https://images.unsplash.com/photo-1581291518857-4e27b48ff24e?w=800&q=80","alt":"Responsive design testing across multi-screen matrix","caption":"Adaptive layout verification across mobile and desktop viewports.","showCaption":false},"imageSrc":"https://images.unsplash.com/photo-1581291518857-4e27b48ff24e?w=800&q=80","reference":"UX Benchmark Audit 2026-B"}],"metadata":{"category":"ergonomics","stability":"active","version":"2.4.0"}},{"id":"quality","index":2,"nodeNumber":3,"title":"Architecture & System Quality","subtitle":"Rigorous AST Schemas & Pure Vector Visualizers","summary":"Transforming arbitrary tabular streams into high-precision vector charts, interactive drawer controls, and D3 mathematical curves.","tagline":"Stage 03 · Analytical Protocol","accentColor":"#f59e0b","accentTint":"#fef3c7","heroImage":{"src":"https://images.unsplash.com/photo-1460925895917-afdab827c52f?w=1200&q=80&auto=format&fit=crop","alt":"Financial analytics and vector graphics charting on modern glass interface","caption":"Dynamic vector charting studio rendering real-time analytical curves.","showCaption":true},"annotation":"Stage 03 anchors vector charting capabilities with instant synchronous rendering.","stages":[{"step":1,"stageName":"Where We Are","narrative":"Third-party charting libraries frequently introduce heavy canvas bloat, sluggish bundle sizes, and unstyled tooltips that break design harmony."},{"step":2,"stageName":"What We Need","narrative":"Pure SVG visualizers driven directly by CSS tokens with zero layout thrashing, responsive tooltips, and instant CSV verification receipts."},{"step":3,"stageName":"What We Are Doing","narrative":"Crafting native Bar, Line, Donut, Scatter, and Histogram renderers powered by D3 mathematical scales and memoized SVG paths."},{"step":4,"stageName":"What We Are Achieving","narrative":"Under 10ms initial paint time, interactive drawer parameterization, and LOESS polynomial smoothing curves."},{"step":5,"stageName":"How We Serve Users","narrative":"Enabling precise, verifiable visual analytics without sacrificing page speed or editorial restraint."}],"sourceItems":[{"id":"src-qual-01","title":"Vector Rendering Performance Profile","dateStamp":"2026-03-20","photo":{"src":"https://images.unsplash.com/photo-1551836022-d5d88e9218df?w=800&q=80","alt":"Performance benchmark graphs and telemetry monitor","caption":"Sub-10ms render latency benchmark across 5000 SVG points.","showCaption":false},"imageSrc":"https://images.unsplash.com/photo-1551836022-d5d88e9218df?w=800&q=80","reference":"Performance Profiling Report Q1"}],"metadata":{"category":"visualization","stability":"active","version":"2.4.0"}},{"id":"resiliency","index":3,"nodeNumber":4,"title":"Validation & Resilient Integrity","subtitle":"Edge-Cached Redundancy & Local-First Durability","summary":"Hardening client persistence with optimistic transactions, cryptographic verification, and instant rollback safety across offline states.","tagline":"Stage 04 · Verification Protocol","accentColor":"#15803d","accentTint":"#dcfce7","heroImage":{"src":"https://images.unsplash.com/photo-1526374965328-7f61d4dc18c5?w=1200&q=80&auto=format&fit=crop","alt":"Encrypted code stream and cryptographic matrix symbolizing data resiliency","caption":"Local-first persistence architecture with multi-tier cryptographic safeguards.","showCaption":true},"annotation":"Stage 04 provides resilient transactional guarantees and rollback safety.","stages":[{"step":1,"stageName":"Where We Are","narrative":"Network intermittency and cloud sync timeouts risk user data loss when editing dynamic canvas structures in the browser."},{"step":2,"stageName":"What We Need","narrative":"A dual-channel storage engine combining synchronous localStorage caching with asynchronous IndexedDB transactional undo/redo stacks."},{"step":3,"stageName":"What We Are Doing","narrative":"Scaffolding 50-step undo/redo circular ring buffers and automatic recovery procedures for unsaved draft modifications."},{"step":4,"stageName":"What We Are Achieving","narrative":"Instantaneous optimistic UI dispatch, zero lost keystrokes, and clean separation between draft editing and published channels."},{"step":5,"stageName":"How We Serve Users","narrative":"Providing an authoring environment where creative changes can be tested boldly with immediate rollback protection."}],"sourceItems":[{"id":"src-res-01","title":"Offline Durability & Stress Testing Logs","dateStamp":"2026-04-05","photo":{"src":"https://images.unsplash.com/photo-1544197150-b99a580bb7a8?w=800&q=80","alt":"Server rack cabling and edge infrastructure cluster","caption":"Cluster redundancy tests under simulated network partitioning.","showCaption":false},"imageSrc":"https://images.unsplash.com/photo-1544197150-b99a580bb7a8?w=800&q=80","reference":"Resilience Test Report SEC-44"}],"metadata":{"category":"storage","stability":"active","version":"2.4.0"}},{"id":"governance","index":4,"nodeNumber":5,"title":"Scale & Coordinated Governance","subtitle":"Multi-Tenant Orchestration & Versioned History","summary":"Enabling collaborative multi-editor workflows with audit logging, pin-secured publication gates, and tenant autonomy.","tagline":"Stage 05 · Governance Protocol","accentColor":"#d97706","accentTint":"#ffedd5","heroImage":{"src":"https://images.unsplash.com/photo-1507679799987-c73779587ccf?w=1200&q=80&auto=format&fit=crop","alt":"Modern collaborative architectural workspace representing team governance","caption":"Collaborative coordinator governance with multi-editor publication checkpoints.","showCaption":true},"annotation":"Stage 05 manages multi-editor deployment gates and historical audit logs.","stages":[{"step":1,"stageName":"Where We Are","narrative":"Unregulated deployments and uncoordinated concurrent edits cause staging collisions and inadvertent overwrites in production."},{"step":2,"stageName":"What We Need","narrative":"Role-gated coordinator mode secured by salted SHA-256 PIN authentication and explicit staging review checkpoints."},{"step":3,"stageName":"What We Are Doing","narrative":"Integrating DevPinModal, DevModeBadge, DevLockService, and UniversalEditModal into a unified coordinator dock."},{"step":4,"stageName":"What We Are Achieving","narrative":"Cryptographically verified release pipelines, tamper-evident publication records, and instantaneous edge KV sync."},{"step":5,"stageName":"How We Serve Users","narrative":"Delivering enterprise-grade administrative governance with complete transparency and zero operational downtime."}],"sourceItems":[{"id":"src-gov-01","title":"Cryptographic Audit & Access Logs","dateStamp":"2026-04-18","photo":{"src":"https://images.unsplash.com/photo-1563986768609-322da13575f3?w=800&q=80","alt":"Cryptographic key signature and audit trail verification UI","caption":"Cryptographic commit verification for edge deployment pipeline.","showCaption":false},"imageSrc":"https://images.unsplash.com/photo-1563986768609-322da13575f3?w=800&q=80","reference":"Governance Standard GOV-2026"}],"metadata":{"category":"governance","stability":"active","version":"2.4.0"}}]'),Ge={header:"_header_1k4ie_8",kicker:"_kicker_1k4ie_15",kickerDot:"_kickerDot_1k4ie_27",title:"_title_1k4ie_34",subtitle:"_subtitle_1k4ie_44",pinContainer:"_pinContainer_1k4ie_53",nativeHiddenInput:"_nativeHiddenInput_1k4ie_63",slotsRow:"_slotsRow_1k4ie_78",pinSlot:"_pinSlot_1k4ie_85",pinSlotFilled:"_pinSlotFilled_1k4ie_98",pinSlotActive:"_pinSlotActive_1k4ie_103",pinSlotDisabled:"_pinSlotDisabled_1k4ie_109",pinDot:"_pinDot_1k4ie_115",pinCaret:"_pinCaret_1k4ie_124",shake:"_shake_1k4ie_152",statusBox:"_statusBox_1k4ie_157",statusText:"_statusText_1k4ie_165",errorText:"_errorText_1k4ie_173",lockoutText:"_lockoutText_1k4ie_178",verifyingText:"_verifyingText_1k4ie_184",successText:"_successText_1k4ie_189",actions:"_actions_1k4ie_195"},Uh=()=>{const{isPinModalOpen:e,pinState:t,attemptsRemaining:n,lockoutRemainingSeconds:s,isRenewal:a,closePinModal:o,submitPin:i}=Oe(),[l,c]=u.useState(""),[d,h]=u.useState(!1),[p,f]=u.useState(!1),m=u.useRef(null),g=t==="locked_out"||s>0,b=t==="verifying";u.useEffect(()=>{var x;if(e&&(c(""),f(!1),!g)){(x=m.current)==null||x.focus();const I=requestAnimationFrame(()=>{var _;(_=m.current)==null||_.focus()}),N=setTimeout(()=>{var _;(_=m.current)==null||_.focus()},30);return()=>{cancelAnimationFrame(I),clearTimeout(N)}}},[e,g]),u.useEffect(()=>{if(t==="error"){f(!0);const x=setTimeout(()=>{var I;f(!1),c(""),(I=m.current)==null||I.focus()},450);return()=>clearTimeout(x)}},[t]);const y=u.useCallback(x=>{if(g||b)return;const I=x.target.value.replace(/\D/g,"").slice(0,4);c(I),I.length===4&&i(I)},[g,b,i]),S=u.useCallback(x=>{x.key==="Enter"&&l.length===4&&!g&&!b&&(x.preventDefault(),i(l))},[l,g,b,i]),v=u.useCallback(()=>{l.length===4&&!g&&!b&&i(l)},[l,g,b,i]),k=x=>{const I=Math.floor(x/60),N=x%60;return`${I}:${N<10?"0":""}${N}`};return r.jsxs(bt,{isOpen:e,onClose:o,initialFocusRef:m,onConfirm:v,maxWidth:"440px",ariaLabelledBy:"dev-pin-title",ariaDescribedBy:"dev-pin-desc",children:[r.jsxs("div",{className:Ge.header,children:[r.jsxs("div",{className:Ge.kicker,children:[r.jsx("span",{className:Ge.kickerDot,"aria-hidden":"true"}),r.jsx("span",{children:a?"Session Renewal":"Developer Access"})]}),r.jsx("h2",{id:"dev-pin-title",className:Ge.title,children:a?"Renew Developer Session":"Developer Authentication"}),r.jsx("p",{id:"dev-pin-desc",className:Ge.subtitle,children:a?"Enter PIN to renew session.":"Enter 4-digit PIN."})]}),r.jsxs("div",{className:`${Ge.pinContainer} ${p?Ge.shake:""}`,onClick:()=>{var x;!g&&!b&&((x=m.current)==null||x.focus())},children:[r.jsx("input",{ref:m,type:"password",inputMode:"numeric",pattern:"[0-9]*",maxLength:4,value:l,onChange:y,onKeyDown:S,onFocus:()=>h(!0),onBlur:()=>h(!1),disabled:g||b,className:Ge.nativeHiddenInput,autoComplete:"off","data-autofocus":!0,"aria-label":"4-digit Developer PIN"}),r.jsx("div",{className:Ge.slotsRow,"aria-hidden":"true",children:[0,1,2,3].map(x=>{const I=!!l[x],N=d&&!g&&!b&&(l.length===x||l.length===4&&x===3);return r.jsx("div",{className:`
38
- ${Ge.pinSlot}
39
- ${I?Ge.pinSlotFilled:""}
40
- ${N?Ge.pinSlotActive:""}
41
- ${g||b?Ge.pinSlotDisabled:""}
42
- `,children:I?r.jsx("span",{className:Ge.pinDot}):N?r.jsx("span",{className:Ge.pinCaret}):null},x)})})]}),r.jsx("div",{className:Ge.statusBox,children:g?r.jsxs("p",{className:`${Ge.statusText} ${Ge.lockoutText}`,children:["Too many failed attempts. Please wait ",k(s)]}):b?r.jsx("p",{className:`${Ge.statusText} ${Ge.verifyingText}`,children:"Verifying..."}):t==="error"?r.jsxs("p",{className:`${Ge.statusText} ${Ge.errorText}`,children:["Incorrect PIN. ",n," ",n===1?"attempt":"attempts"," remaining."]}):t==="success"?r.jsx("p",{className:`${Ge.statusText} ${Ge.successText}`,children:"Authenticated."}):n<5?r.jsxs("p",{className:Ge.statusText,children:[n," attempts remaining."]}):null}),r.jsx("div",{className:Ge.actions,children:r.jsx(me,{variant:"secondary",size:"sm",type:"button",onClick:o,children:"Cancel"})})]})},Ue={container:"_container_10oun_12",subtitle:"_subtitle_10oun_20",timelineList:"_timelineList_10oun_29",emptyState:"_emptyState_10oun_36",historyList:"_historyList_10oun_47",historyItem:"_historyItem_10oun_56",itemMain:"_itemMain_10oun_79",itemTitleRow:"_itemTitleRow_10oun_87",itemTitle:"_itemTitle_10oun_87",itemMeta:"_itemMeta_10oun_103",metaInterval:"_metaInterval_10oun_113",metaDot:"_metaDot_10oun_125",metaTimestamp:"_metaTimestamp_10oun_131",itemAction:"_itemAction_10oun_138",confirmModalContent:"_confirmModalContent_10oun_146",confirmHeader:"_confirmHeader_10oun_153",confirmTitle:"_confirmTitle_10oun_159",confirmDesc:"_confirmDesc_10oun_169",confirmNotice:"_confirmNotice_10oun_177",confirmActions:"_confirmActions_10oun_185"};function ca(e){return e?e.replace(/\s*\([^)]*\)/g,"").trim():""}function bb(e){try{const t=new Date(e).getTime();if(Number.isNaN(t))return"Recently";const n=Date.now(),s=Math.max(0,n-t),a=Math.floor(s/1e3),o=Math.floor(a/60),i=Math.floor(o/60),l=Math.floor(i/24),c=Math.floor(l/30),d=Math.floor(l/365);return o<1?"just now":o<60?`${o}m`:i<24?`${i}h`:l<30?`${l}d`:c<12?`${c}mo`:`${d}y`}catch{return"Recently"}}function yb(e){try{const t=new Date(e);return Number.isNaN(t.getTime())?"Recently":t.toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric",hour:"2-digit",minute:"2-digit"})}catch{return"Recently"}}function zh(e){if(e.id==="snap-system-baseline"||!!(e.title&&e.title.toLowerCase().includes("baseline")))return ca(e.title)||"System Baseline";const n="description"in e&&e.description?e.description:"notes"in e&&e.notes?e.notes:"",s=ca(n);if(s)return s;const a=ca(e.title);return a&&!a.toLowerCase().includes("published revision")&&!a.toLowerCase().includes("published version")?a:"Revision"}const Gh=u.memo(({snapshot:e,isCurrentLive:t,onRequestRestore:n})=>{const s=e.id==="snap-system-baseline"||!!(e.title&&e.title.toLowerCase().includes("baseline")),a="description"in e&&e.description?e.description:"notes"in e&&e.notes?e.notes:"",o=ca(a),i=ca(e.title);let l="";return s?l=i||"System Baseline":o?l=o:l=i&&!i.toLowerCase().includes("published revision")&&!i.toLowerCase().includes("published version")?i:"Revision",r.jsxs("li",{className:Ue.historyItem,children:[r.jsxs("div",{className:Ue.itemMain,children:[r.jsxs("div",{className:Ue.itemTitleRow,children:[r.jsx("span",{className:Ue.itemTitle,children:l}),t?r.jsx(qs,{label:"Live",variant:"primary",size:"sm"}):null]}),r.jsxs("div",{className:Ue.itemMeta,children:[r.jsx("span",{className:Ue.metaInterval,children:bb(e.createdAt)}),r.jsx("span",{className:Ue.metaDot,"aria-hidden":"true",children:"•"}),r.jsx("time",{className:Ue.metaTimestamp,dateTime:e.createdAt,children:yb(e.createdAt)})]})]}),!t&&r.jsx("div",{className:Ue.itemAction,children:r.jsx(me,{variant:"secondary",size:"sm",type:"button",onClick:()=>n(e),"aria-label":`Restore "${l}" to Draft`,children:"Load as Draft"})})]})});Gh.displayName="HistoryTimelineRow";const Wh=({isOpen:e,onClose:t,onRestored:n})=>{const[s,a]=u.useState([]),[o,i]=u.useState(null),[l,c]=u.useState(!1),[d,h]=u.useState(null),[p,f]=u.useState("success"),[m,g]=u.useState(null),[b,y]=u.useState(!1),S=u.useCallback(async()=>{c(!0);try{await Fi().catch(()=>{});const I=await Bd();if(I.length>0){a(I);const N=I.find(_=>_.isActive);i(N?N.id:cn())}else{const N=In();a(N);const _=N.find(T=>T.isActive);i(_?_.id:cn())}}catch{const I=In();a(I);const N=I.find(_=>_.isActive);i(N?N.id:cn())}finally{c(!1)}},[]);u.useEffect(()=>e?(S(),Dd(()=>{S()})):void 0,[e,S]);const v=u.useCallback(I=>{g(I)},[]),k=u.useCallback(()=>{if(!m)return;const I=m;g(null);const N=zi(I),_=zh(I);N?(n==null||n(_),t()):(h("Failed to restore draft."),f("error"))},[m,n,t]),x=u.useCallback(()=>{y(!1);const I=Ja(!1);zi(I)?(n==null||n("System Baseline"),t()):(h("Failed to restore default baseline."),f("error"))},[n,t]);return e?r.jsxs(r.Fragment,{children:[r.jsx(Vl,{isOpen:e,onClose:t,position:"right",size:"md",title:"History",showCloseButton:!0,ariaLabel:"Revision history and published configurations",ariaLabelledBy:"history-drawer-title",ariaDescribedBy:"history-drawer-desc",footerLeft:r.jsx(me,{variant:"ghost",size:"sm",type:"button",onClick:()=>y(!0),title:"Restore workspace back to official factory default baseline",children:"Restore to default"}),footerRight:r.jsx(me,{variant:"secondary",size:"sm",type:"button",onClick:t,children:"Close"}),children:r.jsxs("div",{className:Ue.container,children:[r.jsx("p",{id:"history-drawer-desc",className:Ue.subtitle,children:"Revision history and published configurations."}),r.jsx("div",{className:Ue.timelineList,children:l&&s.length===0?r.jsx("div",{className:Ue.emptyState,children:"Loading history..."}):s.length===0?r.jsx("div",{className:Ue.emptyState,children:"No saved configurations yet."}):r.jsx("ul",{className:Ue.historyList,children:s.map(I=>r.jsx(Gh,{snapshot:I,isCurrentLive:o?I.id===o:!!("isActive"in I&&I.isActive),onRequestRestore:v},I.id))})})]})}),m&&r.jsx(bt,{isOpen:!!m,onClose:()=>g(null),maxWidth:460,role:"alertdialog",ariaLabelledBy:"preview-confirm-title",ariaDescribedBy:"preview-confirm-desc",children:r.jsxs("div",{className:Ue.confirmModalContent,children:[r.jsxs("div",{className:Ue.confirmHeader,children:[r.jsx("h3",{id:"preview-confirm-title",className:Ue.confirmTitle,children:"Load as Draft?"}),r.jsxs("p",{id:"preview-confirm-desc",className:Ue.confirmDesc,children:["Are you sure you want to load"," ",r.jsxs("strong",{children:['"',zh(m),'"']})," into your Developer Mode draft to preview and edit?"]}),r.jsx("p",{className:Ue.confirmNotice,children:"Your live public portal will remain unchanged until you review and publish."})]}),r.jsxs("div",{className:Ue.confirmActions,children:[r.jsx(me,{variant:"ghost",size:"sm",type:"button",onClick:()=>g(null),children:"Cancel"}),r.jsx(me,{variant:"primary",size:"sm",type:"button",onClick:k,children:"Load as Draft"})]})]})}),b&&r.jsx(bt,{isOpen:b,onClose:()=>y(!1),maxWidth:460,role:"alertdialog",ariaLabelledBy:"restore-default-title",ariaDescribedBy:"restore-default-desc",children:r.jsxs("div",{className:Ue.confirmModalContent,children:[r.jsxs("div",{className:Ue.confirmHeader,children:[r.jsx("h3",{id:"restore-default-title",className:Ue.confirmTitle,children:"Restore System Baseline?"}),r.jsx("p",{id:"restore-default-desc",className:Ue.confirmDesc,children:"Are you sure you want to reset your Developer Mode draft back to the official baseline?"}),r.jsx("p",{className:Ue.confirmNotice,children:"All unpublished draft changes across all 5 nodes will be reset to the original baseline. Your live portal remains untouched until you publish."})]}),r.jsxs("div",{className:Ue.confirmActions,children:[r.jsx(me,{variant:"ghost",size:"sm",type:"button",onClick:()=>y(!1),children:"Cancel"}),r.jsx(me,{variant:"primary",size:"sm",type:"button",onClick:x,children:"Restore Baseline"})]})]})}),d?r.jsx(Zt,{message:d,type:p,onDismiss:()=>h(null)}):null]}):null},mt={form:"_form_11pme_7",fieldGroup:"_fieldGroup_11pme_14",textarea:"_textarea_11pme_19",footer:"_footer_11pme_46",meta:"_meta_11pme_53",shortcutHint:"_shortcutHint_11pme_59",kbd:"_kbd_11pme_64",charCounter:"_charCounter_11pme_81",charCounterLimit:"_charCounterLimit_11pme_87",error:"_error_11pme_92",actions:"_actions_11pme_102",staleContent:"_staleContent_11pme_118",staleMessage:"_staleMessage_11pme_124",btnDanger:"_btnDanger_11pme_132"},cc=({isOpen:e,onClose:t,onPublished:n})=>{const[s,a]=u.useState(""),[o,i]=u.useState(!1),[l,c]=u.useState(null),[d,h]=u.useState(!1);if(u.useEffect(()=>{e||(a(""),i(!1),c(null),h(!1))},[e]),!e)return null;const p=Ds();if(p.isStale&&!d)return r.jsx(bt,{isOpen:e,onClose:o?()=>{}:t,closeOnEscape:!o,title:"Published Version Changed",maxWidth:"440px",role:"dialog",children:r.jsxs("div",{className:mt.staleContent,children:[r.jsxs("p",{className:mt.staleMessage,children:["A newer snapshot (",p.currentActiveId,") was published by another session. Publishing now will overwrite it."]}),r.jsxs("div",{className:mt.actions,children:[r.jsx(me,{variant:"secondary",size:"sm",type:"button",onClick:()=>{ui(),t()},children:"Discard Draft"}),r.jsx(me,{variant:"primary",size:"sm",type:"button",className:mt.btnDanger,onClick:()=>h(!0),children:"Publish Anyway"})]})]})});const f=s.trim(),m=f.length>3,g=async S=>{if(S&&S.preventDefault(),!(!m||o)){i(!0),c(null);try{const v=await Pd(f,void 0,void 0,{forcePublish:!0});v.success?(n==null||n(v.snapshot,v.cloudSynced),t()):c(v.error||"Failed to publish version.")}catch{c("Unexpected error during publishing.")}finally{i(!1)}}},b=S=>{if(S.key==="Escape"&&o){S.preventDefault();return}(S.metaKey||S.ctrlKey)&&S.key==="Enter"&&(S.preventDefault(),m&&!o&&g())},y=typeof navigator<"u"&&(/Mac|iPod|iPhone|iPad/.test(navigator.platform)||/Macintosh|MacIntel|MacPPC|Mac68K/.test(navigator.userAgent));return r.jsx(bt,{isOpen:e,onClose:o?()=>{}:t,closeOnEscape:!o,title:"Publish Changes",maxWidth:"440px",role:"dialog",children:r.jsxs("form",{className:mt.form,onSubmit:g,children:[r.jsx("div",{className:mt.fieldGroup,children:r.jsx("textarea",{id:"publish-changelog",className:mt.textarea,placeholder:"What changed in this version?",value:s,onChange:S=>a(S.target.value),onKeyDown:b,rows:3,maxLength:400,autoFocus:!0,disabled:o,"aria-label":"Describe what changed in this version",required:!0})}),l&&r.jsx("p",{className:mt.error,role:"alert",children:l}),r.jsxs("div",{className:mt.footer,children:[r.jsxs("div",{className:mt.meta,children:[r.jsx("span",{className:mt.shortcutHint,title:y?"Press ⌘+Enter to publish":"Press Ctrl+Enter to publish","aria-label":y?"Press Command plus Enter to publish":"Press Control plus Enter to publish",children:r.jsx("kbd",{className:mt.kbd,children:y?"⌘↵":"Ctrl+↵"})}),f.length>0&&f.length<4&&r.jsx("span",{className:mt.charCounter,"aria-live":"polite",children:"Min 4 characters"}),s.length>=300&&r.jsxs("span",{className:`${mt.charCounter} ${s.length>=400?mt.charCounterLimit:""}`,"aria-live":"polite",children:[s.length,"/400"]})]}),r.jsxs("div",{className:mt.actions,children:[r.jsx(me,{variant:"secondary",size:"sm",type:"button",onClick:t,disabled:o,children:"Cancel"}),r.jsx(me,{variant:"primary",size:"sm",type:"submit",disabled:!m||o,children:o?"Publishing...":"Publish"})]})]})]})})},qe={floatingCapsule:"_floatingCapsule_4z54a_8",statusPill:"_statusPill_4z54a_31",statusIcon:"_statusIcon_4z54a_45",statusTitle:"_statusTitle_4z54a_55",sessionTime:"_sessionTime_4z54a_62",cloudSyncIndicator:"_cloudSyncIndicator_4z54a_70",actionButton:"_actionButton_4z54a_79",buttonDisabled:"_buttonDisabled_4z54a_124",actionIcon:"_actionIcon_4z54a_130",actionLabel:"_actionLabel_4z54a_149"},_b=({className:e})=>r.jsxs("svg",{className:e,width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[r.jsx("polyline",{points:"16 16 12 12 8 16"}),r.jsx("line",{x1:"12",y1:"12",x2:"12",y2:"21"}),r.jsx("path",{d:"M20.39 18.39A5 5 0 0 0 18 9h-1.26A8 8 0 1 0 3 16.3"})]}),wb=({className:e})=>r.jsx("svg",{className:e,width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:r.jsx("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"})}),Sb=({className:e})=>r.jsxs("svg",{className:e,width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[r.jsx("polyline",{points:"1 4 1 10 7 10"}),r.jsx("path",{d:"M3.51 15a9 9 0 1 0 2.13-9.36L1 10"})]}),kb=({className:e})=>r.jsxs("svg",{className:e,width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[r.jsx("polyline",{points:"23 4 23 10 17 10"}),r.jsx("path",{d:"M20.49 15a9 9 0 1 1-2.12-9.36L23 10"})]}),Cb=({className:e})=>r.jsxs("svg",{className:e,width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[r.jsx("circle",{cx:"12",cy:"12",r:"10"}),r.jsx("polyline",{points:"12 6 12 12 16 14"})]}),xb=({className:e})=>r.jsxs("svg",{className:e,width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[r.jsx("path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"}),r.jsx("polyline",{points:"16 17 21 12 16 7"}),r.jsx("line",{x1:"21",y1:"12",x2:"9",y2:"12"})]}),Hh=()=>{const{isDevMode:e,isDesktop:t,sessionRemainingMinutes:n,requestExitDevMode:s,cloudSyncStatus:a}=Oe(),{canUndo:o,canRedo:i,lastActionDescription:l,nextRedoDescription:c,undo:d,redo:h}=Ks(),[p,f]=u.useState(!1),[m,g]=u.useState(!1),[b,y]=u.useState(null),[S,v]=u.useState("success");if(!e||!t)return null;const k=typeof navigator<"u"&&/Mac|iPod|iPhone|iPad/.test(navigator.platform),x=k?"⌘Z":"Ctrl+Z",I=k?"⇧⌘Z":"Ctrl+Shift+Z",N=o?l?`Undo: ${l} (${x})`:`Undo (${x})`:`Undo (${x})`,_=i?c?`Redo: ${c} (${I})`:`Redo (${I})`:`Redo (${I})`;return r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:qe.floatingCapsule,role:"status","aria-live":"polite","aria-label":"Developer mode is active",children:[r.jsxs("div",{className:qe.statusPill,children:[r.jsx(wb,{className:qe.statusIcon}),r.jsxs("span",{className:qe.statusTitle,children:["Dev Mode",r.jsx(Xn,{text:"Lets you edit the page. Changes are saved as a private draft until you publish.",label:"Dev Mode"})]}),r.jsxs("span",{className:qe.sessionTime,title:`${n} minutes remaining in session`,children:[n,"m left"]}),a&&r.jsx("span",{className:qe.cloudSyncIndicator,title:a==="saving"?"Saving draft changes to cloud...":a==="saved"?"All changes saved to cloud draft":a==="offline"?"Operating in local memory draft":"Cloud sync error",children:a==="saving"?"◌ Saving...":a==="error"?"⚠ Sync error":""})]}),r.jsxs("button",{type:"button",className:`${qe.actionButton} ${o?"":qe.buttonDisabled}`,onClick:T=>{T.preventDefault(),T.stopPropagation(),o&&d()},disabled:!o,"aria-label":"Undo last change",title:N,children:[r.jsx(Sb,{className:qe.actionIcon}),r.jsx("span",{className:qe.actionLabel,children:"Undo"})]}),r.jsxs("button",{type:"button",className:`${qe.actionButton} ${i?"":qe.buttonDisabled}`,onClick:T=>{T.preventDefault(),T.stopPropagation(),i&&h()},disabled:!i,"aria-label":"Redo last change",title:_,children:[r.jsx(kb,{className:qe.actionIcon}),r.jsx("span",{className:qe.actionLabel,children:"Redo"})]}),r.jsxs("button",{type:"button",className:qe.actionButton,onClick:T=>{T.preventDefault(),T.stopPropagation(),f(!0)},"aria-label":"Open History",title:"Revision history",children:[r.jsx(Cb,{className:qe.actionIcon}),r.jsx("span",{className:qe.actionLabel,children:"History"})]}),r.jsxs("button",{type:"button",className:qe.actionButton,onClick:T=>{T.preventDefault(),T.stopPropagation(),g(!0)},"aria-label":"Publish Changes",title:"Publish changes live to portal",children:[r.jsx(_b,{className:qe.actionIcon}),r.jsx("span",{className:qe.actionLabel,children:"Publish"})]}),r.jsxs("button",{type:"button",className:qe.actionButton,onClick:T=>{T.preventDefault(),T.stopPropagation(),s()},"aria-label":"Exit Developer Mode",children:[r.jsx(xb,{className:qe.actionIcon}),r.jsx("span",{className:qe.actionLabel,children:"Exit"})]})]}),r.jsx(Wh,{isOpen:p,onClose:()=>f(!1),onRestored:T=>{const w=T.replace(/\s*\([^)]*\)/g,"").trim(),M=w==="System Baseline"?"Loaded official factory baseline into draft preview. Review and click Publish to make live.":`Loaded "${w}" into draft preview. Review changes and click Publish to make live.`;y(M),v("success")}}),r.jsx(cc,{isOpen:m,onClose:()=>g(!1),onPublished:(T,w)=>{w===!1?(y("Published locally. Cloud sync pending reconnection."),v("info")):(y("Published changes live to portal."),v("success"))}}),b&&r.jsx(Zt,{message:b,type:S,onDismiss:()=>y(null)})]})},Tt={content:"_content_150bw_8",header:"_header_150bw_15",title:"_title_150bw_21",subtitle:"_subtitle_150bw_31",metaList:"_metaList_150bw_40",metaItem:"_metaItem_150bw_47",metaLabel:"_metaLabel_150bw_53",metaValue:"_metaValue_150bw_62",metaValueData:"_metaValueData_150bw_69",noticeText:"_noticeText_150bw_76",actions:"_actions_150bw_85"};function Nb(e){if(!e)return"Just now";const t=new Date(e).getTime();if(Number.isNaN(t))return"Just now";const n=Math.max(0,Math.floor((Date.now()-t)/1e3));if(n<10)return"Just now";if(n<60)return`${n}s ago`;const s=Math.floor(n/60);if(s===1)return"1 minute ago";if(s<60)return`${s} minutes ago`;const a=Math.floor(s/60);return a===1?"1 hour ago":`${a} hours ago`}const Vh=()=>{const{isLockBlocked:e,activeLockInfo:t,closeLockBlockedModal:n,refreshLockStatus:s}=Oe(),[a,o]=u.useState(10),[i,l]=u.useState(!1);u.useEffect(()=>{if(!e){o(10);return}const h=window.setInterval(()=>{o(p=>p<=1?(s(),10):p-1)},1e3);return()=>clearInterval(h)},[e,s]);const c=u.useCallback(async()=>{l(!0);try{await s(),o(10)}finally{l(!1)}},[s]);if(!e)return null;const d=Nb(t==null?void 0:t.lockedAt);return r.jsx(bt,{isOpen:e,onClose:n,onConfirm:i?void 0:c,maxWidth:"480px",ariaLabelledBy:"dev-lock-title",ariaDescribedBy:"dev-lock-desc",children:r.jsxs("div",{className:Tt.content,children:[r.jsxs("div",{className:Tt.header,children:[r.jsx("h2",{id:"dev-lock-title",className:Tt.title,children:"Developer Mode is active elsewhere"}),r.jsx("p",{id:"dev-lock-desc",className:Tt.subtitle,children:"Another user is currently editing."})]}),r.jsxs("div",{className:Tt.metaList,children:[r.jsxs("div",{className:Tt.metaItem,children:[r.jsx("span",{className:Tt.metaLabel,children:"Started"}),r.jsx("span",{className:Tt.metaValue,children:d})]}),r.jsxs("div",{className:Tt.metaItem,children:[r.jsx("span",{className:Tt.metaLabel,children:"Auto-refresh"}),r.jsxs("span",{className:Tt.metaValueData,children:[a,"s"]})]})]}),r.jsx("p",{className:Tt.noticeText,children:"Frees automatically after 1 minute of inactivity."}),r.jsxs("div",{className:Tt.actions,children:[r.jsx(me,{variant:"secondary",size:"sm",type:"button",onClick:n,children:"Close"}),r.jsx(me,{variant:"primary",size:"sm",type:"button",disabled:i,onClick:c,children:i?"Checking...":"Check Status"})]})]})})},fs={content:"_content_pegda_8",header:"_header_pegda_15",title:"_title_pegda_21",subtitle:"_subtitle_pegda_31",actions:"_actions_pegda_40",destructiveButton:"_destructiveButton_pegda_57"},dc=u.memo(()=>{const{isExitConfirmOpen:e,closeExitConfirmModal:t,confirmExitDevMode:n,hasUnpublishedChanges:s}=Oe(),{clearHistory:a}=Ks(),[o,i]=u.useState(!1),l=u.useCallback(()=>{a(),n({discard:!1})},[a,n]),c=u.useCallback(()=>{a(),n({discard:!0})},[a,n]),d=u.useCallback(()=>{t(),i(!0)},[t]),h=u.useCallback(()=>{i(!1),a(),n({discard:!1})},[a,n]);if(!e&&!o)return null;const p=s?"Unpublished Changes":"Exit Developer Mode",f=s?"You have unpublished changes. Drafts will not be kept once you exit.":"Active editing session will end and session history will be cleared.";return r.jsxs(r.Fragment,{children:[e&&r.jsx(bt,{isOpen:e,onClose:t,onConfirm:s?d:c,maxWidth:s?"500px":"420px",role:"alertdialog",ariaLabelledBy:"dev-exit-title",ariaDescribedBy:"dev-exit-desc",children:r.jsxs("div",{className:fs.content,children:[r.jsxs("div",{className:fs.header,children:[r.jsx("h2",{id:"dev-exit-title",className:fs.title,children:p}),r.jsx("p",{id:"dev-exit-desc",className:fs.subtitle,children:f})]}),r.jsx("div",{className:fs.actions,children:s?r.jsxs(r.Fragment,{children:[r.jsx(me,{variant:"secondary",size:"sm",type:"button",onClick:t,children:"Keep Editing"}),r.jsx(me,{variant:"secondary",size:"sm",type:"button",className:fs.destructiveButton,onClick:c,children:"Discard Draft & Exit"}),r.jsx(me,{variant:"primary",size:"sm",type:"button",onClick:d,children:"Publish & Exit"})]}):r.jsxs(r.Fragment,{children:[r.jsx(me,{variant:"secondary",size:"sm",type:"button",onClick:t,children:"Cancel"}),r.jsx(me,{variant:"primary",size:"sm",type:"button",onClick:l,children:"Exit"})]})})]})}),o&&r.jsx(cc,{isOpen:o,onClose:()=>i(!1),onPublished:h})]})});dc.displayName="DevExitConfirmModal";const bn={appShell:"_appShell_kzbod_13",mainContent:"_mainContent_kzbod_22",nodePageShell:"_nodePageShell_kzbod_29",breadcrumbContainer:"_breadcrumbContainer_kzbod_40",backButton:"_backButton_kzbod_52",nodeLayout:"_nodeLayout_kzbod_80",sidebarColumn:"_sidebarColumn_kzbod_92",contentColumn:"_contentColumn_kzbod_98",overviewSection:"_overviewSection_kzbod_105"},Tb=vb,Ab=[{id:"node-overview",label:"Overview",href:"#node-overview"},{id:"node-canvas",label:"Document Canvas",number:"01",href:"#node-canvas"}],Ib=()=>{const{route:e,nodeId:t,pageId:n,targetStage:s,navigateToNode:a,navigateToHome:o}=lc(),[i,l]=u.useState(1),[c,d]=u.useState("above"),[h,p]=u.useState([]),f=u.useRef(null),m=u.useRef(null),g=ys(),b=g.nodes&&g.nodes.length>0?g.nodes:Tb,y=t||n,S=y?b.find(O=>O.id===y):null,v=u.useCallback((O,U)=>{l(O),d(U)},[]);u.useEffect(()=>{if(e==="home"&&s){const O=setTimeout(()=>{var U;(U=f.current)==null||U.scrollToStage(s)},50);return()=>clearTimeout(O)}},[e,s]),u.useEffect(()=>{p([])},[e,y]),u.useEffect(()=>{Fi().catch(O=>{console.warn("[App] History hydration notice:",O)})},[]);const k=e==="node"||e==="page",x=gb({containerId:"node-content"}),I=u.useMemo(()=>x&&x.length>0?x:h&&h.length>0?h:Ab,[x,h]),N=u.useMemo(()=>k?I:e==="home"?c==="above"?[{label:"Roadmap",href:"#sequence-roadmap"}]:[{label:"Overview",href:"#main-content"}]:[],[k,I,e,c]),_=u.useCallback(()=>{Ys({top:0,interruptible:!1})},[]),T=u.useCallback(()=>{Ys({top:document.documentElement.scrollHeight,interruptible:!1})},[]),w=u.useCallback(O=>{var U;O&&O.preventDefault(),e==="home"?(U=f.current)==null||U.scrollToStage(1):o(1)},[e,o]),M=u.useCallback(O=>{O&&O.preventDefault(),e==="home"?_():o()},[e,o,_]),$=u.useCallback(()=>{var O,U;c==="above"?(O=f.current)==null||O.scrollToStage(1):i<b.length?(U=f.current)==null||U.scrollToStage(i+1):T()},[c,i,T]),A=u.useCallback(()=>{var O,U;c==="below"?(O=f.current)==null||O.scrollToStage(b.length):i>1?(U=f.current)==null||U.scrollToStage(i-1):_()},[c,i,_]);pb({enabled:e==="home",activeStage:i,scrollZone:c,onNextStage:$,onPrevStage:A,onScrollToTop:_,onScrollToFooter:T,onDirectStage:O=>{var U;return(U=f.current)==null?void 0:U.scrollToStage(O)}});const P=u.useMemo(()=>e!=="home"?!1:c!=="above",[e,c]),V=u.useMemo(()=>e!=="home"?!1:c!=="above",[e,c]),D=u.useMemo(()=>c==="below"||i===b.length?"Top":"Next",[c,i]),W=u.useMemo(()=>c==="below"||i===b.length?"up":"down",[c,i]),H=u.useCallback(()=>{c==="below"||i===b.length?_():$()},[c,i,$,_]),q=u.useCallback(O=>{O==null||O.stopPropagation(),A()},[A]),j=u.useCallback(O=>{a(O)},[a]),z=u.useCallback(()=>{if(S){const O=S.nodeNumber??S.index+1;o(O)}else o(1)},[S,o]);return r.jsxs("div",{className:bn.appShell,children:[r.jsx(jd,{brandTitle:g.branding.appName||"Folio",brandSubtitle:g.branding.tagline||"Engine",brandLetter:g.branding.logoText||"F",navItems:N,mobileOnlyNav:k,onRoadmapClick:w,onOverviewClick:M,onBrandClick:M}),k&&S?r.jsxs("div",{className:bn.nodePageShell,children:[r.jsxs("div",{className:bn.breadcrumbContainer,children:[r.jsx(hl,{items:[{label:"Overview",onClick:()=>o()},{label:"Milestones",onClick:()=>o(S.nodeNumber??1)},{label:S.title,isCurrent:!0}]}),r.jsx("button",{type:"button",className:bn.backButton,onClick:z,"aria-label":"Return to roadmap sequence",children:r.jsx("span",{children:"← Return to Roadmap"})})]}),r.jsxs("div",{className:bn.nodeLayout,children:[r.jsx("div",{className:bn.sidebarColumn,children:r.jsx(hu,{title:"Contents",items:I,accentColor:S.accentColor,nodeNumber:S.nodeNumber??1,nodeTitle:S.title,onBack:z})}),r.jsxs("main",{id:"node-content",className:bn.contentColumn,children:[r.jsx("section",{id:"node-overview",className:bn.overviewSection,"aria-label":"Node Overview",children:r.jsx(fl,{kicker:`Stage 0${S.nodeNumber??1}: ${S.title}`,title:S.subtitle??S.title,subtitle:S.summary,accentColor:S.accentColor})}),r.jsx("section",{id:"node-canvas","aria-label":"Dynamic Document Canvas",children:r.jsx(oc,{nodeId:S.id,nodeTitle:S.title,accentColor:S.accentColor})})]})]}),r.jsx(ro,{orgName:g.branding.orgName||"Folio Engine Open Sequence Architecture",onRoadmapClick:w,onOverviewClick:M,onNodeClick:j})]}):e==="not-found"?r.jsxs(r.Fragment,{children:[r.jsx("div",{style:{paddingTop:"calc(var(--space-8) + 68px)",flex:1},children:r.jsx(ob,{onReturn:()=>o(1)})}),r.jsx(ro,{orgName:g.branding.orgName||"Folio Engine Open Sequence Architecture",onRoadmapClick:w,onOverviewClick:M,onNodeClick:j})]}):r.jsxs(r.Fragment,{children:[r.jsxs("main",{id:"main-content",className:bn.mainContent,children:[r.jsx(il,{heroCtaRef:m,onStartJourney:w,kickerText:g.branding.heroKicker,title:g.branding.heroTitle,subtitle:g.branding.heroSubtitle}),r.jsx(dl,{ref:f,nodes:b,onStageChange:v,onExploreNode:j})]}),r.jsx(ro,{orgName:g.branding.orgName||"Folio Engine Open Sequence Architecture",onRoadmapClick:w,onOverviewClick:M,onNodeClick:j}),r.jsx(ul,{position:"left",label:"Previous",direction:"up",revolving:!0,pulse:!1,isVisible:V,onClick:q,"aria-label":"Return to the previous milestone"}),r.jsx(ul,{position:"right",label:D,direction:W,revolving:!0,isVisible:P,onClick:H})]}),r.jsx(Uh,{}),r.jsx(Vh,{}),r.jsx(dc,{}),r.jsx(Hh,{})]})},$b=({config:e})=>(e&&hc(e),r.jsx(qd,{children:r.jsx(eu,{children:r.jsx(Ib,{})})})),Eb=e=>{const t=e==null?void 0:e.target,[n,s]=u.useState({scrollY:0,scrollProgress:0}),a=u.useRef(new Set),o=u.useRef(null),i=u.useRef({scrollY:0,scrollProgress:0}),l=u.useCallback(()=>{const d=typeof window<"u"&&(window.scrollY||window.pageYOffset)||0;if(!(t!=null&&t.current)){const v=typeof document<"u"?Math.max(document.documentElement.scrollHeight,document.body.scrollHeight,window.innerHeight):window.innerHeight,k=Math.max(v-window.innerHeight,1),x=Math.min(Math.max(d/k,0),1);return{scrollY:d,scrollProgress:x}}const p=t.current.getBoundingClientRect(),f=p.top+d,m=p.height,g=typeof document<"u"&&document.documentElement.clientHeight||window.innerHeight,b=m-g,y=d-f;if(b<=0)return{scrollY:d,scrollProgress:0};const S=Math.min(Math.max(y/b,0),1);return{scrollY:d,scrollProgress:S}},[t]),c=u.useCallback(d=>(a.current.add(d),d(i.current),()=>{a.current.delete(d)}),[]);return u.useEffect(()=>{const d=()=>{o.current===null&&(o.current=requestAnimationFrame(()=>{o.current=null;const h=l();i.current=h,a.current.forEach(p=>p(h)),s(h)}))};return d(),window.addEventListener("scroll",d,{passive:!0}),window.addEventListener("resize",d,{passive:!0}),window.addEventListener("orientationchange",d,{passive:!0}),()=>{o.current!==null&&cancelAnimationFrame(o.current),window.removeEventListener("scroll",d),window.removeEventListener("resize",d),window.removeEventListener("orientationchange",d)}},[l]),{...n,subscribeScroll:c}},da={cardContainer:"_cardContainer_dfk33_7",cardInteractiveTarget:"_cardInteractiveTarget_dfk33_21",imageWrapper:"_imageWrapper_dfk33_41",heroImage:"_heroImage_dfk33_56"},Lb=({node:e,heroImage:t,onExploreNode:n,className:s,priority:a=!1,docked:o=!1,focalPoint:i={x:50,y:50},onClick:l})=>{const c=t??(e==null?void 0:e.heroImage)??{src:"",alt:"",caption:""},d=u.useCallback(m=>{m.stopPropagation(),l?l():e!=null&&e.id&&n&&n(e.id)},[l,n,e==null?void 0:e.id]),h=u.useCallback(m=>{(m.key==="Enter"||m.key===" ")&&(m.preventDefault(),l?l():e!=null&&e.id&&n&&n(e.id))},[l,n,e==null?void 0:e.id]);if(!c.src&&!e)return null;const p=`${i.x}% ${i.y}%`,f=l?`View photograph: ${c.caption||c.alt||(e==null?void 0:e.title)||"Photograph"}`:`Explore ${(e==null?void 0:e.title)||"Node"}`;return r.jsx("div",{className:`${da.cardContainer} ${o?da.docked:""} ${s||""}`,"data-node-id":e==null?void 0:e.id,children:r.jsx("button",{type:"button",className:da.cardInteractiveTarget,onClick:d,onKeyDown:h,"aria-label":f,children:r.jsx("div",{className:da.imageWrapper,children:r.jsx("img",{src:c.src,alt:c.alt,loading:a?"eager":"lazy",fetchPriority:a?"high":"auto",className:da.heroImage,style:{objectPosition:`var(--card-crop-focal, ${p})`}})})})})},fe={container:"_container_1gczx_12",panel:"_panel_1gczx_19",formField:"_formField_1gczx_25",fieldLabel:"_fieldLabel_1gczx_31",requiredMark:"_requiredMark_1gczx_40",input:"_input_1gczx_45",textarea:"_textarea_1gczx_72",checkboxLabel:"_checkboxLabel_1gczx_101",checkbox:"_checkbox_1gczx_101",segmentedControl:"_segmentedControl_1gczx_148",segmentButton:"_segmentButton_1gczx_156",segmentButtonActive:"_segmentButtonActive_1gczx_177",imagePreviewWrapper:"_imagePreviewWrapper_1gczx_184",previewThumb:"_previewThumb_1gczx_195",fileRow:"_fileRow_1gczx_202",hiddenFileInput:"_hiddenFileInput_1gczx_208",actions:"_actions_1gczx_212"},qh=({isOpen:e,type:t,nodeId:n,targetSectionId:s,targetIndex:a,targetSubsectionId:o,onClose:i,onConfirmAdd:l})=>{const{showToast:c}=Oe(),[d,h]=u.useState(""),[p,f]=u.useState(!0),[m,g]=u.useState(""),[b,y]=u.useState("p"),[S,v]=u.useState(""),[k,x]=u.useState(""),[I,N]=u.useState(""),[_,T]=u.useState(!1),[w,M]=u.useState(""),[$,A]=u.useState(""),[P,V]=u.useState("upload"),[D,W]=u.useState(!1),[H,q]=u.useState(null),j=u.useRef(null),z=u.useRef(null);u.useEffect(()=>{if(e){h(""),f(!0),g(""),y("p"),v(""),x(""),N(""),T(!1),M(""),A(""),V("upload");const B=setTimeout(()=>{var Y;(Y=z.current)==null||Y.focus()},50);return()=>clearTimeout(B)}},[e,t]);const O=u.useMemo(()=>e?!!(d.trim()||m.trim()||S.trim()||k.trim()||I.trim()||w.trim()||$.trim()):!1,[e,d,m,S,k,I,w,$]);if(eo(e&&O,"canvas-add-modal"),!e||!t)return null;let U=!1,Q="Add Element",se="Add Element";switch(t){case"section":U=d.trim().length>0,Q="Add Section",se="Add Section";break;case"subsection":U=d.trim().length>0,Q="Add Subsection",se="Add Subsection";break;case"text":U=m.trim().length>0,Q="Add Narrative Text",se="Add Text";break;case"photo":U=S.trim().length>0&&k.trim().length>0,Q="Add Photo Evidence",se="Add Photo";break;case"gallery":U=d.trim().length>0,Q="Add Photo Gallery",se="Add Gallery";break;case"chart":U=d.trim().length>0,Q="Add Indicator Chart",se="Add Chart";break}const ae=async B=>{var X;const Y=(X=B.target.files)==null?void 0:X[0];if(!Y)return;const ee=Y.name.replace(/\.[^/.]+$/,"");k||x(ee),W(!0),q(null);try{const te=await to(Y,"photos");v(te)}catch(te){console.error("[CanvasAddModal] Photo upload failed:",te),q(te instanceof Error?te.message:"Photo upload failed")}finally{W(!1)}},de=B=>{if(B&&B.preventDefault(),!U)return;const Y={title:d.trim(),isNumbered:p,content:m.trim(),as:b,src:S.trim(),alt:k.trim(),caption:I.trim(),showCaption:_,driveUrl:w.trim(),subtitle:$.trim()};l(t,Y,s,a,o),c("Element added to canvas.","success"),i()};return r.jsx(bt,{isOpen:e,onClose:i,onConfirm:U&&!D?de:void 0,title:Q,maxWidth:"500px",ariaLabel:Q,children:r.jsxs("form",{onSubmit:de,className:fe.container,children:[t==="section"&&r.jsxs("div",{className:fe.panel,children:[r.jsxs("div",{className:fe.formField,children:[r.jsxs("label",{className:fe.fieldLabel,htmlFor:"add-section-title",children:["Section Title ",r.jsx("span",{className:fe.requiredMark,children:"*"})]}),r.jsx("input",{ref:B=>{z.current=B},id:"add-section-title",type:"text",className:fe.input,value:d,onChange:B=>h(B.target.value),placeholder:"e.g. Learning Continuity & Remediation",required:!0})]}),r.jsxs("div",{className:fe.formField,children:[r.jsx("label",{className:fe.fieldLabel,children:"Section Numbering"}),r.jsxs("div",{className:fe.segmentedControl,role:"radiogroup","aria-label":"Section Numbering",children:[r.jsx("button",{type:"button",role:"radio","aria-checked":p,className:`${fe.segmentButton} ${p?fe.segmentButtonActive:""}`,onClick:()=>f(!0),children:"Numbered"}),r.jsx("button",{type:"button",role:"radio","aria-checked":!p,className:`${fe.segmentButton} ${p?"":fe.segmentButtonActive}`,onClick:()=>f(!1),children:"Unnumbered"})]})]})]}),t==="subsection"&&r.jsx("div",{className:fe.panel,children:r.jsxs("div",{className:fe.formField,children:[r.jsxs("label",{className:fe.fieldLabel,htmlFor:"add-subsec-title",children:["Subsection Title ",r.jsx("span",{className:fe.requiredMark,children:"*"})]}),r.jsx("input",{ref:B=>{z.current=B},id:"add-subsec-title",type:"text",className:fe.input,value:d,onChange:B=>h(B.target.value),placeholder:"e.g. Grade 7 Catch-Up Fridays & Remediation",required:!0})]})}),t==="text"&&r.jsxs("div",{className:fe.panel,children:[r.jsxs("div",{className:fe.formField,children:[r.jsx("label",{className:fe.fieldLabel,children:"Typography Style"}),r.jsxs("div",{className:fe.segmentedControl,role:"radiogroup","aria-label":"Text Typography Style",children:[r.jsx("button",{type:"button",role:"radio","aria-checked":b==="p",className:`${fe.segmentButton} ${b==="p"?fe.segmentButtonActive:""}`,onClick:()=>y("p"),children:"Body Paragraph"}),r.jsx("button",{type:"button",role:"radio","aria-checked":b==="blockquote",className:`${fe.segmentButton} ${b==="blockquote"?fe.segmentButtonActive:""}`,onClick:()=>y("blockquote"),children:"Editorial Quote"})]})]}),r.jsxs("div",{className:fe.formField,children:[r.jsxs("label",{className:fe.fieldLabel,htmlFor:"add-text-content",children:["Narrative Content ",r.jsx("span",{className:fe.requiredMark,children:"*"})]}),r.jsx("textarea",{ref:B=>{z.current=B},id:"add-text-content",className:fe.textarea,value:m,onChange:B=>g(B.target.value),placeholder:"Type narrative overview, milestone progress, or strategic initiative...",rows:5,required:!0})]})]}),t==="photo"&&r.jsxs("div",{className:fe.panel,children:[S&&r.jsx("div",{className:fe.imagePreviewWrapper,children:r.jsx("img",{src:S,alt:k||"Selected preview",className:fe.previewThumb,onError:B=>{B.target.style.display="none"}})}),r.jsxs("div",{className:fe.formField,children:[r.jsx("span",{className:fe.fieldLabel,children:"Photo Source"}),r.jsxs("div",{className:fe.segmentedControl,role:"radiogroup","aria-label":"Photo Source",children:[r.jsx("button",{type:"button",role:"radio","aria-checked":P==="upload",className:`${fe.segmentButton} ${P==="upload"?fe.segmentButtonActive:""}`,onClick:()=>V("upload"),children:"Upload Photo"}),r.jsx("button",{type:"button",role:"radio","aria-checked":P==="url",className:`${fe.segmentButton} ${P==="url"?fe.segmentButtonActive:""}`,onClick:()=>V("url"),children:"Photo URL"})]})]}),P==="upload"?r.jsxs("div",{className:fe.formField,children:[r.jsxs("span",{className:fe.fieldLabel,children:["Select Photo File ",r.jsx("span",{className:fe.requiredMark,children:"*"})]}),r.jsxs("div",{className:fe.fileRow,children:[r.jsx(me,{type:"button",variant:"secondary",size:"sm",onClick:()=>{var B;return(B=j.current)==null?void 0:B.click()},children:"Upload Photo"}),r.jsx("input",{ref:j,type:"file",accept:"image/*",className:fe.hiddenFileInput,onChange:ae,"aria-label":"Upload photo file"}),r.jsx("span",{className:fe.fieldLabel,children:S?"Photo selected":"No photo chosen"})]})]}):r.jsxs("div",{className:fe.formField,children:[r.jsxs("label",{className:fe.fieldLabel,htmlFor:"add-photo-url",children:["Photo URL ",r.jsx("span",{className:fe.requiredMark,children:"*"})]}),r.jsx("input",{id:"add-photo-url",type:"text",className:fe.input,value:S.startsWith("data:")?"":S,onChange:B=>v(B.target.value),placeholder:"https://... or /images/..."})]}),r.jsxs("div",{className:fe.formField,children:[r.jsxs("label",{className:fe.fieldLabel,htmlFor:"add-photo-alt",children:["Alt Text ",r.jsx("span",{className:fe.requiredMark,children:"*"})]}),r.jsx("input",{ref:B=>{z.current||(z.current=B)},id:"add-photo-alt",type:"text",className:fe.input,value:k,onChange:B=>x(B.target.value),placeholder:"Brief visual description for screen readers",required:!0})]}),r.jsxs("label",{className:fe.checkboxLabel,children:[r.jsx("input",{type:"checkbox",className:fe.checkbox,checked:_,onChange:B=>T(B.target.checked)}),r.jsx("span",{children:"Show caption below photo"})]}),_&&r.jsxs("div",{className:fe.formField,children:[r.jsx("label",{className:fe.fieldLabel,htmlFor:"add-photo-caption",children:"Caption"}),r.jsx("input",{id:"add-photo-caption",type:"text",className:fe.input,value:I,onChange:B=>N(B.target.value),placeholder:"Editorial context or story shown beneath photo"})]})]}),t==="gallery"&&r.jsxs("div",{className:fe.panel,children:[r.jsxs("div",{className:fe.formField,children:[r.jsxs("label",{className:fe.fieldLabel,htmlFor:"add-gallery-title",children:["Gallery Title ",r.jsx("span",{className:fe.requiredMark,children:"*"})]}),r.jsx("input",{ref:B=>{z.current=B},id:"add-gallery-title",type:"text",className:fe.input,value:d,onChange:B=>h(B.target.value),placeholder:"e.g. Photo & Activity Evidence Gallery",required:!0})]}),r.jsxs("div",{className:fe.formField,children:[r.jsx("label",{className:fe.fieldLabel,htmlFor:"add-gallery-drive",children:"Google Drive Folder URL (Optional)"}),r.jsx("input",{id:"add-gallery-drive",type:"text",className:fe.input,value:w,onChange:B=>M(B.target.value),placeholder:"https://drive.google.com/drive/folders/..."})]})]}),t==="chart"&&r.jsxs("div",{className:fe.panel,children:[r.jsxs("div",{className:fe.formField,children:[r.jsxs("label",{className:fe.fieldLabel,htmlFor:"add-chart-title",children:["Chart Title ",r.jsx("span",{className:fe.requiredMark,children:"*"})]}),r.jsx("input",{ref:B=>{z.current=B},id:"add-chart-title",type:"text",className:fe.input,value:d,onChange:B=>h(B.target.value),placeholder:"e.g. Learner Mastery by Learning Area",required:!0})]}),r.jsxs("div",{className:fe.formField,children:[r.jsx("label",{className:fe.fieldLabel,htmlFor:"add-chart-subtitle",children:"Subtitle / Description (Optional)"}),r.jsx("input",{id:"add-chart-subtitle",type:"text",className:fe.input,value:$,onChange:B=>A(B.target.value),placeholder:"Quarterly performance against benchmark standard"})]})]}),r.jsxs("div",{className:fe.actions,children:[H&&r.jsx("span",{style:{fontSize:"0.8125rem",color:"var(--color-danger, #e11d48)",marginRight:"auto"},children:H}),r.jsx(me,{type:"button",variant:"ghost",onClick:i,disabled:D,children:"Cancel"}),r.jsx(me,{type:"submit",variant:"primary",disabled:!U||D,children:D?"Uploading...":se})]})]})})};qh.displayName="CanvasAddModal";const At={searchForm:"_searchForm_xyd73_2",searchPill:"_searchPill_xyd73_9",searchIconWrap:"_searchIconWrap_xyd73_35",searchIcon:"_searchIcon_xyd73_35",searchInput:"_searchInput_xyd73_55",clearBtn:"_clearBtn_xyd73_84",shortcutKbd:"_shortcutKbd_xyd73_107",searchSubmitBtn:"_searchSubmitBtn_xyd73_127",searchSubmitText:"_searchSubmitText_xyd73_140",searchSubmitBtnBottom:"_searchSubmitBtnBottom_xyd73_145",arrowIcon:"_arrowIcon_xyd73_156"},Mb=({placeholder:e="Search nodes, projects, or indicators...",mobilePlaceholder:t="Search",onSearch:n,className:s})=>{const[a,o]=u.useState(""),[i,l]=u.useState(()=>typeof window<"u"?window.matchMedia("(max-width: 640px)").matches:!1),c=u.useRef(null),d=u.useRef(null),h=u.useRef(null),p=u.useRef(null);u.useEffect(()=>{const b=window.matchMedia("(max-width: 640px)"),y=S=>{l(S.matches)};return y(b),b.addEventListener("change",y),()=>b.removeEventListener("change",y)},[]),u.useEffect(()=>{const b=y=>{var S;(y.metaKey||y.ctrlKey)&&y.key.toLowerCase()==="k"&&(y.preventDefault(),(S=c.current)==null||S.focus())};return window.addEventListener("keydown",b),()=>window.removeEventListener("keydown",b)},[]);const f=b=>{var y;if(b.key==="Enter"&&!b.nativeEvent.isComposing){b.preventDefault();const v=i||typeof window<"u"&&window.matchMedia("(max-width: 640px)").matches?h.current||d.current:d.current||h.current;v?v.click():(y=p.current)==null||y.requestSubmit()}},m=b=>{if(b.preventDefault(),n)n(a.trim());else{const y=document.getElementById("roadmap");y&&y.scrollIntoView({behavior:"smooth"})}},g=()=>{var b;o(""),(b=c.current)==null||b.focus()};return r.jsxs("form",{ref:p,role:"search",className:`${At.searchForm} ${s||""}`,onSubmit:m,"aria-label":"Search Plan",children:[r.jsxs("div",{className:At.searchPill,children:[r.jsx("span",{className:At.searchIconWrap,"aria-hidden":"true",children:r.jsxs("svg",{className:At.searchIcon,width:"21",height:"21",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round",children:[r.jsx("circle",{cx:"11",cy:"11",r:"8"}),r.jsx("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]})}),r.jsx("input",{ref:c,type:"search",className:At.searchInput,value:a,onChange:b=>o(b.target.value),onKeyDown:f,placeholder:i?t:e,"aria-label":i?t:e,autoComplete:"off",spellCheck:"false"}),a?r.jsx("button",{type:"button",className:At.clearBtn,onClick:g,"aria-label":"Clear search input",children:r.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[r.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),r.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})}):r.jsx("kbd",{className:At.shortcutKbd,"aria-hidden":"true",title:"Press ⌘K or Ctrl+K to search",children:"⌘K"}),r.jsxs(me,{ref:d,id:"search-submit-btn",type:"submit",variant:"revolving-outline",outlineWidth:6,className:At.searchSubmitBtn,"aria-label":"Search",children:[r.jsx("span",{className:At.searchSubmitText,children:"Search"}),r.jsxs("svg",{className:At.arrowIcon,width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[r.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"}),r.jsx("polyline",{points:"12 5 19 12 12 19"})]})]})]}),r.jsxs(me,{ref:h,id:"search-submit-btn-mobile",type:"submit",variant:"revolving-outline",outlineWidth:6,className:At.searchSubmitBtnBottom,"aria-label":"Search",children:[r.jsx("span",{className:At.searchSubmitText,children:"Search"}),r.jsxs("svg",{className:At.arrowIcon,width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[r.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"}),r.jsx("polyline",{points:"12 5 19 12 12 19"})]})]})]})},Db={editorialSection:"_editorialSection_bx623_1"},jh=u.memo(({id:e,title:t,number:n,as:s="section",className:a,style:o,children:i})=>{const l=n!=null?typeof n=="number"?String(n).padStart(2,"0"):String(n):void 0;return r.jsx(s,{id:e,"data-toc-title":t,"data-toc-number":l,"aria-label":t,className:`${Db.editorialSection} ${a||""}`,style:o,children:i})});jh.displayName="EditorialSection",C.AUTOSAVE_DEBOUNCE_MS=Ld,C.AUTOSYNC_DEBOUNCE_MS=Wc,C.AccordionSection=Dt,C.App=$b,C.AppFooter=ro,C.AppHeader=jd,C.BROADCAST_CHANNEL_NAME=nm,C.BarChart=dh,C.Breadcrumb=hl,C.Button=me,C.CANVAS_DRAFT_STORAGE_PREFIX=lp,C.CANVAS_LEGACY_STORAGE_PREFIX=cp,C.CANVAS_LIVE_STORAGE_PREFIX=xr,C.CANVAS_SCHEMA_VERSION=Fa,C.CANVAS_STORAGE_PREFIX=dp,C.CanvasAddBar=vn,C.CanvasAddModal=qh,C.CanvasChart=sc,C.CanvasDeleteConfirmModal=ac,C.CanvasGallery=Al,C.CanvasItemControls=ds,C.CanvasPhoto=xl,C.CanvasSection=ml,C.CanvasSubsection=gl,C.CanvasText=vl,C.ChartCard=rc,C.ChartConfigDrawer=nc,C.ChartGhostWireframe=Hl,C.ChartLegend=rs,C.ChartRouter=mh,C.ChartSortingControls=Lh,C.ChartTableModal=Mh,C.ChartTooltip=ts,C.ColumnSelect=nr,C.ColumnTypeBadge=xv,C.DEFAULT_IMAGE_QUALITY=nu,C.DEFAULT_MAX_DIMENSION=tu,C.DEV_LOCK_STORAGE_KEY=Cs,C.DEV_SALT=Wf,C.DEV_SESSION_ID_KEY=Sc,C.DRAFT_ACTIVE_KEY=Gc,C.DRAFT_CANVAS_PREFIX=sp,C.DRAFT_CONTENT_KEY=ap,C.DRAFT_DIRTY_KEY=op,C.DataPendingCard=gh,C.DevActionAffordance=Qn,C.DevExitConfirmModal=dc,C.DevHelpTooltip=Xn,C.DevLockBlockedModal=Vh,C.DevModeBadge=Hh,C.DevPinModal=Uh,C.DevPublishModal=cc,C.DeveloperModeProvider=qd,C.DocumentCanvas=oc,C.DonutChart=hh,C.DraggableRows=_h,C.Drawer=Vl,C.DrawerTier=_v,C.EVENT_CHART_SOURCE_CHANGE=Co,C.EVENT_CLOUD_DRAFT_SYNC_STATUS=La,C.EVENT_DRAFT_CANVAS_CHANGE=Tr,C.EVENT_DRAFT_CONTENT_CHANGE=$s,C.EVENT_DRAFT_STATUS_CHANGE=Ea,C.EVENT_HISTORY_CHANGE=Za,C.EVENT_LIVE_CANVAS_CHANGE=Nr,C.EVENT_LIVE_CONTENT_CHANGE=Ta,C.EVENT_SOURCE_SOURCE_CHANGE=ao,C.EXPECTED_PIN_HASH=fc,C.EditableText=jr,C.EditorialSection=jh,C.EditorialSidebar=hu,C.EnzoLogo=_s,C.FAB=ul,C.HEARTBEAT_INTERVAL_MS=kc,C.HISTORY_SCHEMA_VERSION=Ur,C.HeroPhoto=Lb,C.HeroSection=il,C.HeroWelcome=il,C.HistogramChart=ph,C.HistoryHubModal=Wh,C.LEGACY_STORAGE_KEY_ACTIVE_PUBLISHED_ID=Fr,C.LOCAL_STORAGE_ALL_KEY=ss,C.LOCAL_STORAGE_PREFIX=Yl,C.LOCKOUT_DURATION_MS=Wo,C.LOCK_EXPIRATION_MS=Sa,C.LineChart=uh,C.MAX_ATTEMPTS=fr,C.MAX_AUTOSAVES=Ed,C.MAX_STACK_DEPTH=Ra,C.MEDIA_BUCKET_ID=rl,C.Modal=bt,C.NODE_IDS=rn,C.NODE_TO_STAGE=ic,C.PHOTO_STACKED_BREAKPOINT=du,C.PageTitle=fl,C.ParametricShape=_s,C.RangePreviewMatrix=Eh,C.RevolvingButton=wv,C.RoadmapNode=ll,C.RoadmapSection=dl,C.RoadmapTrack=cl,C.SESSION_DURATION_MS=Go,C.STAGE_TO_NODE=lb,C.STORAGE_KEY_ACTIVE_PUBLISHED_ID=sm,C.STORAGE_KEY_CONTENT_OVERRIDES=Rf,C.STORAGE_KEY_DRAFT_CONTENT=ei,C.STORAGE_KEY_FAILED_ATTEMPTS=Vf,C.STORAGE_KEY_HISTORY_MANIFEST=Pi,C.STORAGE_KEY_LEGACY_CONTENT=Dc,C.STORAGE_KEY_LIVE_ACTIVE_PUBLISHED_ID=rm,C.STORAGE_KEY_LIVE_CONTENT=xa,C.STORAGE_KEY_LOCKOUT_UNTIL=Hf,C.STORAGE_KEY_MISSING_TABLES=ks,C.STORAGE_KEY_SOURCE_CACHE=bl,C.STORAGE_KEY_UNLOCKED_AT=ba,C.ScatterPlot=fh,C.SearchField=Mb,C.SectionTitle=so,C.SeriesSelectToolbar=Nv,C.StatusPill=qs,C.TAB_INSTANCE_ID=Ns,C.TieredSlider=wh,C.Toast=Zt,C.UndoRedoContext=nl,C.UndoRedoManager=Qd,C.UndoRedoProvider=eu,C.UniversalEditModal=Jn,C.VALID_NODES=ib,C.ValueLabelToggle=So,C.acquireDevLock=Jo,C.acquireScrollLock=Ki,C.broadcastLiveSync=Fd,C.canPublishDraft=hm,C.cancelCinematicScroll=no,C.canvasLayoutService=up,C.captureCurrentSnapshot=Qa,C.checkDevLockStatus=Wn,C.checkDraftStaleness=Ds,C.cinematicScrollTo=Ys,C.clearAllDirtyEditors=wm,C.clearAllHistory=cm,C.clearDraftStorage=Os,C.clearLockoutUntil=jo,C.clearSessionUnlockTime=Un,C.closeSyncBroadcastChannel=fm,C.computeMetricsSummary=Xa,C.createDefaultEngineConfig=ga,C.deleteSnapshot=lm,C.deployNodeCanvasToCloud=yi,C.discardDraftSession=ui,C.dispatchAggregateCanvasChange=Fs,C.dispatchDraftChange=Cn,C.downscaleImage=su,C.exportHistoryBackupJson=dm,C.fetchActiveCloudDraft=Zc,C.fetchActivePublishedVersionFromCloud=Od,C.fetchChartConfig=xh,C.fetchChartConfigsByNode=Av,C.fetchLiveSourceSources=_l,C.fetchPublishedHistoryFromCloud=Bd,C.findCanvasItemLocation=za,C.findPositiveActionElement=Ri,C.foldCanvasOverridesIntoDocument=rd,C.formatSaveErrorMessage=ls,C.generateParametricPath=Gf,C.generateSerpentineRoadmap=lu,C.generateWavyPolygonPath=zo,C.getActiveNodeIds=Ut,C.getActivePublishedId=cn,C.getAllContentOverrides=Ls,C.getBroadcastChannelName=Oi,C.getCachedChartConfig=os,C.getCanvasDraftStoragePrefix=hi,C.getCanvasLegacyStoragePrefix=fi,C.getCanvasLiveStoragePrefix=Pa,C.getCanvasStorageKey=Rc,C.getChartSourcePrefix=ko,C.getChartSourcesManifestKey=Sh,C.getCloudDraftSyncStatus=jc,C.getContent=wn,C.getContentObject=si,C.getContentSnapshot=zc,C.getDefaultSystemBaselineSnapshot=Ja,C.getDevFailedAttemptsKey=Ss,C.getDevLockStorageKey=wc,C.getDevLockoutUntilKey=ws,C.getDevSalt=va,C.getDevSessionIdKey=gr,C.getDevUnlockedAtKey=pc,C.getDraftActiveKey=Sn,C.getDraftBaseId=Ms,C.getDraftCanvasKey=Sr,C.getDraftCanvasPrefix=oi,C.getDraftCanvasStorageKey=ed,C.getDraftContentKey=ii,C.getDraftContentStorageKey=Is,C.getDraftDirtyKey=Hn,C.getEngineConfig=ys,C.getFailedAttempts=_a,C.getHistoryDbName=Ic,C.getHistoryManifest=zt,C.getHistoryManifestKey=Or,C.getHydrationState=mm,C.getInMemoryDraftCanvas=Vc,C.getLegacyContentStorageKey=Na,C.getLiveActivePublishedIdKey=Pr,C.getLiveContentOverrides=np,C.getLiveContentStorageKey=As,C.getLiveNodeCanvas=Ga,C.getLiveSourceSource=io,C.getLocalFallbackSnapshots=In,C.getLocalLock=Ts,C.getLockoutUntil=_n,C.getMissingTablesStorageKey=yc,C.getNodeCanvas=Ft,C.getRemainingSessionMinutes=Vo,C.getSessionBroadcastChannel=Cc,C.getSessionId=ka,C.getSessionUnlockTime=en,C.getSourceCacheStorageKey=Js,C.getSourceSourceSync=Yr,C.getStorage=Ee,C.getStorageKey=zf,C.getStorageNamespace=Ae,C.getSupabaseConfig=tt,C.getSyncBroadcastChannel=Gi,C.handleBeforeUnloadGuard=ji,C.handleIncomingSyncBroadcast=Ud,C.hasAnyUnsavedChanges=Hd,C.hasContentOverride=Pc,C.hasDraftKeys=Yc,C.hashPin=mc,C.hydrateActiveVersionFromCloud=Gd,C.hydrateHistoryFromIndexedDB=Fi,C.importHistoryBackupJson=um,C.initDraftSession=Oa,C.insertLeafElement=gi,C.insertSection=pi,C.insertSubsection=mi,C.invalidateContentCache=yr,C.isChartElement=qp,C.isClickablePositiveCandidate=Zn,C.isCloudHydrating=pm,C.isDesktopDevice=ya,C.isDraftDirty=Bs,C.isDraftModeActive=Da,C.isDraftStale=ip,C.isGalleryElement=Vp,C.isInitialHydrationPending=Hi,C.isLeafElement=Wp,C.isLockExpired=Xo,C.isPhotoElement=$i,C.isPositiveShortcut=Qi,C.isSectionElement=Gp,C.isSessionValid=zn,C.isSubsectionElement=Ad,C.isTableAvailable=It,C.isTextElement=Hp,C.isTextInput=Rd,C.isTopmostModal=Ji,C.loadFromIndexedDB=Lc,C.mapChartConfigToDbRow=Ch,C.mapDbRowToChartConfig=Xl,C.markTableAvailable=_c,C.markTableMissing=Ot,C.migrateCanvasOverridesIntoAst=Ar,C.migrateLegacyStorageKeys=td,C.moveCanvasItem=sd,C.notifyChartChange=xo,C.parseHash=cb,C.parseRoute=hs,C.progressToDrawnLength=cu,C.pruneAutoSaves=Ui,C.publishNewSnapshot=Pd,C.purgeLegacyDocumentStorage=Mc,C.regenerateSessionId=xc,C.registerActiveModal=Zi,C.registerDirtyEditor=Wd,C.releaseDevLock=Qo,C.releaseDevLockBeacon=Tc,C.releaseScrollLock=Yi,C.relocateCanvasItem=ad,C.removeCanvasItem=od,C.renewDevLockHeartbeat=Nc,C.renumberSections=xt,C.resetAllContentOverrides=tp,C.resetChartSourceCache=$v,C.resetContent=br,C.resetEngineConfig=Uf,C.resetFailedAttempts=Yo,C.resetHydrationStateForTesting=gm,C.resetMissingTablesForTesting=Zf,C.resetNodeCanvas=vi,C.resetSessionIdForTesting=Xf,C.resetSourceCache=qm,C.restoreSnapshotToDraft=zi,C.restoreUnifiedSnapshot=im,C.sanitizeFilename=ru,C.sanitizeLiveSourceSource=oo,C.sanitizePublicChartConfig=Tv,C.saveChartConfig=Iv,C.saveChartConfigDetailed=is,C.saveHistoryManifest=dn,C.saveLiveNodeCanvas=Ir,C.saveMilestone=am,C.saveNodeCanvas=Ps,C.saveToIndexedDB=Ec,C.setActivePublishedId=zr,C.setAllContentOverrides=Ia,C.setCachedChartConfig=Rt,C.setContent=nn,C.setContentObject=ep,C.setDraftDirty=kn,C.setDraftModeActive=kr,C.setEngineConfig=hc,C.setFailedAttempts=Ko,C.setInMemoryDraftCanvas=Ma,C.setLiveContentOverrides=$a,C.setLocalLock=Ct,C.setLockoutUntil=qo,C.setSessionUnlockTime=vc,C.sha256Fallback=Ho,C.subscribeContentKey=Uc,C.subscribeToCanvasChange=bi,C.subscribeToCloudDraftSync=Kc,C.subscribeToContentChange=ai,C.subscribeToDraftStatus=qc,C.subscribeToHistoryChange=Dd,C.subscribeToHydration=zd,C.subscribeToLockStorage=Ac,C.syncDraftToCloud=Jc,C.syncDraftWithPublished=Qc,C.triggerAutoSave=om,C.triggerDebouncedCloudDraftSync=Ba,C.triggerPositiveAction=el,C.undoRedoService=un,C.unregisterActiveModal=Xi,C.unregisterDirtyEditor=qi,C.updateCanvasItem=id,C.uploadMediaAsset=to,C.upsertLiveSourceSource=Zr,C.useAppRoute=db,C.useDeveloperMode=Oe,C.useDocumentCanvas=pl,C.useHashRoute=lc,C.useLightboxHistory=fu,C.useNodeCanvas=Dm,C.useRoadmapScroll=iu,C.useScroll=Eb,C.useScrollspy=uu,C.useUndoRedo=Ks,C.verifyPin=gc,Object.defineProperty(C,Symbol.toStringTag,{value:"Module"})}));