@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.
package/dist/folio.cjs ADDED
@@ -0,0 +1,9 @@
1
+ "use strict";var rh=Object.defineProperty;var ah=(e,t,s)=>t in e?rh(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s;var qr=(e,t,s)=>ah(e,typeof t!="symbol"?t+"":t,s);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("react/jsx-runtime"),me=require("./diagnostics-Dw5PzR78.cjs");require("./edge-1WCVZ0J7.cjs");const u=require("react"),$e=require("./edge-Dr41JdrQ.cjs"),fr=require("react-dom");var Le=typeof document<"u"?document.currentScript:null;const oh="_parametricShape_17iau_1",ih="_sizeSm_17iau_16",lh="_sizeMd_17iau_20",ch="_sizeLg_17iau_24",dh="_conicShape_17iau_29",uh="_letter_17iau_54",Sn={parametricShape:oh,sizeSm:ih,sizeMd:lh,sizeLg:ch,conicShape:dh,letter:uh};function Po({sides:e=5,radius:t=50,waviness:s=10,roundness:r=1,strokeWidth:a=12}={}){const o=Math.max(3,Math.round(e)),i=o*2,l=[],c=s>0&&s<=1?t*s:s;for(let q=0;q<i;q++){const P=-Math.PI/2+q*Math.PI/o,R=q%2===0?t+c:t-c,W=R*Math.cos(P),se=R*Math.sin(P),re=-Math.sin(P),le=Math.cos(P);l.push({x:W,y:se,tx:re,ty:le})}let d=1/0,f=-1/0,m=1/0,h=-1/0;for(const q of l)q.x<d&&(d=q.x),q.x>f&&(f=q.x),q.y<m&&(m=q.y),q.y>h&&(h=q.y);const p=50-(d+f)/2,x=50-(m+h)/2,v=l.map(q=>({x:q.x+p,y:q.y+x,tx:q.tx,ty:q.ty}));let b=`M ${v[0].x.toFixed(2)} ${v[0].y.toFixed(2)}`;for(let q=0;q<v.length;q++){const P=v[q],F=v[(q+1)%v.length],W=Math.hypot(F.x-P.x,F.y-P.y)*r,se=P.x+P.tx*W,re=P.y+P.ty*W,le=F.x-F.tx*W,M=F.y-F.ty*W;b+=` C ${se.toFixed(2)} ${re.toFixed(2)}, ${le.toFixed(2)} ${M.toFixed(2)}, ${F.x.toFixed(2)} ${F.y.toFixed(2)}`}b+=" Z";let y=1/0,g=-1/0,S=1/0,C=-1/0;for(let q=0;q<v.length;q++){const P=v[q],F=v[(q+1)%v.length],W=Math.hypot(F.x-P.x,F.y-P.y)*r,se=P.x+P.tx*W,re=P.y+P.ty*W,le=F.x-F.tx*W,M=F.y-F.ty*W;for(let K=0;K<=1;K+=.05){const Q=1-K,X=Q*Q*Q*P.x+3*Q*Q*K*se+3*Q*K*K*le+K*K*K*F.x,ee=Q*Q*Q*P.y+3*Q*Q*K*re+3*Q*K*K*M+K*K*K*F.y;X<y&&(y=X),X>g&&(g=X),ee<S&&(S=ee),ee>C&&(C=ee)}}const T=a/2+.5,N=y-T,_=g+T,k=S-T,w=C+T,$=N===_?100:_-N,I=k===w?100:w-k,j=Math.max($,I),D=(N+_)/2,H=(k+w)/2,L=(D-j/2).toFixed(2),U=(H-j/2).toFixed(2),G=j.toFixed(2),z=`${L} ${U} ${G} ${G}`;return{pathData:b,viewBox:z}}function hh(e=8,t=.15,s=24){return Po({sides:e,waviness:t,radius:s}).pathData}const pr=({sides:e=5,radius:t=50,waviness:s=10,roundness:r=1,strokeWidth:a=12,size:o="sm",letter:i,className:l,style:c,fill:d,stroke:f="none",ariaLabel:m="Parametric Brand Mark",ariaHidden:h=!0,children:p})=>{const{pathData:x,viewBox:v}=u.useMemo(()=>Po({sides:e,radius:t,waviness:s,roundness:r,strokeWidth:a}),[e,t,s,r,a]),b=typeof o=="number",y=b?void 0:o==="lg"?Sn.sizeLg:o==="md"?Sn.sizeMd:Sn.sizeSm,g=b?{...c,"--logo-size":`${o}px`}:c??{};if(d||p){const C=b?o:o==="lg"?54:o==="md"?42:36;return n.jsxs("svg",{width:C,height:C,viewBox:v,className:`${Sn.parametricShape} ${y??""} ${l??""}`.trim(),style:g,role:h?"presentation":"img","aria-label":h?void 0:m,"aria-hidden":h,children:[n.jsx("path",{d:x,fill:d||"currentColor",stroke:f,strokeWidth:a}),p]})}const S=`url("data:image/svg+xml,${encodeURIComponent(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="${v}"><path d="${x}" fill="none" stroke="black" stroke-width="${a}" stroke-linecap="round" stroke-linejoin="round"/></svg>`)}")`;return n.jsxs("div",{className:`${Sn.parametricShape} ${y??""} ${l??""}`.trim(),style:g,role:h?"presentation":"img","aria-label":h?void 0:m,"aria-hidden":h,children:[n.jsx("div",{className:Sn.conicShape,style:{WebkitMaskImage:S,maskImage:S}}),i&&n.jsx("span",{className:Sn.letter,children:i})]})},us={},Sa=e=>{const t=me.getEngineConfig();if(t.securitySalt)return t.securitySalt;if(!(typeof{url:typeof document>"u"?require("url").pathToFileURL(__filename).href:Le&&Le.tagName.toUpperCase()==="SCRIPT"&&Le.src||new URL("folio.cjs",document.baseURI).href}<"u"&&(us!=null&&us.VITE_DEV_SALT)))return(e||me.getStorageNamespace())+"_dev_salt_v1"},mh=Sa(),Rc="73b1e1cccbe22119e026c333e9de035db2a553f8acecdb5406af95f59bf46178",Oo=1800*1e3,uo=60*1e3,es=5,Bc=e=>(e||me.getStorageNamespace())+"_dev_unlocked_at",Ca=Bc(),gr=e=>(e||me.getStorageNamespace())+"_dev_lockout_until",fh=gr(),vr=e=>(e||me.getStorageNamespace())+"_dev_failed_attempts",ph=vr();function ho(e){function t(m,h){return m>>>h|m<<32-h}const s=Math.pow,r=s(2,32);let a="";const o=[],i=e.length*8;let l=[];const c=[];let d=0;const f={};for(let m=2;d<64;m++)if(!f[m]){for(let h=m*m;h<312;h+=m)f[h]=!0;d<8&&(l[d]=s(m,.5)*r|0),c[d]=s(m,1/3)*r|0,d++}for(e+="€";e.length%64-56;)e+="\0";for(let m=0;m<e.length;m++){const h=e.charCodeAt(m);if(h>>8)return"";o[m>>2]|=h<<(3-m%4)*8}o[o.length]=i/r|0,o[o.length]=i|0;for(let m=0;m<o.length;){const h=o.slice(m,m+=16),p=[...l];for(let x=0;x<64;x++){const v=h[x-15],b=h[x-2],y=x<16?h[x]:(h[x]=h[x-16]+(t(v,7)^t(v,18)^v>>>3)+h[x-7]+(t(b,17)^t(b,19)^b>>>10)|0|0)|0,g=l[4]&l[5]^~l[4]&l[6],S=t(l[4],6)^t(l[4],11)^t(l[4],25),C=l[7]+S+g+c[x]+y|0,T=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],_=T+N|0;l=[C+_|0,l[0],l[1],l[2],l[3]+C|0,l[4],l[5],l[6]]}for(let x=0;x<8;x++)l[x]=l[x]+p[x]|0}for(let m=0;m<8;m++)for(let h=3;h>=0;h--){const p=l[m]>>8*h&255;a+=(p<16?"0":"")+p.toString(16)}return a}async function Pc(e,t){const r=`${t??Sa()}:${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(r),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(r)}return ho(r)}async function Oc(e,t,s){if(!e||e.length!==4)return!1;const r=me.getEngineConfig(),a=t??r.securitySalt??Sa(),o=s??r.expectedPinHash??(typeof{url:typeof document>"u"?require("url").pathToFileURL(__filename).href:Le&&Le.tagName.toUpperCase()==="SCRIPT"&&Le.src||new URL("folio.cjs",document.baseURI).href}<"u"&&(us!=null&&us.VITE_DEV_PIN_HASH)?void 0:Rc);return await Pc(e,a)===o}function Qr(){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 Wt(){if(typeof window>"u"||!window.sessionStorage)return null;const e=sessionStorage.getItem(Ca);if(!e)return null;const t=parseInt(e,10);return Number.isFinite(t)?t:null}function Fc(e){typeof window>"u"||!window.sessionStorage||sessionStorage.setItem(Ca,e.toString())}function Tn(){typeof window>"u"||!window.sessionStorage||sessionStorage.removeItem(Ca)}function En(e,t=Date.now()){return e?t-e<Oo:!1}function mo(e,t=Date.now()){if(!e)return 0;const s=t-e,r=Math.max(0,Oo-s);return Math.ceil(r/(60*1e3))}function $s(){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 cn(){const e=$s();if(!e)return null;const t=e.getItem(gr());if(!t)return null;const s=parseInt(t,10);return Number.isFinite(s)?s:null}function fo(e){const t=$s();t&&t.setItem(gr(),e.toString())}function po(){const e=$s();e&&e.removeItem(gr())}function ea(){const e=$s();if(!e)return 0;const t=e.getItem(vr());if(!t)return 0;const s=parseInt(t,10);return Number.isFinite(s)?s:0}function go(e){const t=$s();t&&t.setItem(vr(),e.toString())}function vo(){const e=$s();e&&e.removeItem(vr())}const gh="mjuwqlxdxhujqiqpkcaj";function vh(e){return e.toLowerCase().includes(gh)}function xh(){return typeof{url:typeof document>"u"?require("url").pathToFileURL(__filename).href:Le&&Le.tagName.toUpperCase()==="SCRIPT"&&Le.src||new URL("folio.cjs",document.baseURI).href}<"u"&&!0}function bh(e,t){const s=vh(e);return!t&&s?{ok:!1,code:"DEV_BUILD_WITH_PROD_DB",message:"Development build is pointed at the PRODUCTION database. Cloud disabled. Fix .env.development."}:t&&!s?{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 Kn={};let Vl=null;function qe(){var s,r;const e=typeof{url:typeof document>"u"?require("url").pathToFileURL(__filename).href:Le&&Le.tagName.toUpperCase()==="SCRIPT"&&Le.src||new URL("folio.cjs",document.baseURI).href}<"u"&&(Kn==null?void 0:Kn.VITE_SUPABASE_URL)||typeof process<"u"&&((s=process.env)==null?void 0:s.VITE_SUPABASE_URL)||"",t=typeof{url:typeof document>"u"?require("url").pathToFileURL(__filename).href:Le&&Le.tagName.toUpperCase()==="SCRIPT"&&Le.src||new URL("folio.cjs",document.baseURI).href}<"u"&&(Kn==null?void 0:Kn.VITE_SUPABASE_ANON_KEY)||typeof process<"u"&&((r=process.env)==null?void 0:r.VITE_SUPABASE_ANON_KEY)||"";if(e&&t&&!e.includes("your-project.supabase.co")){const a=e.replace(/\/+$/,""),o=bh(a,xh());return o.ok?{url:a,anonKey:t}:(Vl!==o.code&&(Vl=o.code,console.error(`[env-guard] ${o.code}: ${o.message}`)),null)}return null}const Fn=new Set,Uc=e=>(e||me.getStorageNamespace())+"_missing_supabase_tables",xr=Uc();function ka(){try{if(typeof window<"u"&&window.sessionStorage)return window.sessionStorage;if(typeof sessionStorage<"u")return sessionStorage}catch{}return null}try{const e=ka();if(e){const t=e.getItem(xr);if(t){const s=JSON.parse(t);Array.isArray(s)&&s.filter(r=>r!=="dev_mode_session").forEach(r=>typeof r=="string"&&Fn.add(r))}}}catch{}function St(e){return e==="dev_mode_session"?!0:!Fn.has(e)}function Et(e){if(e!=="dev_mode_session"){Fn.add(e);try{const t=ka();t&&t.setItem(xr,JSON.stringify(Array.from(Fn)))}catch{}}}function Gc(e){Fn.delete(e);try{const t=ka();t&&t.setItem(xr,JSON.stringify(Array.from(Fn)))}catch{}}function yh(){Fn.clear();try{const e=ka();e&&e.removeItem(xr)}catch{}}const Hc=e=>(e||me.getStorageNamespace())+"_dev_lock",rr=Hc(),bs=e=>(e||me.getStorageNamespace())+"_dev_session_id",zc=bs(),qc=3e4,Na=6e4;let er=null;const Qs=typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():`tab-${Date.now()}-${Math.random().toString(36).substring(2,9)}`;let Wa=null;function Vc(){if(typeof window>"u"||typeof BroadcastChannel>"u")return null;if(!Wa)try{Wa=new BroadcastChannel(me.getStorageNamespace()+"_tab_session_dedup")}catch{}return Wa}function Wc(){const e=typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():`session-${Date.now()}-${Math.random().toString(36).substring(2,9)}`;if(er=e,typeof window<"u"&&window.sessionStorage)try{window.sessionStorage.setItem(bs(),e)}catch{}return e}function ja(){if(typeof window<"u"&&window.sessionStorage)try{const e=window.sessionStorage.getItem(bs());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(bs(),t),t}catch{}return er||(er=typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():`session-${Date.now()}-${Math.random().toString(36).substring(2,9)}`),er}function _h(e){if(er=e||null,typeof window<"u"&&window.sessionStorage)try{e?window.sessionStorage.setItem(bs(),e):window.sessionStorage.removeItem(zc)}catch{}}function Fo(e,t=Date.now()){if(!e.isLocked)return!0;const s=new Date(e.lastHeartbeatAt).getTime();return Number.isNaN(s)?!0:t-s>Na}function br(){var e;if(typeof window>"u")return null;try{const t=(e=window.localStorage)==null?void 0:e.getItem(rr);if(!t)return null;const s=JSON.parse(t);return s&&typeof s.isLocked=="boolean"&&s.lockedBySessionId?s:null}catch{return null}}function pt(e){var t,s;if(!(typeof window>"u"))try{e?(s=window.localStorage)==null||s.setItem(rr,JSON.stringify(e)):(t=window.localStorage)==null||t.removeItem(rr)}catch{}}async function In(e){const t=qe();let s=null,r=!1;if(t&&St("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)Et("dev_mode_session");else if(l.ok){r=!0;const c=await l.json();if(c&&c.length>0&&c[0].is_locked){const d=c[0];s={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},pt(s)}else c&&c.length>0&&!c[0].is_locked&&(s=null,pt(null))}}catch{}if(!r&&!s&&(s=br()),!s||Fo(s))return{canAcquire:!0,currentLock:void 0,isSelfSession:!1};const a=s.lockedBySessionId===e;return{canAcquire:a,currentLock:s,isSelfSession:a}}async function xo(e,t="Coordinator"){const s=await In(e);if(!s.canAcquire&&s.currentLock&&!s.isSelfSession)return{success:!1,lock:s.currentLock,error:"Lock is currently held by another active coordinator."};const r=new Date,a=new Date(r.getTime()+Na),o={id:"active_session",isLocked:!0,lockedBySessionId:e,coordinatorLabel:t,lockedAt:r.toISOString(),lastHeartbeatAt:r.toISOString(),expiresAt:a.toISOString()},i=qe();if(i&&St("dev_mode_session"))try{const l=r.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 Et("dev_mode_session"),pt(o),{success:!0,lock:o};if(d.ok){const f=await d.json();if(f&&f.length>0){const m=f[0],h={id:"active_session",isLocked:!0,lockedBySessionId:m.locked_by_session_id,coordinatorLabel:m.coordinator_label||t,lockedAt:m.locked_at,lastHeartbeatAt:m.last_heartbeat_at,expiresAt:m.expires_at};return pt(h),{success:!0,lock:h}}else{const m=await fetch(`${i.url}/rest/v1/dev_mode_session?id=eq.active_session&select=*`,{headers:{apikey:i.anonKey,Authorization:`Bearer ${i.anonKey}`}});if(m.ok){const h=await m.json();if(h.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 pt(o),{success:!0,lock:o}}else if(h[0].is_locked&&h[0].locked_by_session_id!==e){const p={id:"active_session",isLocked:!0,lockedBySessionId:h[0].locked_by_session_id,coordinatorLabel:h[0].coordinator_label||"Coordinator",lockedAt:h[0].locked_at,lastHeartbeatAt:h[0].last_heartbeat_at,expiresAt:h[0].expires_at};return pt(p),{success:!1,lock:p,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 pt(o),{success:!0,lock:o}}async function Kc(e){const t=br();if(t&&t.isLocked&&t.lockedBySessionId!==e&&!Fo(t))return!1;const s=new Date,r=new Date(s.getTime()+Na),a={id:"active_session",isLocked:!0,lockedBySessionId:e,coordinatorLabel:(t==null?void 0:t.coordinatorLabel)||"Coordinator",lockedAt:(t==null?void 0:t.lockedAt)||s.toISOString(),lastHeartbeatAt:s.toISOString(),expiresAt:r.toISOString()},o=qe();if(o&&St("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 Et("dev_mode_session"),pt(a),!0;if(i.ok){const l=await i.json();return l&&l.length>0?(pt(a),!0):!1}return!1}catch{return!0}return pt(a),!0}async function bo(e){const t=br();t&&t.lockedBySessionId===e&&pt(null);const s=qe();if(s&&St("dev_mode_session"))try{const r=await fetch(`${s.url}/rest/v1/dev_mode_session?id=eq.active_session&locked_by_session_id=eq.${e}`,{method:"PATCH",headers:{apikey:s.anonKey,Authorization:`Bearer ${s.anonKey}`,"Content-Type":"application/json"},body:JSON.stringify({is_locked:!1})});return r.status===404?(Et("dev_mode_session"),!0):r.ok}catch{return!0}return!0}function Yc(e){const t=br();t&&t.lockedBySessionId===e&&pt(null);const s=qe();if(!s||!St("dev_mode_session"))return;const r=`${s.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(r,o))return}}catch{}try{typeof fetch<"u"&&fetch(r,{method:"PATCH",headers:{apikey:s.anonKey,Authorization:`Bearer ${s.anonKey}`,"Content-Type":"application/json"},body:a,keepalive:!0}).catch(()=>{})}catch{}}function Xc(e){if(typeof window>"u")return()=>{};const t=s=>{if(s.key===rr)try{const r=s.newValue?JSON.parse(s.newValue):null;e(r)}catch{e(null)}};return window.addEventListener("storage",t),()=>window.removeEventListener("storage",t)}function Dt(e){const t=Date.now().toString(36),s=Math.random().toString(36).substring(2,7);return`${e}-${t}-${s}`}function wh(e){const t=Dt("subsection");return{id:t,type:"subsection",title:"Subsection Title",titlePointId:e?`node.${e}.subsection.${t}.title`:void 0,subtitle:"Subsection details and documentation",subtitlePointId:e?`node.${e}.subsection.${t}.subtitle`:void 0,elements:[]}}function yo(e,t){const s=Dt("section");return{id:s,type:"section",number:String(e+1).padStart(2,"0"),isNumbered:!0,title:"Section Title",titlePointId:t?`node.${t}.section.${s}.title`:void 0,subtitle:"Milestone initiatives and summary of progress",subtitlePointId:t?`node.${t}.section.${s}.subtitle`:void 0,elements:[]}}function Ta(e){return{nodeId:e,version:2,sections:[],updatedAt:new Date().toISOString()}}const Jc=e=>(e||me.getStorageNamespace())+"_portal_db",Sh=1,ys="history_store";function Zc(){return typeof window>"u"||!window.indexedDB?Promise.resolve(null):new Promise(e=>{try{const t=window.indexedDB.open(Jc(),Sh);t.onupgradeneeded=()=>{const s=t.result;s.objectStoreNames.contains(ys)||s.createObjectStore(ys)},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 Qc(e,t){const s=await Zc();return s?new Promise(r=>{try{const i=s.transaction(ys,"readwrite").objectStore(ys).put(t,e);i.onsuccess=()=>r(!0),i.onerror=()=>{console.warn("[historyStorage] Save to IndexedDB failed:",i.error),r(!1)}}catch(a){console.warn("[historyStorage] IndexedDB transaction error:",a),r(!1)}}):!1}async function ed(e){const t=await Zc();return t?new Promise(s=>{try{const o=t.transaction(ys,"readonly").objectStore(ys).get(e);o.onsuccess=()=>{s(o.result??null)},o.onerror=()=>{console.warn("[historyStorage] Read from IndexedDB failed:",o.error),s(null)}}catch(r){console.warn("[historyStorage] IndexedDB read error:",r),s(null)}}):null}function Se(){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 td(){const e=Se();if(e)try{const t=[],s=typeof Object.keys=="function"?Object.keys(e):[];for(const a of s)(a.includes("_draft_canvas_")||a.includes("_canvas_")||a.includes("_live_canvas_")||a.includes("_content_overrides"))&&t.push(a);const r=e.length||0;for(let a=0;a<r;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{td()}catch{}const Gn=e=>(e||me.getStorageNamespace())+"_live_content_overrides",nd=Gn(),Hn=e=>(e||me.getStorageNamespace())+"_draft_content_overrides",Ch=Hn(),yr=e=>(e||me.getStorageNamespace())+"_content_overrides",kh=yr(),Nh=nd,Ia="engine-live-content-change",_r="engine-draft-content-change";let We=null,Je=null,Wl=null,Kl=null;const Uo=new Map,Go=new Map;function Jt(){const e=me.getStorageNamespace();if(Wl!==e&&(We=null,Wl=e),We!==null)return We;const t=Se();if(!t)return We=Uo.get(e)||{},We;try{let s=t.getItem(Gn());s||(s=t.getItem(yr())),We=s?JSON.parse(s):{}}catch{We={}}return We}function wr(){const e=me.getStorageNamespace();if(Kl!==e&&(Je=null,Kl=e),Je!==null)return Je;const t=Se();if(!t)return Je=Go.get(e)||{},Je;try{const s=t.getItem(Hn());Je=s?JSON.parse(s):{}}catch{Je={}}return Je}function Aa(){const e=me.getStorageNamespace();We&&Uo.set(e,{...We});const t=Se();if(!(!t||!We))try{t.setItem(Gn(),JSON.stringify(We))}catch{}}function Ho(){const e=me.getStorageNamespace();Je&&Go.set(e,{...Je});const t=Se();if(!(!t||!Je))try{t.setItem(Hn(),JSON.stringify(Je)),pn(!0)}catch{}}function Tt(e,t,s=!1){if(!(typeof window>"u"))try{const r=s?_r:Ia;window.dispatchEvent(new CustomEvent(r,{detail:{key:e,value:t}}))}catch{}}function hn(e,t,s=!1){const r=s?wr():Jt();if(Object.prototype.hasOwnProperty.call(r,e)&&typeof r[e]=="string")return r[e];if(s){const a=Jt();if(Object.prototype.hasOwnProperty.call(a,e)&&typeof a[e]=="string")return a[e]}return t}function sd(e,t=!1){const s=t?wr():Jt();if(Object.prototype.hasOwnProperty.call(s,e))return!0;if(t){const r=Jt();return Object.prototype.hasOwnProperty.call(r,e)}return!1}function Kt(e,t,s=!1){if(s){const r=wr();r[e]=t,Ho(),Tt(e,t,!0)}else{const r=Jt();r[e]=t,Aa(),Tt(e,t,!1)}}function zo(e,t,s=!1){const r=hn(e,"",s);if(!r)return t;try{const a=JSON.parse(r);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 r=="string"&&r.trim().length>0?{...t,src:r.trim()}:typeof t=="string"?r:t}}function jh(e,t,s=!1){const r=typeof t=="string"?t:JSON.stringify(t);Kt(e,r,s)}function hs(e,t=!1){if(t){const s=wr();Object.prototype.hasOwnProperty.call(s,e)&&(delete s[e],Ho(),Tt(e,null,!0))}else{const s=Jt();Object.prototype.hasOwnProperty.call(s,e)&&(delete s[e],Aa(),Tt(e,null,!1))}}function Sr(e=!1){return e?{...Jt(),...wr()}:{...Jt()}}function Th(e=!1){const t=Se();if(e){if(Go.delete(me.getStorageNamespace()),Je={},t)try{t.removeItem(Hn())}catch{}Tt("*",null,!0)}else{if(Uo.delete(me.getStorageNamespace()),We={},t)try{t.removeItem(Gn()),t.removeItem(yr())}catch{}Tt("*",null,!1)}}function Ea(e,t=!1){t?(Je={...e},Ho(),Tt("*",null,!0)):(We={...e},Aa(),Tt("*",null,!1))}function ms(){We=null,Je=null,Tt("*",null,!1),Tt("*",null,!0)}function Ih(){return{...Jt()}}function $a(e){We={...e},Aa(),Tt("*",null,!1)}function qo(e,t=!1){if(typeof window>"u")return()=>{};const s=t?_r:Ia,r=o=>{const i=o;i.detail&&e(i.detail)},a=o=>{const i=t?Hn():Gn();(o.key===i||o.key===null)&&(t?Je=null:We=null,e({key:"*",value:null}))};return window.addEventListener(s,r),window.addEventListener("storage",a),()=>{window.removeEventListener(s,r),window.removeEventListener("storage",a)}}const rs=new Set;let Yl=!1;function Ah(){if(typeof window>"u"||Yl)return;const e=r=>{const a=r.detail,o=(a==null?void 0:a.key)||"*";rs.forEach(i=>{(o==="*"||o===i.key)&&i.callback()})},t=r=>{const a=r.detail,o=(a==null?void 0:a.key)||"*";rs.forEach(i=>{i.isDevMode&&(o==="*"||o===i.key)&&i.callback()})},s=r=>{const a=Gn(),o=yr(),i=Hn();r.key===a||r.key===o||r.key===null?(We=null,rs.forEach(l=>l.callback())):r.key===i&&(Je=null,rs.forEach(l=>{l.isDevMode&&l.callback()}))};window.addEventListener(Ia,e),window.addEventListener(_r,t),window.addEventListener("storage",s),Yl=!0}function rd(e,t,s=!1){Ah();const r={key:e,isDevMode:s,callback:t};return rs.add(r),()=>{rs.delete(r)}}function ad(e,t,s=!1){return hn(e,t,s)}const Vo=e=>(e||me.getStorageNamespace())+"_draft_canvas_",Eh=Vo(),Wo=e=>(e||me.getStorageNamespace())+"_draft_content_overrides",$h=Wo(),fn=e=>(e||me.getStorageNamespace())+"_draft_active",od=fn(),Un=e=>(e||me.getStorageNamespace())+"_draft_dirty",Lh=Un(),la="engine-draft-status-change",ca="engine-cloud-draft-sync-status",id=1500;let Ko=!1,Yo=!1,_s=null;const Bt={};let Ka=null,ld="saved";function Ls(e){return`${Vo()}${e}`}function cd(e){const t=Bt[e];return t?JSON.parse(JSON.stringify(t)):null}function La(e,t){Bt[e]=JSON.parse(JSON.stringify(t))}function Ma(){if(Ko)return!0;const e=Se();if(!e)return!1;try{const t=e.getItem(fn());if(!t)return!1;if(t==="true")return!0;try{const s=JSON.parse(t);return typeof s=="object"&&s!==null}catch{return!1}}catch{return!1}}function Cr(){if(_s)return _s;const e=Se();if(!e)return null;try{const t=e.getItem(fn());if(!t||t==="true")return null;const s=JSON.parse(t);return s&&typeof s=="object"&&"baseId"in s&&s.baseId||null}catch{return null}}function kr(){const e=Yt(),t=Cr();return{isStale:!!(t&&t!==e),baseId:t,currentActiveId:e}}function Mh(){return kr().isStale}function as(e,t){Ko=e,e?t!==void 0&&(_s=t):_s=null;const s=Se();if(s)try{if(e){const a={baseId:t!==void 0?t:Cr(),startedAt:new Date().toISOString()};s.setItem(fn(),JSON.stringify(a))}else s.removeItem(fn())}catch{}mn()}function Nr(){if(Yo)return!0;const e=Se();if(!e)return!1;try{return e.getItem(Un())==="true"}catch{return!1}}function pn(e){Yo=e;const t=Se();if(t)try{e?t.setItem(Un(),"true"):t.removeItem(Un())}catch{}mn()}function mn(){typeof window>"u"||typeof window.dispatchEvent!="function"||(window.dispatchEvent(new CustomEvent(la,{detail:{isActive:Ma(),isDirty:Nr(),timestamp:new Date().toISOString()}})),window.dispatchEvent(new CustomEvent(_r,{detail:{channel:"draft",timestamp:Date.now(),key:"*",value:null}})))}function dd(e){if(typeof window>"u")return()=>{};const t=()=>{e({isActive:Ma(),isDirty:Nr()})};return window.addEventListener(la,t),()=>window.removeEventListener(la,t)}function ud(){return ld}function hd(e){if(typeof window>"u")return()=>{};const t=s=>{const r=s.detail;e(r)};return window.addEventListener(ca,t),()=>window.removeEventListener(ca,t)}function ts(e,t){if(ld=e,typeof window<"u"&&typeof window.dispatchEvent=="function"){const s={status:e,lastSavedAt:e==="saved"?new Date().toISOString():void 0,error:t};window.dispatchEvent(new CustomEvent(ca,{detail:s}))}}function tr(){Ko=!1,Yo=!1,_s=null;for(const t of Zt)delete Bt[t];const e=Se();if(e)try{for(const t of Zt)e.removeItem(Ls(t));e.removeItem(Wo()),e.removeItem(fn()),e.removeItem(Un())}catch{}mn()}function md(){if(Object.keys(Bt).length>0)return!0;const e=Se();if(!e)return!1;try{return e.getItem(fn())!==null}catch{return!1}}async function fd(){const e=qe();if(!e||!St("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 Et("engine_drafts"),null;if(!t.ok)return null;const s=await t.json();if(!Array.isArray(s)||s.length===0)return null;const r=s[0];return{id:r.id,baseSnapshotId:r.base_snapshot_id,canvases:r.canvases||{},contentOverrides:r.content_overrides||{},updatedAt:r.updated_at,updatedBySession:r.updated_by_session,lockedBySession:r.locked_by_session}}catch(t){return console.warn("[draftService] Fetch active cloud draft failed:",t),null}}function Xl(e,t){if(typeof e!="object"||e===null)return!1;const s=e;return s.nodeId===t&&typeof s.version=="number"&&Array.isArray(s.sections)}async function pd(){var t;const e=qe();if(!e||!St("engine_drafts"))return ts("offline"),!1;ts("saving");try{const r={id:"active_draft",base_snapshot_id:Cr()||Yt(),canvases:Bt,content_overrides:Sr(!0),updated_at:new Date().toISOString(),updated_by_session:((t=Wt())==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(r)});if(a.status===404)return Et("engine_drafts"),ts("offline"),!1;if(!a.ok)throw new Error(`Cloud draft sync failed (${a.status})`);return ts("saved"),!0}catch(s){return console.warn("[draftService] Cloud draft sync error:",s),ts("error",s instanceof Error?s.message:"Sync failed"),!1}}function Da(){Ka&&clearTimeout(Ka),ts("saving"),Ka=setTimeout(()=>{pd().catch(()=>{})},id)}async function ta(e=!1){const t=Wt(),s=En(t),r=md();if(!e&&(s||Ma())&&r&&Object.keys(Bt).length>0){as(!0);return}const a=Yt();if(!e){try{const i=await fd();if(i&&Object.keys(i.canvases).length>0){let l=!1;for(const[c,d]of Object.entries(i.canvases))Xl(d,c)&&(Bt[c]=d,l=!0);if(l){i.contentOverrides&&Object.keys(i.contentOverrides).length>0&&Ea(i.contentOverrides,!0);const c=i.baseSnapshotId||a;as(!0,c),mn(),ms();return}}}catch{}const o=Se();if(o)try{let i=!1;for(const l of Zt){const c=o.getItem(Ls(l));if(c){const d=JSON.parse(c);Xl(d,l)&&(Bt[l]=d,i=!0)}}if(i){as(!0,Cr()||a),mn(),ms();return}}catch{}}for(const o of Zt){const i=Ra(o);Bt[o]=JSON.parse(JSON.stringify(i))}as(!0,a),pn(!1),mn(),ms()}async function Xo(){tr();const e=qe();if(e&&St("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)}mn(),ms()}function gd(e,t,s){const r=s||Yt();for(const o of Zt)e[o]&&(Bt[o]=JSON.parse(JSON.stringify(e[o])));_s=r;const a=Se();if(a)try{a.setItem(od,JSON.stringify({baseId:r,startedAt:new Date().toISOString()})),a.removeItem(Un())}catch{}pn(!1),ms()}const gn=e=>(e||me.getStorageNamespace())+"_live_canvas_",vd=gn(),Jo=e=>(e||me.getStorageNamespace())+"_draft_canvas_",Dh=Jo(),Zo=e=>(e||me.getStorageNamespace())+"_canvas_",Rh=Zo(),Bh=vd,Ms="engine-live-canvas-change",Ds="engine-draft-canvas-change",na=2,Zt=["access","equity","quality","resiliency","governance"];function xd(e){return`${gn()}${e}`}function bd(e){return`${Jo()}${e}`}function yd(){const e=Se();if(!e)return;for(const r of Zt){const a=`${Zo()}${r}`,o=`${gn()}${r}`;!e.getItem(o)&&e.getItem(a)&&e.setItem(o,e.getItem(a))}const t=me.getStorageNamespace()+"_content_overrides",s=me.getStorageNamespace()+"_live_content_overrides";!e.getItem(s)&&e.getItem(t)&&e.setItem(s,e.getItem(t))}function _d(e,t,s){let r=!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,r=!0),s.push(l)}if(Array.isArray(i.elements))for(const c of i.elements)_d(c,t,s)&&(r=!0);return r}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(),r=!0),i.alt&&typeof i.alt=="string"&&i.alt.trim().length>0&&(l.alt=i.alt.trim(),r=!0),i.caption&&typeof i.caption=="string"&&i.caption.trim().length>0&&(l.caption=i.caption.trim(),r=!0),i.driveUrl&&typeof i.driveUrl=="string"&&i.driveUrl.trim().length>0&&(l.driveUrl=i.driveUrl.trim(),r=!0)}catch{}s.push(o)}else if(a.type==="text"){const i=t[o].trim();i.length>0&&(a.content=i,r=!0),s.push(o)}else if(a.type==="gallery"){const i=t[o].trim();i.length>0&&(a.title=i,r=!0),s.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,r=!0),s.push(i.titlePointId)}}return r}function wd(e,t){let s=!1;const r=[];if(!e.sections||!Array.isArray(e.sections))return{modified:!1,consumedKeys:r};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,s=!0),r.push(o)}if(o){const i=`${o}.isNumbered`;t[i]&&(a.isNumbered=t[i]==="true",s=!0,r.push(i))}if(Array.isArray(a.elements))for(const i of a.elements)_d(i,t,r)&&(s=!0)}return{modified:s,consumedKeys:r}}function ws(e){const t=Se();if(!t)return;const s=e==="draft",r=s?me.getStorageNamespace()+"_draft_content_overrides":me.getStorageNamespace()+"_live_content_overrides",a=t.getItem(r);if(!a)return;let o;try{o=JSON.parse(a)}catch{return}const i=[];for(const l of Zt){const c=s?It(l,!0):Ra(l);if(!c||(c.version??1)>=na)continue;const{modified:d,consumedKeys:f}=wd(c,o);i.push(...f),(d||(c.version??1)<na)&&(c.version=na,s?jr(c,!0):Rs(c))}if(i.length>0){for(const l of i)delete o[l];t.setItem(r,JSON.stringify(o))}}if(typeof window<"u")try{yd(),ws("live"),ws("draft")}catch{}function da(e,t){if(typeof e!="object"||e===null)return!1;const s=e;return s.nodeId===t&&typeof s.version=="number"&&Array.isArray(s.sections)&&(s.updatedAt===void 0||typeof s.updatedAt=="string")}function vt(e){return e.map((t,s)=>({...t,number:String(s+1).padStart(2,"0")}))}function _o(e,t,s){const r=[...e.sections];return typeof s=="number"&&s>=0&&s<=r.length?r.splice(s,0,t):r.push(t),{...e,sections:vt(r),updatedAt:new Date().toISOString()}}function wo(e,t,s,r){const a=e.sections.map(o=>{if(o.id!==t)return o;const i=[...o.elements];return typeof r=="number"&&r>=0&&r<=i.length?i.splice(r,0,s):i.push(s),{...o,elements:i}});return{...e,sections:a,updatedAt:new Date().toISOString()}}function So(e,t,s,r,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 f=[...d.elements];return typeof r=="number"&&r>=0&&r<=f.length?f.splice(r,0,s):f.push(s),{...d,elements:f}});return{...i,elements:c}}const l=[...i.elements];return typeof r=="number"&&r>=0&&r<=l.length?l.splice(r,0,s):l.push(s),{...i,elements:l}});return{...e,sections:o,updatedAt:new Date().toISOString()}}function Sd(e,t,s,r){const a=s==="up"?-1:1,o=e.sections.findIndex(f=>f.id===t);if(o!==-1&&(!r||e.sections.some(f=>f.id===r))){const f=o+a;if(f<0||f>=e.sections.length)return e;const m=[...e.sections],[h]=m.splice(o,1);return m.splice(f,0,h),{...e,sections:vt(m),updatedAt:new Date().toISOString()}}let i=-1,l=-1,c=-1,d=-1;for(let f=0;f<e.sections.length;f++){const m=e.sections[f],h=m.elements.findIndex(p=>p.id===t);if(h!==-1){i=f,l=h;break}for(let p=0;p<m.elements.length;p++){const x=m.elements[p];if(x.type==="subsection"){const v=x.elements.findIndex(b=>b.id===t);if(v!==-1){i=f,c=p,d=v;break}}}if(i!==-1)break}if(i===-1)return e;if(c!==-1&&d!==-1){const f=e.sections[i],m=f.elements[c],h=d+a;if(h>=0&&h<m.elements.length){const p=[...m.elements],[x]=p.splice(d,1);p.splice(h,0,x);const v=[...f.elements];v[c]={...m,elements:p};const b=[...e.sections];return b[i]={...f,elements:v},{...e,sections:b,updatedAt:new Date().toISOString()}}if(s==="up"&&d===0){const p=m.elements.filter((y,g)=>g!==d),x=m.elements[d],v=[...f.elements];v[c]={...m,elements:p},v.splice(c,0,x);const b=[...e.sections];return b[i]={...f,elements:v},{...e,sections:b,updatedAt:new Date().toISOString()}}if(s==="down"&&d===m.elements.length-1){const p=m.elements.filter((y,g)=>g!==d),x=m.elements[d],v=[...f.elements];v[c]={...m,elements:p},v.splice(c+1,0,x);const b=[...e.sections];return b[i]={...f,elements:v},{...e,sections:b,updatedAt:new Date().toISOString()}}return e}if(l!==-1){const f=e.sections[i],m=l+a;if(m>=0&&m<f.elements.length){const h=[...f.elements],[p]=h.splice(l,1);h.splice(m,0,p);const x=[...e.sections];return x[i]={...f,elements:h},{...e,sections:x,updatedAt:new Date().toISOString()}}if(s==="up"&&l===0){if(i>0){const h=e.sections[i-1],p=[...f.elements],[x]=p.splice(0,1),v=[...h.elements,x],b=[...e.sections];return b[i-1]={...h,elements:v},b[i]={...f,elements:p},{...e,sections:b,updatedAt:new Date().toISOString()}}return e}if(s==="down"&&l===f.elements.length-1){if(i<e.sections.length-1){const h=e.sections[i+1],p=[...f.elements],[x]=p.splice(l,1),v=[x,...h.elements],b=[...e.sections];return b[i]={...f,elements:p},b[i+1]={...h,elements:v},{...e,sections:b,updatedAt:new Date().toISOString()}}return e}}return e}function Cd(e,t,s,r){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(m=>m.id===t);if(c!==-1){const m=[...l.elements];return[a]=m.splice(c,1),{...l,elements:m}}let d=!1;const f=l.elements.map(m=>{if(m.type!=="subsection")return m;const h=m.elements.findIndex(p=>p.id===t);if(h!==-1){d=!0;const p=[...m.elements];return[a]=p.splice(h,1),{...m,elements:p}}return m});return d?{...l,elements:f}:l}),!a)return e;if(s===e.nodeId||s==="root"){if(a.type==="section"){const l=typeof r=="number"&&r>=0&&r<=o.length?r: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 r=="number"&&r>=0&&r<o.length?r:o.length-1,c=o[l],d=[...c.elements,a];o[l]={...c,elements:d}}return{...e,sections:vt(o),updatedAt:new Date().toISOString()}}return o=o.map(l=>{if(l.id===s){const d=[...l.elements],f=typeof r=="number"&&r>=0&&r<=d.length?r:d.length;return d.splice(f,0,a),{...l,elements:d}}const c=l.elements.findIndex(d=>d.type==="subsection"&&d.id===s);if(c!==-1&&a&&a.type!=="section"&&a.type!=="subsection"){const d=l.elements[c],f=[...d.elements],m=typeof r=="number"&&r>=0&&r<=f.length?r:f.length;f.splice(m,0,a);const h=[...l.elements];return h[c]={...d,elements:f},{...l,elements:h}}return l}),{...e,sections:vt(o),updatedAt:new Date().toISOString()}}function kd(e,t,s){if(e.sections.some(a=>a.id===t)&&(!s||s===e.nodeId)){const a=e.sections.filter(o=>o.id!==t);return{...e,sections:vt(a),updatedAt:new Date().toISOString()}}const r=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:r,updatedAt:new Date().toISOString()}}function Nd(e,t,s){const r=e.sections.map(a=>{if(a.id===t)return{...a,...s};const o=a.elements.map(i=>{if(i.id===t)return{...i,...s};if(i.type==="subsection"){const l=i.elements.map(c=>c.id===t?{...c,...s}:c);return{...i,elements:l}}return i});return{...a,elements:o}});return{...e,sections:r,updatedAt:new Date().toISOString()}}function sa(e,t){const s=e.sections.findIndex(r=>r.id===t);if(s!==-1)return{item:e.sections[s],kind:"section",index:s,sectionId:t};for(const r of e.sections)for(let a=0;a<r.elements.length;a++){const o=r.elements[a];if(o.id===t)return{item:o,kind:o.type==="subsection"?"subsection":"leaf",index:a,sectionId:r.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:r.id,subsectionId:o.id}}}return null}function Ra(e){const t=Se(),s=`${gn()}${e}`;if(t)try{const r=t.getItem(s);if(r){const a=JSON.parse(r);if(da(a,e))return{...a,sections:vt(a.sections)}}}catch{}return Ta(e)}function Rs(e,t){const s={...e,sections:vt(e.sections),updatedAt:new Date().toISOString()},r=Se();let a=!0,o;if(r)try{r.setItem(`${gn()}${e.nodeId}`,JSON.stringify(s))}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:s};window.dispatchEvent(new CustomEvent(Ms,{detail:i}))}return{ok:a,error:o,document:s}}function It(e,t=!1){const s=Se();if(t){const r=cd(e);if(r&&da(r,e))return{...r,sections:vt(r.sections)};if(s)try{const a=s.getItem(Ls(e));if(a){const o=JSON.parse(a);if(da(o,e))return{...o,sections:vt(o.sections)}}}catch{}}return Ra(e)}function jr(e,t=!1,s){const r={...e,sections:vt(e.sections),updatedAt:new Date().toISOString()},a=Se();let o=!0,i;if(t)La(e.nodeId,r),pn(!0),Da();else if(a)try{a.setItem(`${gn()}${e.nodeId}`,JSON.stringify(r))}catch(l){console.error("Storage quota exceeded while saving canvas document:",l),o=!1,i="quota"}else o=!1,i="unknown";if(o&&!(s!=null&&s.silent)&&typeof window<"u"&&typeof window.dispatchEvent=="function"){const l=t?Ds:Ms,c={nodeId:e.nodeId,document:r};window.dispatchEvent(new CustomEvent(l,{detail:c}))}return{ok:o,error:i,document:r}}function Tr(e=!1){if(typeof window>"u"||typeof window.dispatchEvent!="function")return;const t=e?Ds:Ms;window.dispatchEvent(new CustomEvent(t,{detail:{nodeId:"*"}}))}function Qo(e,t=!1){const s=Ta(e),r=Se();if(t){if(La(e,s),pn(!0),Da(),r)try{r.removeItem(Ls(e))}catch{}}else if(r)try{r.removeItem(`${gn()}${e}`)}catch{}if(typeof window<"u"&&typeof window.dispatchEvent=="function"){const a=t?Ds:Ms,o={nodeId:e,document:s};window.dispatchEvent(new CustomEvent(a,{detail:o}))}return s}function ei(e,t,s=!1){if(typeof window>"u")return()=>{};const r=s?Ds:Ms,a=i=>{const l=i;if(l.detail&&(l.detail.nodeId===e||l.detail.nodeId==="*")){const c=l.detail.nodeId==="*"||!l.detail.document?It(e,s):l.detail.document;t(c)}},o=i=>{const l=s?bd(e):xd(e);if((i.key===l||i.key===null)&&i.newValue)try{const c=JSON.parse(i.newValue);da(c,e)&&t({...c,sections:vt(c.sections)})}catch{}};return window.addEventListener(r,a),window.addEventListener("storage",o),()=>{window.removeEventListener(r,a),window.removeEventListener("storage",o)}}async function ti(e){const t=It(e),s=qe();if(!s)return{success:!0};if(!St("pillar_canvas"))return{success:!1,error:"Table pillar_canvas unavailable in this session"};try{const r=await fetch(`${s.url}/rest/v1/node_canvas`,{method:"POST",headers:{apikey:s.anonKey,Authorization:`Bearer ${s.anonKey}`,"Content-Type":"application/json",Prefer:"resolution=merge-duplicates,return=representation"},body:JSON.stringify({node_id:e,document:t,updated_at:t.updatedAt})});return r.status===404?(Et("pillar_canvas"),{success:!1,error:`Cloud sync responded with status ${r.status}`}):r.ok?{success:!0}:{success:!1,error:`Cloud sync responded with status ${r.status}`}}catch(r){return{success:!1,error:r instanceof Error?r.message:String(r)}}}const Ph={getNodeCanvas:It,saveNodeCanvas:jr,resetNodeCanvas:Qo,subscribeToCanvasChange:ei,deployNodeCanvasToCloud:ti};function At(){const e=me.getEngineConfig();return e.nodes&&e.nodes.length>0?e.nodes.map(t=>t.id):[...Zt]}const ni=e=>(e||me.getStorageNamespace())+"_portal_sync",Oh=ni(),Ss=e=>(e||me.getStorageNamespace())+"_history_manifest",si=Ss(),Cs=e=>(e||me.getStorageNamespace())+"_live_active_published_id",Fh=Cs(),ks=me.getStorageNamespace()+"_active_published_id",Uh=ks,ua="engine-history-change",Bs=1,jd=20,Td=6e4;let Rt=null,Jl=0;function Ba(e,t){let s=0,r=0,a=0;for(const i of Object.values(e))if(!(!i||!Array.isArray(i.sections))){s+=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"){r+=1;const d=c;Array.isArray(d.elements)&&(a+=d.elements.length)}else a+=1}const o=Object.keys(t||{}).length;return{totalSections:s,totalSubsections:r,totalLeafElements:a,totalTextOverrides:o}}function Yt(){const e=Se();if(!e)return"snap-system-baseline";const t=e.getItem(Cs());if(t)return t;const s=e.getItem(ks);let r;try{const o=e.getItem(Ss());if(o){const i=JSON.parse(o);r=(i==null?void 0:i.activePublishedId)||(i==null?void 0:i.activeMilestoneId)}}catch{}const a=s||r||"snap-system-baseline";try{e.setItem(Cs(),a),e.removeItem(ks)}catch{}return a}function Ps(e){const t=Se();if(t)try{t.setItem(Cs(),e),t.removeItem(ks)}catch{}}function Pa(e=!0){const t={};for(const a of At())t[a]=Ta(a);const s={},r=Ba(t,s);return{id:"snap-system-baseline",schemaVersion:Bs,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:s,summary:r}}async function ri(){try{const e=await ed(si);if(e&&Array.isArray(e.snapshots)&&e.snapshots.length>0)return Rt=e,en(e),e}catch{}return $t()}function $t(){const e={snapshots:[],updatedAt:new Date().toISOString()},t=Se();if(!t)return Rt||e;try{const s=t.getItem(Ss());if(!s)return Rt||e;const r=JSON.parse(s);if(r&&Array.isArray(r.snapshots)){const a={lastRestoredId:r.lastRestoredId,snapshots:r.snapshots,updatedAt:r.updatedAt||r.lastUpdated||new Date().toISOString()};return Rt=Rt||a,Rt}}catch{}return Rt||e}function en(e){const t={...e,updatedAt:e.updatedAt||new Date().toISOString()};Rt=t,Qc(si,t).catch(()=>{});const s=Se();if(s){const r={version:Bs,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{s.setItem(Ss(),JSON.stringify(r))}catch{try{const a={...r,snapshots:r.snapshots.filter(o=>o.type!=="autosave")};s.setItem(Ss(),JSON.stringify(a))}catch{}}}if(typeof window<"u")try{window.dispatchEvent(new CustomEvent(ua,{detail:{manifest:t}}))}catch{}}function Id(e){if(typeof window>"u")return()=>{};const t=s=>{var a;const r=s;(a=r==null?void 0:r.detail)!=null&&a.manifest?e(r.detail.manifest):e($t())};return window.addEventListener(ua,t),()=>window.removeEventListener(ua,t)}function Oa(e,t="",s="milestone",r){const a={};for(const d of At())a[d]=It(d);const o=Sr(),i=Ba(a,o),l=r||ja();return{id:`snap-${Date.now()}-${s}-${Math.random().toString(36).substring(2,7)}`,schemaVersion:Bs,type:s,title:e.trim(),notes:t.trim(),createdAt:new Date().toISOString(),authorSessionId:l,canvases:a,contentOverrides:o,summary:i}}function Gh(e,t="",s){const r=Oa(e,t,"milestone",s),a=$t();return a.snapshots=[r,...a.snapshots],en(a),r}function ai(e){let t=0;return e.filter(s=>s.type!=="autosave"?!0:(t+=1,t<=jd))}function Hh(e,t=!1){const s=Date.now();if(!t&&s-Jl<Td)return null;Jl=s;const r=Oa("Auto-Save Checkpoint","","autosave",e),a=$t(),o=ai([r,...a.snapshots]);return a.snapshots=o,en(a),r}async function zh(e){const t=$t(),s=t.snapshots.find(a=>a.id===e);if(!s)return{success:!1,error:`Snapshot ${e} not found`};const r=Oa("Pre-Restore Safety Backup",`Automatic safety backup before restoring "${s.title||s.id}"`,"safety_backup");for(const a of At()){const o=s.canvases[a];o&&jr(o)}return Ea(s.contentOverrides||{}),ws("live"),t.snapshots=[r,...t.snapshots],Ps(s.id),en(t),{success:!0,safetySnapshotId:r.id}}function qh(e){const t=$t(),s=t.snapshots.length;return t.snapshots=t.snapshots.filter(r=>r.id!==e),t.snapshots.length!==s?(en(t),!0):!1}function Vh(){Rt={snapshots:[],updatedAt:new Date().toISOString()},en(Rt)}function Wh(){const e=$t(),t={};for(const r of At())t[r]=It(r);const s={engineBackupVersion:Bs,exportedAt:new Date().toISOString(),tenant:"the host application",manifest:e,activeState:{canvases:t,contentOverrides:Sr()}};return JSON.stringify(s,null,2)}function Kh(e){try{const t=JSON.parse(e);let s=[];if(t&&Array.isArray(t.snapshots))s=t.snapshots;else if(t&&t.manifest&&Array.isArray(t.manifest.snapshots))s=t.manifest.snapshots;else return{success:!1,importedCount:0,error:"Invalid backup structure: missing snapshots array"};const r=s.filter(c=>c&&typeof c.id=="string"&&typeof c.title=="string"&&typeof c.type=="string"&&c.canvases&&typeof c.canvases=="object");if(r.length===0)return{success:!1,importedCount:0,error:"No valid snapshots found in backup file"};const a=$t(),o=new Set(a.snapshots.map(c=>c.id));let i=0;const l=[];for(const c of r)o.has(c.id)||(l.push(c),o.add(c.id),i+=1);return a.snapshots=ai([...l,...a.snapshots]),en(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 Co(e){var t;try{as(!0,e.id);const s=new Date().toISOString();for(const r of At()){const a=((t=e.canvases)==null?void 0:t[r])||Ta(r),o={...JSON.parse(JSON.stringify(a)),nodeId:r,sections:vt(a.sections||[]),updatedAt:s};La(r,o);const i=Se();if(i)try{i.setItem(Ls(r),JSON.stringify(o))}catch{}}if(Ea(e.contentOverrides||{},!0),ws("draft"),typeof window<"u"){for(const r of At()){const a=It(r,!0),o={nodeId:r,document:a};window.dispatchEvent(new CustomEvent(Ds,{detail:o}))}Tr(!0)}return pn(!0),Da(),!0}catch(s){return console.warn("[historyService] Failed to restore snapshot to draft:",s),!1}}function dn(){const e=$t(),t=Yt(),s=e.snapshots.map(r=>{const a=r,o=typeof a.description=="string"?a.description:r.notes||"",i=r.id===t;return{id:r.id,schemaVersion:r.schemaVersion||1,title:r.title,description:o,createdAt:r.createdAt,authorSessionId:r.authorSessionId,isActive:i,canvases:r.canvases,contentOverrides:r.contentOverrides,summary:r.summary}});if(!s.some(r=>r.id==="snap-system-baseline")){const r=s.some(a=>a.isActive);s.push(Pa(!r))}if(!s.some(r=>r.isActive)&&s.length>0){const r=s.find(a=>a.id==="snap-system-baseline");r?r.isActive=!0:s[0].isActive=!0}return s}async function Ad(){const e=qe();if(!e||!St("engine_history"))return dn();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 Et("engine_history"),dn();if(!t.ok)return console.warn(`[historyService] Supabase cloud fetch returned HTTP ${t.status}. Falling back to persistent local storage.`),dn();const s=await t.json();if(!Array.isArray(s)||s.length===0)return dn();const r=s.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(!r.some(o=>o.id==="snap-system-baseline")){const o=r.some(i=>i.isActive);r.push(Pa(!o))}const a=r.find(o=>o.isActive);return a&&Ps(a.id),r}catch(t){return console.warn("[historyService] Cloud fetch error:",t),dn()}}async function Ed(){var t,s;const e=qe();if(!e||!St("engine_history"))return null;try{const r=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(r.status===404)return Et("engine_history"),null;if(!r.ok)return null;const a=await r.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:((s=o.snapshot_data)==null?void 0:s.contentOverrides)||{},summary:o.summary||{totalSections:0,totalSubsections:0,totalLeafElements:0,totalTextOverrides:0}}}catch(r){return console.warn("[historyService] Fetch active version error:",r),null}}function Yh(e=!1){const t=kr();return t.isStale&&!e?{canPublish:!1,reason:"DRAFT_STALE",staleness:t}:{canPublish:!0,staleness:t}}async function $d(e,t="Published Revision",s,r){const a=typeof r=="boolean"?r:!!(r!=null&&r.forcePublish),o=kr();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=Wt();if(l!==null&&!En(l))return{success:!1,snapshot:null,cloudSynced:!1,error:"Session expired. Please unlock Developer Mode again."};const c=s||ja(),d={};for(const T of At())d[T]=It(T,!0);const f=Sr(!0),m=Ba(d,f),h=`pub-${Date.now()}-${Math.random().toString(36).substring(2,7)}`,p=t.trim()||"Published Revision",x=new Date().toISOString(),v={id:h,schemaVersion:Bs,title:p,description:i,createdAt:x,authorSessionId:c,isActive:!0,canvases:d,contentOverrides:f,summary:m};for(const T of At())Rs(d[T],{silent:!0});Tr(!1),$a(f);const b=$t(),y={id:v.id,schemaVersion:v.schemaVersion,type:"milestone",title:v.title,notes:v.description,createdAt:v.createdAt,authorSessionId:v.authorSessionId,canvases:v.canvases,contentOverrides:v.contentOverrides,summary:v.summary};b.snapshots=[y,...b.snapshots],b.activeMilestoneId=v.id,b.activePublishedId=v.id,Ps(v.id),en(b),gd(d),Ld({type:"MASID_PUBLISH_BROADCAST",snapshotId:v.id,timestamp:v.createdAt,canvases:v.canvases,contentOverrides:v.contentOverrides,activePublishedId:v.id});let g=!1,S;const C=qe();if(C)try{const T={id:v.id,schema_version:v.schemaVersion,title:v.title,description:v.description,snapshot_data:{canvases:v.canvases,contentOverrides:v.contentOverrides},summary:v.summary,is_active:!0,author_session_id:v.authorSessionId,created_at:v.createdAt},N=await fetch(`${C.url}/rest/v1/engine_history`,{method:"POST",headers:{apikey:C.anonKey,Authorization:`Bearer ${C.anonKey}`,"Content-Type":"application/json",Prefer:"return=representation"},body:JSON.stringify(T)});if(N.status===404&&Et("engine_history"),N.ok){g=!0,Gc("engine_history");try{await fetch(`${C.url}/rest/v1/engine_history?is_active=eq.true&id=neq.${v.id}`,{method:"PATCH",headers:{apikey:C.anonKey,Authorization:`Bearer ${C.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 S=`Cloud sync failed with HTTP ${N.status}`}catch(T){S=T instanceof Error?T.message:"Network error during cloud publish"}try{$e.compileAndDeployToEdgeKV(v).catch(T=>{console.warn("[historyService] Non-blocking Edge KV pre-bake warning:",T)})}catch(T){console.warn("[historyService] Edge KV pre-bake dispatch error:",T)}return{success:!0,snapshot:v,cloudSynced:g,error:S}}let un=null;function oi(){if(typeof BroadcastChannel>"u")return null;if(!un)try{un=new BroadcastChannel(ni()),un.onmessage=e=>{Md(e.data)}}catch(e){console.warn("[historyService] Failed to initialize BroadcastChannel:",e),un=null}return un}function Xh(){if(un){try{un.close()}catch{}un=null}}function Ld(e){const t=oi();if(t)try{t.postMessage(e)}catch(s){console.warn("[historyService] Failed to postMessage on sync BroadcastChannel:",s)}}function Md(e){if(!(!e||e.type!=="MASID_PUBLISH_BROADCAST")){if(e.canvases){for(const t of At())e.canvases[t]&&Rs(e.canvases[t],{silent:!0});Tr(!1)}e.contentOverrides&&$a(e.contentOverrides),e.activePublishedId&&Ps(e.activePublishedId)}}if(typeof window<"u")try{oi()}catch{}let Rn=!1,fs=!1;const ko=new Set;function ii(){return!1}function Jh(){return Rn}function Dd(e){return ko.add(e),()=>{ko.delete(e)}}function Ya(e){Rn=e,ko.forEach(t=>{try{t(e)}catch(s){console.warn("[historyService] Hydration listener error:",s)}})}function Zh(){const e=Se(),t=e?e.getItem(Cs())||e.getItem(ks):null;return{isHydrating:Rn,hasConfirmedData:!!t||fs,source:t?"cache":fs?"cloud":"baseline",activePublishedId:t}}function Qh(){Rn=!1,fs=!1}let Ws=null;function Rd(){return Ws||(Ws=(async()=>{const e=ii();try{const t=await Ed();if(!t)return fs=!0,(e||Rn)&&Ya(!1),!1;Ps(t.id);for(const s of At())t.canvases[s]&&Rs(t.canvases[s],{silent:!0});return Tr(!1),t.contentOverrides&&$a(t.contentOverrides),ws("live"),fs=!0,(e||Rn)&&Ya(!1),!0}catch(t){return console.warn("[historyService] Hydrate active version error:",t),fs=!0,Rn&&Ya(!1),!1}finally{Ws=null}})(),Ws)}const em="_toastPortal_f8wvm_7",tm="_toastSuccess_f8wvm_49",nm="_toastError_f8wvm_54",sm="_toastInfo_f8wvm_59",rm="_iconWrapper_f8wvm_64",am="_successIcon_f8wvm_74",om="_errorIcon_f8wvm_79",im="_infoIcon_f8wvm_84",lm="_svgIcon_f8wvm_89",cm="_message_f8wvm_94",dm="_dismissButton_f8wvm_101",um="_actionButton_f8wvm_136",nt={toastPortal:em,toastSuccess:tm,toastError:nm,toastInfo:sm,iconWrapper:rm,successIcon:am,errorIcon:om,infoIcon:im,svgIcon:lm,message:cm,dismissButton:dm,actionButton:um};function hm(e="success"){try{const t=window.AudioContext||window.webkitAudioContext;if(!t)return;const s=new t;s.state==="suspended"&&s.resume();const r=s.currentTime,a=s.createGain();if(a.connect(s.destination),e==="success"){const o=s.createOscillator(),i=s.createOscillator();o.type="sine",i.type="sine",o.frequency.setValueAtTime(587.33,r),i.frequency.setValueAtTime(880,r+.06),a.gain.setValueAtTime(.05,r),a.gain.exponentialRampToValueAtTime(.07,r+.06),a.gain.exponentialRampToValueAtTime(1e-4,r+.26),o.connect(a),i.connect(a),o.start(r),o.stop(r+.06),i.start(r+.06),i.stop(r+.26)}else if(e==="error"){const o=s.createOscillator();o.type="triangle",o.frequency.setValueAtTime(329.63,r),o.frequency.setValueAtTime(261.63,r+.07),a.gain.setValueAtTime(.06,r),a.gain.exponentialRampToValueAtTime(1e-4,r+.2),o.connect(a),o.start(r),o.stop(r+.2)}else{const o=s.createOscillator();o.type="sine",o.frequency.setValueAtTime(659.25,r),a.gain.setValueAtTime(.04,r),a.gain.exponentialRampToValueAtTime(1e-4,r+.18),o.connect(a),o.start(r),o.stop(r+.18)}setTimeout(()=>{try{s.close()}catch{}},320)}catch{}}const mm=n.jsx("svg",{className:nt.svgIcon,viewBox:"0 0 20 20",fill:"currentColor","aria-hidden":"true",children:n.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"})}),fm=n.jsx("svg",{className:nt.svgIcon,viewBox:"0 0 20 20",fill:"currentColor","aria-hidden":"true",children:n.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"})}),pm=n.jsx("svg",{className:nt.svgIcon,viewBox:"0 0 20 20",fill:"currentColor","aria-hidden":"true",children:n.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"})}),Ot=({message:e,type:t="success",durationMs:s=3500,onDismiss:r,actionLabel:a,onAction:o,playAudio:i=!0})=>{const[l,c]=u.useState(!1);if(u.useEffect(()=>{c(!0),i&&hm(t)},[t,i]),u.useEffect(()=>{if(s<=0)return;const h=setTimeout(()=>{r()},s);return()=>clearTimeout(h)},[s,r]),!l||typeof document>"u")return null;const d=t==="success"?n.jsx("span",{className:`${nt.iconWrapper} ${nt.successIcon}`,children:mm}):t==="error"?n.jsx("span",{className:`${nt.iconWrapper} ${nt.errorIcon}`,children:fm}):n.jsx("span",{className:`${nt.iconWrapper} ${nt.infoIcon}`,children:pm}),f=t==="error"?nt.toastError:t==="info"?nt.toastInfo:nt.toastSuccess,m=n.jsxs("div",{role:"status","aria-live":"polite",className:`${nt.toastPortal} ${f}`,children:[d,n.jsx("span",{className:nt.message,children:e}),a&&o&&n.jsx("button",{type:"button",className:nt.actionButton,onClick:()=>{o(),r()},children:a}),n.jsx("button",{type:"button",className:nt.dismissButton,onClick:r,"aria-label":"Dismiss notification",children:"✕"})]});return fr.createPortal(m,document.body)},ar=new Set;function Bd(e,t){t?ar.add(e):ar.delete(e)}function No(e){ar.delete(e)}function gm(){ar.clear()}function Pd(){return ar.size>0?!0:Nr()}function li(e){if(Pd())return e.preventDefault(),e.returnValue="",""}const Od=u.createContext(null),Fd=({children:e,securitySalt:t,expectedPinHash:s})=>{const[r,a]=u.useState(()=>Qr()),[o,i]=u.useState(()=>{if(!Qr())return!1;const B=Wt();return En(B)}),[l,c]=u.useState(!1),[d,f]=u.useState(!1),[m,h]=u.useState(()=>{const B=cn();return B&&Date.now()<B?"locked_out":"idle"}),[p,x]=u.useState(()=>ja()),[v,b]=u.useState(!1),[y,g]=u.useState(null),[S,C]=u.useState(!1),[T,N]=u.useState(()=>Math.max(0,es-ea())),[_,k]=u.useState(()=>{const B=cn();return B&&Date.now()<B?Math.ceil((B-Date.now())/1e3):0}),[w,$]=u.useState(()=>mo(Wt())),[I,j]=u.useState(()=>Nr()),[D,H]=u.useState(null),L=u.useRef(null),U=u.useRef(null),G=u.useRef(null),z=u.useRef(v),q=u.useRef(l),P=u.useRef(d);u.useEffect(()=>{z.current=v},[v]),u.useEffect(()=>{q.current=l},[l]),u.useEffect(()=>{P.current=d},[d]),u.useEffect(()=>{const B=Vc();if(!B)return;const E=O=>{if(!(!O.data||typeof O.data!="object")){if(O.data.type==="PING_SESSION"&&O.data.sessionId===p)O.data.tabInstanceId!==Qs&&B.postMessage({type:"SESSION_OWNED",sessionId:p,ownerTabInstanceId:Qs});else if(O.data.type==="SESSION_OWNED"&&O.data.sessionId===p&&O.data.ownerTabInstanceId!==Qs){console.warn("[DeveloperModeContext] Cloned tab detected! Disengaging inherited Dev Mode."),Tn();const ie=Wc();x(ie),i(!1),q.current=!1,c(!1),b(!0),z.current=!0,In(ie).then(ce=>{g(ce.currentLock||null)})}}};return B.addEventListener("message",E),B.postMessage({type:"PING_SESSION",sessionId:p,tabInstanceId:Qs}),()=>{B.removeEventListener("message",E)}},[p]),u.useEffect(()=>dd(E=>{j(E.isDirty)}),[]);const[F,R]=u.useState(()=>ii());u.useEffect(()=>Dd(E=>{R(E)}),[]);const[W,se]=u.useState(()=>ud());u.useEffect(()=>hd(E=>{se(E.status)}),[]),u.useEffect(()=>{Rd().catch(()=>{})},[]),u.useEffect(()=>{o&&ta(!1).catch(B=>{console.error("Draft initialization failed:",B),H({message:"Draft Initialization Failed: Could not initialize draft workspace.",type:"error"}),i(!1)})},[o]),u.useEffect(()=>{const B=()=>{const E=Qr();a(E),E||(i(!1),c(!1),f(!1))};return window.addEventListener("resize",B),()=>window.removeEventListener("resize",B)},[]),u.useEffect(()=>{const B=()=>{const E=cn();if(E){const O=E-Date.now();if(O>0){k(Math.ceil(O/1e3)),h("locked_out");return}else po(),vo(),N(es),k(0),h("idle")}else k(0)};return B(),U.current=window.setInterval(B,1e3),()=>{U.current&&clearInterval(U.current)}},[]),u.useEffect(()=>{if(!o){L.current&&clearInterval(L.current);return}const B=()=>{const E=Wt();En(E)?$(mo(E)):(C(!0),c(!0),$(0))};return B(),L.current=window.setInterval(B,5e3),()=>{L.current&&clearInterval(L.current)}},[o]),u.useEffect(()=>{if(!o){G.current&&(clearInterval(G.current),G.current=null);return}xo(p);const B=()=>{Kc(p).then(async ie=>{if(!ie){console.warn("[DeveloperModeContext] Liveness heartbeat rejected: lock held by another coordinator."),i(!1),Tn(),tr(),b(!0),z.current=!0;const ce=await In(p);g(ce.currentLock||null),H({message:"Developer Mode session ended: another coordinator is currently active.",type:"error"})}})};G.current=window.setInterval(B,qc);const E=()=>{Yc(p)},O=ie=>{o&&li(ie)};return window.addEventListener("beforeunload",O),window.addEventListener("pagehide",E),()=>{G.current&&(clearInterval(G.current),G.current=null),window.removeEventListener("beforeunload",O),window.removeEventListener("pagehide",E)}},[o,p]),u.useEffect(()=>{if(!o)return;const B=async()=>{const ie=await In(p);!ie.canAcquire&&ie.currentLock&&!ie.isSelfSession&&(console.warn("[DeveloperModeContext] Active lock claimed by another coordinator."),i(!1),Tn(),tr(),b(!0),z.current=!0,g(ie.currentLock),H({message:"Developer Mode session ended: another coordinator is currently active.",type:"error"}))};B();const E=window.setInterval(B,1e4),O=()=>{B()};return window.addEventListener("focus",O),()=>{clearInterval(E),window.removeEventListener("focus",O)}},[o,p]);const re=u.useCallback((B=!1,E=!1)=>{C(B);const O=cn();if(O&&Date.now()<O){h("locked_out"),k(Math.ceil((O-Date.now())/1e3)),z.current=!1,b(!1),g(null),q.current=!0,c(!0);return}if(E){z.current=!1,b(!1),g(null),h("idle"),q.current=!0,c(!0);return}In(p).then(ie=>{!ie.canAcquire&&ie.currentLock&&!ie.isSelfSession?(z.current=!0,b(!0),g(ie.currentLock),q.current=!1,c(!1)):(z.current=!1,b(!1),g(null),h("idle"),q.current=!0,c(!0))}).catch(()=>{z.current=!1,b(!1),g(null),h("idle"),q.current=!0,c(!0)})},[p]),le=u.useCallback(()=>{q.current=!1,c(!1);const B=cn();if(B&&Date.now()<B?h("locked_out"):h("idle"),S){const E=Wt();En(E)||(Tn(),bo(p),i(!1)),C(!1)}},[S,p]),M=u.useCallback(()=>{z.current=!1,b(!1),g(null)},[]),K=u.useCallback(async()=>{try{const B=await In(p);B.canAcquire||B.isSelfSession?re(!1,!0):B.currentLock&&(z.current=!0,b(!0),g(B.currentLock))}catch{}},[p,re]);u.useEffect(()=>Xc(E=>{E&&E.isLocked&&E.lockedBySessionId!==p?(o&&(i(!1),Tn()),q.current&&(q.current=!1,c(!1),z.current=!0,b(!0)),g(E)):(!E||!E.isLocked)&&z.current&&re(!1,!0)}),[o,p,re]);const Q=u.useCallback(B=>{(B==null?void 0:B.discard)===!0?Xo():tr(),j(!1),bo(p),Tn(),i(!1),q.current=!1,c(!1),P.current=!1,f(!1),C(!1),z.current=!1,b(!1),g(null),$(0);try{if(typeof window<"u"){const E=new URL(window.location.href);let O=!1;E.searchParams.has("dev")&&(E.searchParams.delete("dev"),O=!0),E.searchParams.has("mode")&&(E.searchParams.delete("mode"),O=!0),E.hash.includes("dev=true")&&(E.hash=E.hash.replace(/[?&]dev=true/,""),O=!0),O&&window.history.replaceState(null,"",E.toString())}}catch{}},[p]),X=u.useCallback(()=>{o&&(f(!0),P.current=!0)},[o]),ee=u.useCallback(()=>{f(!1),P.current=!1},[]),V=u.useCallback(B=>{ee(),Q(B)},[ee,Q]),J=u.useCallback(()=>{o?X():re(!1)},[o,X,re]),Y=u.useCallback(async B=>{if(cn()&&Date.now()<(cn()??0))return h("locked_out"),!1;h("verifying");try{const E=Oc(B,t,s),O=new Promise((ce,de)=>setTimeout(()=>de(new Error("PIN verification timed out.")),3e3));if(await Promise.race([E,O])){const ce=await xo(p);if(!ce.success&&ce.lock)return q.current=!1,c(!1),h("idle"),z.current=!0,b(!0),g(ce.lock),!1;const de=Date.now();Fc(de),vo(),po(),N(es),$(30),h("success");try{ta(!S)}catch(ae){return console.error("Draft initialization failed:",ae),H({message:"Draft Initialization Failed: Insufficient browser storage to create draft workspace.",type:"error"}),i(!1),!1}return i(!0),C(!1),z.current=!1,b(!1),g(null),setTimeout(()=>{q.current=!1,c(!1),h("idle")},400),!0}else{const ce=ea()+1;go(ce);const de=Math.max(0,es-ce);if(N(de),de===0){const ae=Date.now()+uo;fo(ae),k(60),h("locked_out")}else h("error");return!1}}catch(E){console.warn("[DeveloperMode] Verification error caught:",E);const O=ea()+1;go(O);const ie=Math.max(0,es-O);if(N(ie),ie===0){const ce=Date.now()+uo;fo(ce),k(60),h("locked_out")}else h("error");return!1}},[p]);u.useEffect(()=>{const B=E=>{const O=E.metaKey||E.ctrlKey,ie=E.shiftKey,ce=E.key==="D"||E.key==="d"||E.code==="KeyD";O&&ie&&ce&&(E.preventDefault(),J())};return window.addEventListener("keydown",B),()=>window.removeEventListener("keydown",B)},[J]),u.useEffect(()=>{try{const B=new URLSearchParams(window.location.search);if(B.get("dev")==="true"||B.get("mode")==="developer"){const O=Wt();En(O)?i(!0):re(!1),B.delete("dev"),B.get("mode")==="developer"&&B.delete("mode");const ie=B.toString(),ce=window.location.pathname+(ie?`?${ie}`:"")+window.location.hash;window.history.replaceState(null,"",ce)}}catch{}},[re]);const te=u.useCallback((B,E="success")=>{H({message:B,type:E})},[]),oe={isDevMode:o,isDesktop:r,isPinModalOpen:l,pinState:m,attemptsRemaining:T,lockoutRemainingSeconds:_,sessionRemainingMinutes:w,isRenewal:S,openPinModal:re,closePinModal:le,submitPin:Y,exitDevMode:Q,isExitConfirmOpen:d,requestExitDevMode:X,confirmExitDevMode:V,closeExitConfirmModal:ee,toggleDevMode:J,sessionId:p,isLockBlocked:v,activeLockInfo:y,closeLockBlockedModal:M,refreshLockStatus:K,hasUnpublishedChanges:I,setHasUnpublishedChanges:B=>{pn(B),j(B)},isCloudHydrating:F,cloudSyncStatus:W,showToast:te};return n.jsxs(Od.Provider,{value:oe,children:[e,D&&n.jsx(Ot,{message:D.message,type:D.type,onDismiss:()=>H(null)})]})},Ne=()=>{const e=u.useContext(Od);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:()=>{}}},vm="_siteHeader_ho30y_7",xm="_skipLink_ho30y_20",bm="_navCapsule_ho30y_42",ym="_brandGroup_ho30y_70",_m="_brandMeta_ho30y_108",wm="_brandTitle_ho30y_113",Sm="_navLinks_ho30y_123",Cm="_navLink_ho30y_123",km="_navAction_ho30y_185",Nm="_menuToggle_ho30y_225",jm="_menuIcon_ho30y_269",Tm="_menuLine_ho30y_279",Im="_menuLineTop_ho30y_290",Am="_menuLineBottom_ho30y_294",Em="_menuLineTopOpen_ho30y_299",$m="_menuLineBottomOpen_ho30y_303",Lm="_mobileDropdown_ho30y_311",Mm="_mobileNavLink_ho30y_349",Dm="_itemNumber_ho30y_364",Rm="_itemLabel_ho30y_372",Bm="_noCta_ho30y_422",De={siteHeader:vm,skipLink:xm,navCapsule:bm,brandGroup:ym,brandMeta:_m,brandTitle:wm,navLinks:Sm,navLink:Cm,navAction:km,menuToggle:Nm,menuIcon:jm,menuLine:Tm,menuLineTop:Im,menuLineBottom:Am,menuLineTopOpen:Em,menuLineBottomOpen:$m,mobileDropdown:Lm,mobileNavLink:Mm,itemNumber:Dm,itemLabel:Rm,noCta:Bm},Pm=[{label:"Roadmap",href:"#sequence-roadmap"},{label:"Overview",href:"#main-content"}],Ud=({brandTitle:e="Portal",brandLetter:t,navItems:s,mobileOnlyNav:r=!1,onRoadmapClick:a,onOverviewClick:o,onBrandClick:i})=>{const[l,c]=u.useState(!1),d=u.useRef(null),f=u.useRef([]),{openPinModal:m}=Ne(),h=y=>{y.preventDefault(),y.stopPropagation();const g=Date.now();f.current=[...f.current.filter(S=>g-S<3e3),g],f.current.length>=5&&(f.current=[],m(!1))},p=s!==void 0?s:Pm,x=()=>{c(y=>!y)},v=()=>{c(!1)},b=(y,g)=>{const S=y.label.toLowerCase();if(y.href==="#sequence-roadmap"||y.href==="#roadmap"||S==="roadmap"&&!y.href.startsWith("#node")){g.preventDefault(),c(!1),a==null||a(g);return}if(y.href==="#main-content"){g.preventDefault(),c(!1),o==null||o(g);return}if(y.href.startsWith("#")){g.preventDefault(),c(!1);const C=y.id||y.href.slice(1),T=document.getElementById(C);if(T){const k=T.getBoundingClientRect().top+window.pageYOffset-100;window.scrollTo({top:Math.max(0,k),behavior:"smooth"})}return}if(S==="overview"){g.preventDefault(),c(!1),o==null||o(g);return}};return u.useEffect(()=>{const y=g=>{g.key==="Escape"&&l&&c(!1)};return window.addEventListener("keydown",y),()=>window.removeEventListener("keydown",y)},[l]),u.useEffect(()=>{const y=g=>{d.current&&!d.current.contains(g.target)&&c(!1)};return l&&document.addEventListener("mousedown",y),()=>document.removeEventListener("mousedown",y)},[l]),n.jsxs("header",{ref:d,className:De.siteHeader,role:"banner",children:[n.jsx("a",{href:"#roadmap",className:De.skipLink,children:"Skip to content"}),n.jsxs("nav",{className:`${De.navCapsule} ${De.noCta}`,"aria-label":"Main Navigation",children:[n.jsxs("a",{href:"#",className:De.brandGroup,"aria-label":`${e} Home`,onClick:y=>{i&&(y.preventDefault(),i(y))},children:[n.jsx("span",{onClick:h,style:{display:"inline-flex"},title:"Brand Mark",children:n.jsx(pr,{size:"sm",letter:t})}),n.jsx("div",{className:De.brandMeta,children:n.jsx("span",{className:De.brandTitle,children:e})})]}),!r&&p.length>0&&n.jsx("ul",{className:De.navLinks,children:p.map(y=>n.jsx("li",{children:n.jsx("a",{href:y.href,className:De.navLink,onClick:g=>b(y,g),children:y.label})},y.label))}),p.length>0&&n.jsx("div",{className:`${De.navAction} ${r?De.navActionMobileOnly:""}`,children:n.jsx("button",{type:"button",className:De.menuToggle,onClick:x,"aria-label":l?"Close navigation menu":"Open navigation menu","aria-expanded":l,"aria-controls":"app-mobile-nav",children:n.jsxs("div",{className:De.menuIcon,"aria-hidden":"true",children:[n.jsx("span",{className:`${De.menuLine} ${De.menuLineTop} ${l?De.menuLineTopOpen:""}`}),n.jsx("span",{className:`${De.menuLine} ${De.menuLineBottom} ${l?De.menuLineBottomOpen:""}`})]})})}),l&&p.length>0&&n.jsx("div",{id:"app-mobile-nav",className:De.mobileDropdown,role:"menu","aria-label":"Mobile Navigation Menu",children:p.map(y=>n.jsxs("a",{href:y.href,className:De.mobileNavLink,role:"menuitem",onClick:g=>{v(),b(y,g)},children:[y.number&&n.jsx("span",{className:De.itemNumber,children:y.number}),n.jsx("span",{className:De.itemLabel,children:y.label})]},y.id||y.href||y.label))})]})]})},Om="_pill_1jlh1_6",Fm="_icon_1jlh1_36",Um="_label_1jlh1_43",Gm="_externalIcon_1jlh1_48",Hm="_sizeSm_1jlh1_56",zm="_sizeMd_1jlh1_64",qm="_white_1jlh1_75",Vm="_blue_1jlh1_90",Wm="_primary_1jlh1_97",Km="_accent_1jlh1_104",Ym="_green_1jlh1_111",Xm="_amber_1jlh1_118",Jm="_neutral_1jlh1_125",Zm="_mono_1jlh1_134",Qm="_link_1jlh1_146",ef="_interactive_1jlh1_173",Cn={pill:Om,icon:Fm,label:Um,externalIcon:Gm,sizeSm:Hm,sizeMd:zm,white:qm,blue:Vm,primary:Wm,accent:Km,green:Ym,amber:Xm,neutral:Jm,mono:Zm,link:Qm,interactive:ef},or=({label:e,variant:t="neutral",size:s,icon:r,pulse:a=!1,href:o,target:i,rel:l,type:c="button",onClick:d,className:f="",ariaLabel:m,title:h,showExternalIcon:p=t==="link"})=>{const x=n.jsxs(n.Fragment,{children:[r&&n.jsx("span",{className:Cn.icon,"aria-hidden":"true",children:r}),n.jsx("span",{className:Cn.label,children:e}),p&&n.jsx("span",{className:Cn.externalIcon,"aria-hidden":"true",children:"↗"})]}),v=s==="sm"?Cn.sizeSm:s==="md"?Cn.sizeMd:"",b=`${Cn.pill} ${Cn[t]} ${v} ${f}`.trim();return o?n.jsx("a",{href:o,target:i||(t==="link"?"_blank":void 0),rel:l||(t==="link"?"noopener noreferrer":void 0),className:b,onClick:d,"aria-label":m,title:h,children:x}):d||t==="interactive"?n.jsx("button",{type:c,className:b,onClick:d,"aria-label":m,title:h,children:x}):n.jsx("span",{className:b,role:"status","aria-label":m,title:h,children:x})},tf="_btn_cfm1h_11",nf="_btnContent_cfm1h_37",sf="_sizeXs_cfm1h_51",rf="_sizeSm_cfm1h_61",af="_sizeMd_cfm1h_71",of="_sizeLg_cfm1h_81",lf="_variantRevolvingOutline_cfm1h_94",cf="_revolvingStopped_cfm1h_161",df="_variantPrimary_cfm1h_206",uf="_variantSecondary_cfm1h_225",hf="_variantGhost_cfm1h_245",mf="_variantAdmin_cfm1h_262",ff="_pulse_cfm1h_324",rt={btn:tf,btnContent:nf,sizeXs:sf,sizeSm:rf,sizeMd:af,sizeLg:of,variantRevolvingOutline:lf,revolvingStopped:cf,variantPrimary:df,variantSecondary:uf,variantGhost:hf,variantAdmin:mf,pulse:ff},pf={"revolving-outline":rt.variantRevolvingOutline,primary:rt.variantPrimary,secondary:rt.variantSecondary,ghost:rt.variantGhost,admin:rt.variantAdmin},gf={xs:rt.sizeXs,sm:rt.sizeSm,md:rt.sizeMd,lg:rt.sizeLg},he=({variant:e="revolving-outline",size:t="md",outlineWidth:s,revolving:r=!0,pulse:a=!1,as:o,href:i,type:l="button",onClick:c,onMouseEnter:d,onMouseLeave:f,className:m,style:h,children:p,"aria-label":x,title:v,disabled:b=!1,target:y,rel:g,id:S,tabIndex:C,"aria-hidden":T,ref:N,..._})=>{const k=o==="a"||i!==void 0&&o!=="button",w=pf[e]||rt.variantRevolvingOutline,$=gf[t]||rt.sizeMd,I=e==="revolving-outline"&&!r?rt.revolvingStopped:"",j=a?rt.pulse:"",D=`${rt.btn} ${w} ${$} ${I} ${j} ${m||""}`.trim(),H={...h,...s!==void 0?{"--outline-width":typeof s=="number"?`${s}px`:s}:{}},L=e==="revolving-outline"?String(r):void 0;return k?n.jsx("a",{id:S,href:i,onClick:c,onMouseEnter:d,onMouseLeave:f,className:D,style:H,title:v,"aria-label":x,"aria-disabled":b?"true":void 0,target:y,rel:g,tabIndex:C,"aria-hidden":T,"data-revolving":L,"data-pulse":a?"true":void 0,..._,children:n.jsx("span",{className:rt.btnContent,children:p})}):n.jsx("button",{ref:N,id:S,type:l,onClick:c,onMouseEnter:d,onMouseLeave:f,className:D,style:H,title:v,"aria-label":x,disabled:b,tabIndex:C,"aria-hidden":T,"data-revolving":L,"data-pulse":a?"true":void 0,"data-variant":e,"data-primary":e==="primary"||e==="admin"?"true":void 0,..._,children:n.jsx("span",{className:rt.btnContent,children:p})})};let nr=0,Gd="",Hd="",zd="",qd="";function ci(){if(!(typeof document>"u")){if(nr===0){Gd=document.body.style.overflow,Hd=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&&(qd=t.style.pointerEvents,t.style.pointerEvents="none",t.setAttribute("inert",""),t.setAttribute("aria-hidden","true"))}nr++}}function di(){if(!(typeof document>"u")&&(nr=Math.max(0,nr-1),nr===0)){document.body.style.overflow=Gd,document.documentElement.style.overflow=Hd,document.body.style.paddingRight=zd;const e=document.getElementById("root");e&&(e.style.pointerEvents=qd,e.removeAttribute("inert"),e.removeAttribute("aria-hidden"))}}const Bn=[];function ui(e){e&&(Bn.includes(e)||Bn.push(e))}function hi(e){if(!e)return;const t=Bn.indexOf(e);t!==-1&&Bn.splice(t,1)}function mi(e){return e?Bn.length===0?!0:Bn[Bn.length-1]===e:!1}function fi(e){return e.key==="Enter"&&(e.ctrlKey||e.metaKey)}const vf=/\b(save|submit|publish|confirm|approve|next|done|add|create|continue|apply|deploy|verify|restore|exit|delete|proceed|ok|yes)\b/i,Vd=/\b(cancel|close|discard|dismiss|reset|back|keep editing|cancel & exit|no)\b/i;function $n(e){var s;if(!e||"disabled"in e&&e.disabled||e.getAttribute("aria-disabled")==="true"||e.getAttribute("aria-hidden")==="true")return!1;if(typeof window<"u"){const r=window.getComputedStyle(e);if(r.display==="none"||r.visibility==="hidden")return!1}const t=(e.textContent||e.getAttribute("aria-label")||"").trim();return!(t==="✕"||t==="×"||Vd.test(t)||(s=e.getAttribute("aria-label"))!=null&&s.toLowerCase().includes("close"))}function pi(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($n);if(t.length>0)return t[0];const s=Array.from(e.querySelectorAll('button[type="submit"], input[type="submit"]')).filter($n);if(s.length>0)return s[0];const r=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($n);if(r.length>0)return r[0];const o=Array.from(e.querySelectorAll("button")).filter($n).filter(l=>{const c=(l.textContent||l.getAttribute("aria-label")||"").trim();return vf.test(c)&&!Vd.test(c)});if(o.length>0)return o[0];const i=e.querySelector("form");return i||null}function gi(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&&$n(t)?(t.click(),!0):(e.dispatchEvent(new Event("submit",{cancelable:!0,bubbles:!0})),!0)}return $n(e)?(e.click(),!0):!1}const xf="_backdrop_1safl_8",bf="_modalCard_1safl_27",yf="_header_1safl_44",_f="_title_1safl_51",wf="_closeButton_1safl_61",Sf="_absoluteCloseButton_1safl_90",Yn={backdrop:xf,modalCard:bf,header:yf,title:_f,closeButton:wf,absoluteCloseButton:Sf},ut=({isOpen:e,onClose:t,title:s,children:r,maxWidth:a,className:o,cardClassName:i,ariaLabel:l,ariaLabelledBy:c,ariaDescribedBy:d,showCloseButton:f=!0,role:m="dialog",closeOnOutsideClick:h=!1,closeOnBackdropClick:p=!1,closeOnEscape:x=!0,onConfirm:v,enableCtrlEnter:b=!0,initialFocusRef:y})=>{const[g,S]=u.useState(!1),C=u.useRef(null),T=u.useRef(null);if(u.useEffect(()=>{S(!0)},[]),u.useEffect(()=>{if(e)return ci(),()=>{di()}},[e]),u.useEffect(()=>{if(!e)return;const w=C.current;return w&&ui(w),()=>{w&&hi(w)}},[e]),u.useEffect(()=>{if(!e)return;T.current=document.activeElement;const w=window.setTimeout(()=>{if(!C.current)return;if(y!=null&&y.current){y.current.focus();return}const I=C.current.querySelector("[data-autofocus], [autofocus]");if(I){I.focus();return}const j=C.current.querySelector('input:not([disabled]):not([type="hidden"]), textarea:not([disabled]), select:not([disabled])');if(j){j.focus();return}const D=C.current.querySelectorAll('button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])');D.length>0?D[0].focus():C.current.focus()},25),$=I=>{const j=C.current&&(C.current.contains(document.activeElement)||mi(C.current));if(x&&I.key==="Escape"&&j){I.preventDefault(),t();return}if(b&&fi(I)&&j){if(I.preventDefault(),I.stopPropagation(),v){v();return}if(C.current){const D=pi(C.current);D&&gi(D)}return}if(I.key==="Tab"&&C.current){const D=Array.from(C.current.querySelectorAll('button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])'));if(D.length===0){I.preventDefault();return}const H=D[0],L=D[D.length-1];I.shiftKey?(document.activeElement===H||!C.current.contains(document.activeElement))&&(I.preventDefault(),L.focus()):(document.activeElement===L||!C.current.contains(document.activeElement))&&(I.preventDefault(),H.focus())}};return window.addEventListener("keydown",$),()=>{var I;window.clearTimeout(w),window.removeEventListener("keydown",$),(I=T.current)==null||I.focus()}},[e,t,x,b,v,y]),!g||!e)return null;const N=h||p,_=w=>{w.stopPropagation(),w.target===w.currentTarget&&N&&t()},k=n.jsx("div",{className:`${Yn.backdrop} ${o||""}`,onClick:_,onMouseDown:w=>w.stopPropagation(),onTouchStart:w=>w.stopPropagation(),role:"presentation",children:n.jsxs("div",{ref:C,tabIndex:-1,className:`${Yn.modalCard} ${i||""}`,style:a?{maxWidth:typeof a=="number"?`${a}px`:a}:void 0,role:m,"aria-modal":"true","aria-label":l,"aria-labelledby":c,"aria-describedby":d,children:[s?n.jsxs("div",{className:Yn.header,children:[n.jsx("h2",{id:c,className:Yn.title,children:s}),f&&n.jsx("button",{type:"button",className:Yn.closeButton,onClick:t,"aria-label":"Close dialog",children:"✕"})]}):f?n.jsx("button",{type:"button",className:Yn.absoluteCloseButton,onClick:t,"aria-label":"Close dialog",children:"✕"}):null,r]})});return fr.createPortal(k,document.body)},Cf="_trigger_11pzf_1",kf="_icon_11pzf_26",Nf="_bubble_11pzf_32",Xa={trigger:Cf,icon:kf,bubble:Nf},jf=({className:e})=>n.jsxs("svg",{className:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[n.jsx("circle",{cx:"12",cy:"12",r:"10"}),n.jsx("line",{x1:"12",y1:"16",x2:"12",y2:"12"}),n.jsx("line",{x1:"12",y1:"8",x2:"12.01",y2:"8"})]}),Pn=u.memo(({text:e,label:t,className:s})=>{const{isDevMode:r}=Ne(),[a,o]=u.useState(!1),[i,l]=u.useState(null),c=u.useRef(null),d=u.useRef(null),f=u.useRef(null),m=u.useId();u.useEffect(()=>()=>{f.current&&clearTimeout(f.current)},[]);const h=u.useCallback(()=>{if(!c.current)return;const g=c.current.getBoundingClientRect(),S=d.current,C=S?S.offsetWidth:220,T=S?S.offsetHeight:44;let N=g.left+g.width/2-C/2;N=Math.max(12,Math.min(N,window.innerWidth-C-12));let _=g.top-T-6;_<12&&(_=g.bottom+6),l({top:_,left:N})},[]);if(u.useEffect(()=>{if(a){h();const g=requestAnimationFrame(h);return()=>cancelAnimationFrame(g)}else l(null)},[a,h]),u.useEffect(()=>{if(!a)return;const g=S=>{S.key==="Escape"&&o(!1)};return window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)},[a]),!r)return null;const p=()=>{f.current&&clearTimeout(f.current),f.current=setTimeout(()=>{o(!0)},150)},x=()=>{f.current&&clearTimeout(f.current),o(!1)},v=()=>{o(!0)},b=()=>{o(!1)},y=g=>{g.preventDefault(),g.stopPropagation()};return n.jsxs(n.Fragment,{children:[n.jsx("span",{ref:c,role:"button",tabIndex:0,className:`${Xa.trigger} ${s||""}`,"aria-label":t?`Help for ${t}`:"Help info","aria-describedby":a?m:void 0,onMouseEnter:p,onMouseLeave:x,onFocus:v,onBlur:b,onClick:y,onMouseDown:y,onKeyDown:g=>{(g.key===" "||g.key==="Enter")&&(g.preventDefault(),g.stopPropagation())},children:n.jsx(jf,{className:Xa.icon})}),a&&fr.createPortal(n.jsx("div",{id:m,ref:d,role:"tooltip",className:Xa.bubble,style:{top:i?`${i.top}px`:"-9999px",left:i?`${i.left}px`:"-9999px"},children:e}),document.body)]})});Pn.displayName="DevHelpTooltip";const ra=50;class Wd{constructor(){qr(this,"undoStack",[]);qr(this,"redoStack",[]);qr(this,"executingLock",!1)}push(t){if(this.executingLock)return null;const s={...t,id:`undo_${Date.now()}_${Math.random().toString(36).substring(2,7)}`,timestamp:Date.now()};return this.undoStack.push(s),this.undoStack.length>ra&&this.undoStack.shift(),this.redoStack=[],s}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],s=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:s==null?void 0:s.description}}isExecuting(){return this.executingLock}getStacks(){return{undo:[...this.undoStack],redo:[...this.redoStack]}}}function Kd(e){var r;if(!e||typeof HTMLElement<"u"&&!(e instanceof HTMLElement))return!1;const t=e,s=(r=t.tagName)==null?void 0:r.toUpperCase();if(s==="INPUT"){const a=(t.type||"text").toLowerCase();return!["button","submit","reset","checkbox","radio","range","color","file"].includes(a)}return!!(s==="TEXTAREA"||t.isContentEditable||typeof t.getAttribute=="function"&&t.getAttribute("role")==="textbox")}const zt=new Wd,vi=u.createContext(null),Yd=({children:e})=>{const[t,s]=u.useState(()=>zt.getState()),[,r]=u.useTransition(),a=u.useCallback(()=>{s(zt.getState())},[]),o=u.useCallback(f=>{zt.push(f)&&a()},[a]),i=u.useCallback(()=>{r(()=>{zt.popUndo()&&a()})},[a]),l=u.useCallback(()=>{r(()=>{zt.popRedo()&&a()})},[a]),c=u.useCallback(()=>{zt.clear(),a()},[a]);u.useEffect(()=>{const f=m=>{if(Kd(m.target))return;const h=typeof navigator<"u"&&/Mac|iPod|iPhone|iPad/.test(navigator.platform);if(!(h?m.metaKey:m.ctrlKey))return;const x=m.key.toLowerCase();if(x==="z"&&!m.shiftKey){zt.getState().canUndo&&(m.preventDefault(),i());return}(x==="z"&&m.shiftKey||!h&&x==="y"&&!m.shiftKey)&&zt.getState().canRedo&&(m.preventDefault(),l())};return window.addEventListener("keydown",f),()=>{window.removeEventListener("keydown",f)}},[i,l]);const d={...t,pushAction:o,undo:i,redo:l,clearHistory:c};return n.jsx(vi.Provider,{value:d,children:e})};function Ir(){const e=u.useContext(vi);return e||{canUndo:!1,canRedo:!1,undoCount:0,redoCount:0,pushAction:()=>{},undo:()=>{},redo:()=>{},clearHistory:()=>{}}}function Fa(e,t){u.useEffect(()=>{if(Bd(t,e),!e)return()=>{No(t)};const s=r=>{li(r)};return window.addEventListener("beforeunload",s),()=>{No(t),window.removeEventListener("beforeunload",s)}},[e,t])}const jo="engine-media",Xd=1600,Jd=.82;function Zd(e){const t=e.split("."),s=(t.pop()||"png").toLowerCase().trim();return`${t.join(".").replace(/[^a-zA-Z0-9_-]/g,"_").replace(/_+/g,"_").slice(0,40)||"asset"}.${s}`}async function Qd(e,t){if(typeof window>"u"||typeof document>"u")return e;const s=e.type||"image/jpeg";if(!s.startsWith("image/")||s.includes("svg"))return e;const r=(t==null?void 0:t.maxDimension)||Xd,a=(t==null?void 0:t.quality)||Jd,o=(t==null?void 0:t.mimeType)||(s==="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:f}=l;(d>r||f>r)&&(d>f?(f=Math.round(f*r/d),d=r):(d=Math.round(d*r/f),f=r));const m=document.createElement("canvas");m.width=d,m.height=f;const h=m.getContext("2d");if(!h){i(e);return}h.imageSmoothingEnabled=!0,h.imageSmoothingQuality="high",h.drawImage(l,0,0,d,f),m.toBlob(p=>{p&&p.size<e.size?i(p):i(e)},o,a)},l.onerror=()=>{URL.revokeObjectURL(c),i(e)},l.src=c})}async function ha(e,t="photos",s){const r=qe();if(!r)throw new Error("Supabase configuration missing");const a=s||(e instanceof File?e.name:`asset-${Date.now()}.png`),o=Zd(a),i=`${t}/${Date.now()}-${o}`,l=await Qd(e),c=r.anonKey,d=`${r.url}/storage/v1/object/${jo}/${i}`,f=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(!f.ok){const m=await f.text();let h=m;try{const p=JSON.parse(m);p.message&&(p.message.includes("row-level security")||p.code==="AccessDenied"?h="Storage permission denied (RLS policy missing). Apply migration 20261021160000_create_engine_media_storage_and_drafts.sql in Supabase SQL Editor.":h=p.message)}catch{}throw new Error(`Media upload failed (${f.status}): ${h}`)}return`${r.url}/storage/v1/object/public/${jo}/${i}`}const Tf="_container_10l68_10",If="_panel_10l68_17",Af="_formField_10l68_23",Ef="_fieldLabel_10l68_29",$f="_requiredMark_10l68_38",Lf="_input_10l68_43",Mf="_textarea_10l68_70",Df="_checkboxLabel_10l68_99",Rf="_checkbox_10l68_99",Bf="_segmentedControl_10l68_153",Pf="_segmentButton_10l68_161",Of="_segmentButtonActive_10l68_182",Ff="_imagePreviewWrapper_10l68_189",Uf="_previewThumb_10l68_200",Gf="_fileRow_10l68_207",Hf="_fileStatus_10l68_213",zf="_hiddenFileInput_10l68_219",qf="_formatPills_10l68_223",Vf="_formatPill_10l68_223",Wf="_actions_10l68_255",Kf="_actionGroupRight_10l68_263",Z={container:Tf,panel:If,formField:Af,fieldLabel:Ef,requiredMark:$f,input:Lf,textarea:Mf,checkboxLabel:Df,checkbox:Rf,segmentedControl:Bf,segmentButton:Pf,segmentButtonActive:Of,imagePreviewWrapper:Ff,previewThumb:Uf,fileRow:Gf,fileStatus:Hf,hiddenFileInput:zf,formatPills:qf,formatPill:Vf,actions:Wf,actionGroupRight:Kf},Yf=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 Xe(e){if(!e)return"";const t=e.trim();return Yf.has(t)?"":e}function Ja(e){let t="",s={url:"",label:"",openInNewTab:!1},r={src:"",alt:"",caption:"",showCaption:!1},a={name:"",url:"",reference:"",format:"pdf",size:""};if(!e)return{text:t,link:s,image:r,file:a};if(typeof e=="object"){if("src"in e){const o=e,i=!o.src||o.src.trim().length===0;r={src:o.src||"",alt:i?"":Xe(o.alt),caption:i?"":Xe(o.caption),showCaption:i?!1:!!o.showCaption},t=i?"":r.caption||r.alt||r.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;s={url:o.url||"",label:i?"":Xe(o.label),openInNewTab:i?!1:!!o.openInNewTab},t=i?"":s.label||s.url}return{text:t,link:s,image:r,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;r={src:i.src||"",alt:c?"":Xe(i.alt),caption:c?"":Xe(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;s={url:i.url||"",label:c?"":Xe(i.label),openInNewTab:c?!1:!!i.openInNewTab}}const l=typeof i.text=="string"?i.text:o;return t=Xe(l),{text:t,link:s,image:r,file:a}}catch{}t=Xe(o),s.url=/^(https?:\/\/|#|\/)/i.test(o)?o:"",r.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:s,image:r,file:a}}function Zl(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 An=({isOpen:e,onClose:t,mode:s="edit",elementType:r=null,initialData:a,onSubmit:o,onResetToDefault:i,pointId:l,type:c="text",currentValue:d,defaultValue:f,title:m,isSection:h,isNumbered:p,defaultNumbered:x,onNumberedChange:v,onSave:b,onReset:y})=>{const{isDevMode:g,isDesktop:S,setHasUnpublishedChanges:C,showToast:T}=Ne(),{pushAction:N}=Ir(),_=!!(r||o),[k,w]=u.useState(()=>a?{title:a.title||"",isNumbered:a.isNumbered!==!1,content:Xe(a.content),as:a.as||"p",src:a.src||"",alt:Xe(a.alt),caption:Xe(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:""}),[$,I]=u.useState(""),[j,D]=u.useState({url:"",label:"",openInNewTab:!1}),[H,L]=u.useState({src:"",alt:"",caption:"",showCaption:!1}),[U,G]=u.useState({name:"",url:"",reference:"",format:"pdf",size:""}),z=!!(h||r==="section"||l&&/(^|\.)section(\.|$)/i.test(l)&&!l.endsWith(".subtitle")),q=l?`${l}.isNumbered`:"",[P,F]=u.useState(!0),[R,W]=u.useState("upload"),[se,re]=u.useState(!1),[le,M]=u.useState(null),K=u.useRef(null),Q=u.useRef(null),X=u.useRef(null);u.useEffect(()=>{e&&(!g||!S)&&t()},[e,g,S,t]),u.useEffect(()=>{if(!e)return;if(_){const O={title:(a==null?void 0:a.title)||"",isNumbered:(a==null?void 0:a.isNumbered)!==!1,content:Xe(a==null?void 0:a.content),as:(a==null?void 0:a.as)||"p",src:(a==null?void 0:a.src)||"",alt:Xe(a==null?void 0:a.alt),caption:Xe(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(O);const ie=!!(O.src&&!O.src.startsWith("data:"));W(ie?"url":"upload")}else{const O=Ja(d);I(O.text),D(O.link),L(O.image),G(O.file);const ie=!!(O.image.src&&!O.image.src.startsWith("data:"));if(W(ie?"url":"upload"),z&&q){const ce=hn(q,"",g);F(ce!==""?ce==="true":p!==void 0?p:x!==void 0?x:!0)}}const E=setTimeout(()=>{var O;(O=X.current)==null||O.focus()},50);return()=>clearTimeout(E)},[e,_,a,d,z,q,p,x,g]);const ee=u.useMemo(()=>{if(!e)return!1;if(_){const E=(a==null?void 0:a.title)||"",O=Xe(a==null?void 0:a.content),ie=(a==null?void 0:a.src)||"",ce=Xe(a==null?void 0:a.alt),de=Xe(a==null?void 0:a.caption),ae=(a==null?void 0:a.driveUrl)||"",fe=(a==null?void 0:a.isNumbered)!==!1;return(k.title||"")!==E||(k.content||"")!==O||(k.src||"")!==ie||(k.alt||"")!==ce||(k.caption||"")!==de||(k.driveUrl||"")!==ae||k.isNumbered!==fe}else{const E=Ja(d);return $!==E.text||j.url!==E.link.url||j.label!==E.link.label||H.src!==E.image.src||H.alt!==E.image.alt||H.caption!==E.image.caption||U.url!==E.file.url||U.name!==E.file.name}},[e,_,k,a,$,j,H,U,d]);Fa(e&&ee,l?`universal-edit-${l}`:"universal-edit-modal");const V=u.useCallback(async E=>{var ce;const O=(ce=E.target.files)==null?void 0:ce[0];if(!O)return;const ie=O.name.replace(/\.[^/.]+$/,"");re(!0),M(null);try{const de=await ha(O,"photos");_?w(ae=>({...ae,src:de,alt:ae.alt||ie})):L(ae=>({...ae,src:de,alt:ae.alt||ie}))}catch(de){console.error("[UniversalEditModal] Photo upload failed:",de),M(de instanceof Error?de.message:"Photo upload failed")}finally{re(!1)}},[_]),J=u.useCallback(async E=>{var de,ae;const O=(de=E.target.files)==null?void 0:de[0];if(!O)return;const ie=(ae=O.name.split(".").pop())==null?void 0:ae.toLowerCase();let ce="other";ie==="pdf"?ce="pdf":ie==="doc"||ie==="docx"?ce="doc":(ie==="xls"||ie==="xlsx"||ie==="csv")&&(ce="sheet"),re(!0),M(null);try{const fe=await ha(O,"documents");G(be=>({...be,name:O.name,url:fe,format:ce,size:`${(O.size/1024).toFixed(1)} KB`}))}catch(fe){console.error("[UniversalEditModal] Document upload failed:",fe),M(fe instanceof Error?fe.message:"Document upload failed")}finally{re(!1)}},[]),Y=()=>{if(_&&o){o(k),C(!0),T(s==="add"?"Element added to canvas.":"Changes saved to draft successfully.","success"),t();return}let E="",O;switch(c){case"text":E=$;break;case"link":E=JSON.stringify(j),O=j;break;case"image":E=JSON.stringify(H),O=H;break;case"file":E=JSON.stringify(U),O=U;break}if(z&&q&&(Kt(q,String(P),!0),v==null||v(P)),l){const ie=hn(l,typeof f=="string"?f:f?JSON.stringify(f):"",!0);ie!==E&&N({type:"content_text_override",description:`Edit text for ${l}`,undo:()=>{Kt(l,ie,!0)},redo:()=>{Kt(l,E,!0)}}),Kt(l,E,!0)}b&&b(E,c,O),C(!0),T("Changes saved to draft successfully.","success"),t()},te=()=>{if(_){i&&i(),C(!0),T("Reset to default baseline.","info"),t();return}if(l){const O=hn(l,"",!0),ie=typeof f=="string"?f:f?JSON.stringify(f):"";hs(l,!0),O&&O!==ie&&N({type:"content_text_override",description:`Reset text for ${l}`,undo:()=>{Kt(l,O,!0)},redo:()=>{hs(l,!0)}})}if(z&&q){hs(q,!0);const O=x!==void 0?x:!0;F(O),v==null||v(O)}y&&y();const E=Ja(f);I(E.text),D(E.link),L(E.image),G(E.file),C(!0),T("Reset to default baseline.","info"),t()},oe=u.useMemo(()=>{if(m)return m;if(_&&r){const E=Zl(r);return s==="add"?`Add ${E}`:`Edit ${E}`}return z?"Edit Section":c==="image"?"Edit Photo":c==="link"?"Edit Link":c==="file"?"Edit Document":"Edit Text"},[m,_,r,s,z,c]),B=u.useMemo(()=>_&&s==="add"?`Add ${Zl(r)}`:"Save Changes",[_,s,r]);return n.jsx(ut,{isOpen:e,onClose:t,onConfirm:se?void 0:Y,title:oe,maxWidth:"500px",ariaLabel:oe,children:n.jsxs("div",{className:Z.container,children:[_&&r==="section"&&n.jsxs("div",{className:Z.panel,children:[n.jsxs("div",{className:Z.formField,children:[n.jsxs("label",{className:Z.fieldLabel,htmlFor:"edit-modal-section-title",children:["Section Title ",n.jsx("span",{className:Z.requiredMark,children:"*"})]}),n.jsx("input",{id:"edit-modal-section-title",ref:E=>{X.current=E},type:"text",className:Z.input,value:k.title||"",onChange:E=>w(O=>({...O,title:E.target.value})),placeholder:"e.g. Strategic Academic Intervention","aria-label":"Section Title"})]}),n.jsx("div",{className:Z.formField,children:n.jsxs("label",{className:Z.checkboxLabel,children:[n.jsx("input",{type:"checkbox",className:Z.checkbox,checked:k.isNumbered!==!1,onChange:E=>w(O=>({...O,isNumbered:E.target.checked}))}),n.jsxs("span",{children:["Numbered section",n.jsx(Pn,{text:"Adds a number before the title, like I or II.",label:"Numbered section"})]})]})})]}),_&&r==="subsection"&&n.jsx("div",{className:Z.panel,children:n.jsxs("div",{className:Z.formField,children:[n.jsxs("label",{className:Z.fieldLabel,htmlFor:"canvas-subsection-title",children:["Subsection Title ",n.jsx("span",{className:Z.requiredMark,children:"*"})]}),n.jsx("input",{id:"canvas-subsection-title",ref:E=>{X.current=E},type:"text",className:Z.input,value:k.title||"",onChange:E=>w(O=>({...O,title:E.target.value})),placeholder:"e.g. Implementation Milestones","aria-label":"Subsection Title"})]})}),_&&r==="text"&&n.jsxs("div",{className:Z.panel,children:[n.jsxs("div",{className:Z.formField,children:[n.jsx("label",{className:Z.fieldLabel,children:"Typography Style"}),n.jsxs("div",{className:Z.segmentedControl,role:"radiogroup","aria-label":"Typography Style",children:[n.jsx("button",{type:"button",role:"radio","aria-checked":k.as!=="blockquote",className:`${Z.segmentButton} ${k.as!=="blockquote"?Z.segmentButtonActive:""}`,onClick:()=>w(E=>({...E,as:"p"})),children:"Paragraph"}),n.jsx("button",{type:"button",role:"radio","aria-checked":k.as==="blockquote",className:`${Z.segmentButton} ${k.as==="blockquote"?Z.segmentButtonActive:""}`,onClick:()=>w(E=>({...E,as:"blockquote"})),children:"Quote / Callout"})]})]}),n.jsxs("div",{className:Z.formField,children:[n.jsxs("label",{className:Z.fieldLabel,htmlFor:"canvas-text-content",children:["Narrative Text",n.jsx("span",{className:Z.requiredMark,children:"*"})]}),n.jsx("textarea",{id:"canvas-text-content",ref:E=>{X.current=E},className:Z.textarea,value:k.content||"",onChange:E=>w(O=>({...O,content:E.target.value})),placeholder:"Enter narrative text or editorial testimony...",rows:5,"aria-label":"Narrative Text Content"})]})]}),_&&r==="photo"&&n.jsxs("div",{className:Z.panel,children:[n.jsxs("div",{className:Z.formField,children:[n.jsx("label",{className:Z.fieldLabel,children:"Photo Source"}),n.jsxs("div",{className:Z.segmentedControl,role:"radiogroup","aria-label":"Photo Source",children:[n.jsx("button",{type:"button",role:"radio","aria-checked":R==="upload",className:`${Z.segmentButton} ${R==="upload"?Z.segmentButtonActive:""}`,onClick:()=>W("upload"),children:"Upload Photo"}),n.jsx("button",{type:"button",role:"radio","aria-checked":R==="url",className:`${Z.segmentButton} ${R==="url"?Z.segmentButtonActive:""}`,onClick:()=>W("url"),children:"Photo URL"})]})]}),R==="upload"?n.jsxs("div",{className:Z.fileRow,children:[n.jsx(he,{type:"button",variant:"secondary",size:"sm",onClick:()=>{var E;return(E=K.current)==null?void 0:E.click()},children:"Upload Photo"}),n.jsx("input",{ref:K,type:"file",accept:"image/png,image/jpeg,image/webp,image/gif",className:Z.hiddenFileInput,onChange:V,"aria-label":"Upload photo file"}),n.jsx("span",{className:Z.fileStatus,children:k.src?"Photo selected":"No photo chosen"})]}):n.jsxs("div",{className:Z.formField,children:[n.jsxs("label",{className:Z.fieldLabel,htmlFor:"canvas-photo-url",children:["Photo URL ",n.jsx("span",{className:Z.requiredMark,children:"*"})]}),n.jsx("input",{id:"canvas-photo-url",ref:E=>{X.current=E},type:"text",className:Z.input,value:k.src||"",onChange:E=>w(O=>({...O,src:E.target.value})),placeholder:"https://.../photo.webp","aria-label":"Photo URL"})]}),k.src?n.jsx("div",{className:Z.imagePreviewWrapper,children:n.jsx("img",{src:k.src,alt:k.alt||"Preview",className:Z.previewThumb})}):null,n.jsxs("div",{className:Z.formField,children:[n.jsx("label",{className:Z.fieldLabel,htmlFor:"canvas-photo-alt",children:"Alt Text (Accessibility)"}),n.jsx("input",{id:"canvas-photo-alt",type:"text",className:Z.input,value:k.alt||"",onChange:E=>w(O=>({...O,alt:E.target.value})),placeholder:"Descriptive image summary for screen readers","aria-label":"Photo Alt Text"})]}),n.jsx("div",{className:Z.formField,children:n.jsxs("label",{className:Z.checkboxLabel,children:[n.jsx("input",{type:"checkbox",className:Z.checkbox,checked:!!k.showCaption,onChange:E=>w(O=>({...O,showCaption:E.target.checked}))}),n.jsx("span",{children:"Show caption below photo"})]})}),k.showCaption?n.jsxs("div",{className:Z.formField,children:[n.jsx("label",{className:Z.fieldLabel,htmlFor:"canvas-photo-caption",children:"Caption"}),n.jsx("input",{id:"canvas-photo-caption",type:"text",className:Z.input,value:k.caption||"",onChange:E=>w(O=>({...O,caption:E.target.value})),placeholder:"Photo caption or description","aria-label":"Photo Caption"})]}):null]}),_&&r==="gallery"&&n.jsxs("div",{className:Z.panel,children:[n.jsxs("div",{className:Z.formField,children:[n.jsxs("label",{className:Z.fieldLabel,htmlFor:"canvas-gallery-title",children:["Gallery Title ",n.jsx("span",{className:Z.requiredMark,children:"*"})]}),n.jsx("input",{id:"canvas-gallery-title",ref:E=>{X.current=E},type:"text",className:Z.input,value:k.title||"",onChange:E=>w(O=>({...O,title:E.target.value})),placeholder:"e.g. Mid-Year Assessment & Verification","aria-label":"Gallery Title"})]}),n.jsxs("div",{className:Z.formField,children:[n.jsxs("label",{className:Z.fieldLabel,htmlFor:"canvas-gallery-drive",children:["Google Drive Repository URL ",n.jsx("span",{className:Z.requiredMark,children:"*"}),n.jsx(Pn,{text:"A link to an online folder with more photos or files.",label:"Folder Link"})]}),n.jsx("input",{id:"canvas-gallery-drive",type:"text",className:Z.input,value:k.driveUrl||"",onChange:E=>w(O=>({...O,driveUrl:E.target.value})),placeholder:"https://drive.google.com/drive/folders/...","aria-label":"Google Drive URL"})]})]}),!_&&c==="text"&&n.jsx("div",{className:Z.panel,children:z?n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:Z.formField,children:[n.jsxs("label",{className:Z.fieldLabel,htmlFor:"edit-modal-section-title",children:["Section Title",n.jsx("span",{className:Z.requiredMark,children:"*"})]}),n.jsx("input",{id:"edit-modal-section-title",ref:E=>{X.current=E},type:"text",className:Z.input,value:$,onChange:E=>I(E.target.value),placeholder:"e.g. Strategic Academic Intervention","aria-label":"Section Title"})]}),n.jsx("div",{className:Z.formField,children:n.jsxs("label",{className:Z.checkboxLabel,children:[n.jsx("input",{type:"checkbox",className:Z.checkbox,checked:P,onChange:E=>F(E.target.checked)}),n.jsxs("span",{children:["Numbered section",n.jsx(Pn,{text:"Adds a number before the title, like I or II.",label:"Numbered section"})]})]})})]}):n.jsxs("div",{className:Z.formField,children:[n.jsxs("label",{className:Z.fieldLabel,htmlFor:"dev-modal-generic-text",children:["Content",n.jsx("span",{className:Z.requiredMark,children:"*"})]}),n.jsx("textarea",{id:"dev-modal-generic-text",ref:E=>{X.current=E},className:Z.textarea,value:$,onChange:E=>I(E.target.value),placeholder:"Enter text, title, or description...",rows:5,"aria-label":oe})]})}),!_&&c==="link"&&n.jsxs("div",{className:Z.panel,children:[n.jsxs("div",{className:Z.formField,children:[n.jsxs("label",{className:Z.fieldLabel,htmlFor:"dev-modal-link-url",children:["URL ",n.jsx("span",{className:Z.requiredMark,children:"*"})]}),n.jsx("input",{id:"dev-modal-link-url",ref:E=>{X.current=E},type:"text",className:Z.input,value:j.url,onChange:E=>D(O=>({...O,url:E.target.value})),placeholder:"https://... or #overview","aria-label":"Link URL"})]}),n.jsxs("div",{className:Z.formField,children:[n.jsx("label",{className:Z.fieldLabel,htmlFor:"dev-modal-link-label",children:"Label"}),n.jsx("input",{id:"dev-modal-link-label",type:"text",className:Z.input,value:j.label,onChange:E=>D(O=>({...O,label:E.target.value})),placeholder:"Button or hyperlink label","aria-label":"Link Label"})]}),n.jsx("div",{className:Z.formField,children:n.jsxs("label",{className:Z.checkboxLabel,children:[n.jsx("input",{type:"checkbox",className:Z.checkbox,checked:!!j.openInNewTab,onChange:E=>D(O=>({...O,openInNewTab:E.target.checked}))}),n.jsx("span",{children:"Open in new tab"})]})})]}),!_&&c==="image"&&n.jsxs("div",{className:Z.panel,children:[n.jsxs("div",{className:Z.formField,children:[n.jsx("label",{className:Z.fieldLabel,children:"Photo Source"}),n.jsxs("div",{className:Z.segmentedControl,role:"radiogroup","aria-label":"Photo Source",children:[n.jsx("button",{type:"button",role:"radio","aria-checked":R==="upload",className:`${Z.segmentButton} ${R==="upload"?Z.segmentButtonActive:""}`,onClick:()=>W("upload"),children:"Upload Photo"}),n.jsx("button",{type:"button",role:"radio","aria-checked":R==="url",className:`${Z.segmentButton} ${R==="url"?Z.segmentButtonActive:""}`,onClick:()=>W("url"),children:"Photo URL"})]})]}),R==="upload"?n.jsxs("div",{className:Z.fileRow,children:[n.jsx(he,{type:"button",variant:"secondary",size:"sm",onClick:()=>{var E;return(E=K.current)==null?void 0:E.click()},children:"Upload Photo"}),n.jsx("input",{ref:K,type:"file",accept:"image/png,image/jpeg,image/webp,image/gif",className:Z.hiddenFileInput,onChange:V,"aria-label":"Upload photo file"}),n.jsx("span",{className:Z.fileStatus,children:H.src?"Photo selected":"No photo chosen"})]}):n.jsxs("div",{className:Z.formField,children:[n.jsxs("label",{className:Z.fieldLabel,htmlFor:"dev-modal-image-url",children:["Photo URL ",n.jsx("span",{className:Z.requiredMark,children:"*"})]}),n.jsx("input",{id:"dev-modal-image-url",ref:E=>{X.current=E},type:"text",className:Z.input,value:H.src,onChange:E=>L(O=>({...O,src:E.target.value})),placeholder:"https://.../photo.webp","aria-label":"Photo URL"})]}),H.src?n.jsx("div",{className:Z.imagePreviewWrapper,children:n.jsx("img",{src:H.src,alt:H.alt||"Preview",className:Z.previewThumb})}):null,n.jsxs("div",{className:Z.formField,children:[n.jsx("label",{className:Z.fieldLabel,htmlFor:"dev-modal-image-alt",children:"Alt Text (Accessibility)"}),n.jsx("input",{id:"dev-modal-image-alt",type:"text",className:Z.input,value:H.alt,onChange:E=>L(O=>({...O,alt:E.target.value})),placeholder:"Descriptive image summary for screen readers","aria-label":"Photo Alt Text"})]}),n.jsx("div",{className:Z.formField,children:n.jsxs("label",{className:Z.checkboxLabel,children:[n.jsx("input",{type:"checkbox",className:Z.checkbox,checked:!!H.showCaption,onChange:E=>L(O=>({...O,showCaption:E.target.checked}))}),n.jsx("span",{children:"Show caption below photo"})]})}),H.showCaption?n.jsxs("div",{className:Z.formField,children:[n.jsx("label",{className:Z.fieldLabel,htmlFor:"dev-modal-image-caption",children:"Caption"}),n.jsx("input",{id:"dev-modal-image-caption",type:"text",className:Z.input,value:H.caption,onChange:E=>L(O=>({...O,caption:E.target.value})),placeholder:"Image caption text","aria-label":"Photo Caption"})]}):null]}),!_&&c==="file"&&n.jsxs("div",{className:Z.panel,children:[n.jsxs("div",{className:Z.formField,children:[n.jsxs("label",{className:Z.fieldLabel,htmlFor:"dev-modal-file-name",children:["Document Name ",n.jsx("span",{className:Z.requiredMark,children:"*"})]}),n.jsx("input",{id:"dev-modal-file-name",ref:E=>{X.current=E},type:"text",className:Z.input,value:U.name,onChange:E=>G(O=>({...O,name:E.target.value})),placeholder:"e.g. Plan 2025-2028","aria-label":"Document Name"})]}),n.jsxs("div",{className:Z.formField,children:[n.jsxs("label",{className:Z.fieldLabel,htmlFor:"dev-modal-file-url",children:["Document URL ",n.jsx("span",{className:Z.requiredMark,children:"*"})]}),n.jsx("input",{id:"dev-modal-file-url",type:"text",className:Z.input,value:U.url,onChange:E=>G(O=>({...O,url:E.target.value})),placeholder:"https://.../document.pdf or Google Drive link","aria-label":"Document URL"})]}),n.jsxs("div",{className:Z.formField,children:[n.jsx("label",{className:Z.fieldLabel,children:"Format"}),n.jsx("div",{className:Z.formatPills,children:["pdf","doc","sheet","other"].map(E=>n.jsx("button",{type:"button",className:Z.formatPill,"data-active":U.format===E?"true":"false",onClick:()=>G(O=>({...O,format:E})),children:E},E))})]}),n.jsxs("div",{className:Z.fileRow,children:[n.jsx(he,{type:"button",variant:"secondary",size:"sm",onClick:()=>{var E;return(E=Q.current)==null?void 0:E.click()},children:"Upload Document"}),n.jsx("input",{ref:Q,type:"file",accept:".pdf,.doc,.docx,.xls,.xlsx,.csv",className:Z.hiddenFileInput,onChange:J,"aria-label":"Upload document file"}),n.jsx("span",{className:Z.fileStatus,children:U.url?U.url.startsWith("data:")?"Local file selected":"Document linked":"No file chosen"})]})]}),n.jsxs("div",{className:Z.actions,children:[n.jsx("div",{children:(s==="edit"||i||y||f)&&n.jsx(he,{type:"button",variant:"ghost",size:"sm",onClick:te,children:"Reset to default"})}),n.jsxs("div",{className:Z.actionGroupRight,children:[le&&n.jsx("span",{style:{fontSize:"0.8125rem",color:"var(--color-danger, #e11d48)",marginRight:"8px"},children:le}),n.jsx(he,{type:"button",variant:"secondary",size:"sm",onClick:t,disabled:se,children:"Cancel"}),n.jsx(he,{type:"button",variant:"primary",size:"sm",onClick:Y,disabled:se,children:se?"Uploading...":B})]})]})]})})},Xf="_wrapper_l8ktk_7",Jf="_inlineWrapper_l8ktk_19",Zf="_textWrapper_l8ktk_32",Qf="_imageWrapper_l8ktk_33",ep="_controlsBar_l8ktk_37",tp="_indicatorSlotBadge_l8ktk_69",np="_driveButton_l8ktk_126",sp="_textBadge_l8ktk_146",rp="_textContent_l8ktk_166",ap="_textContentInline_l8ktk_174",op="_imageContent_l8ktk_181",ip="_highlightedTarget_l8ktk_190",lp="_imageBadge_l8ktk_202",cp="_indicatorBox_l8ktk_209",dp="_emptyPlaceholder_l8ktk_245",up="_emptyPlaceholderInline_l8ktk_256",hp="_emptyTextBadge_l8ktk_267",je={wrapper:Xf,inlineWrapper:Jf,textWrapper:Zf,imageWrapper:Qf,controlsBar:ep,indicatorSlotBadge:tp,driveButton:np,textBadge:sp,textContent:rp,textContentInline:ap,imageContent:op,highlightedTarget:ip,imageBadge:lp,indicatorBox:cp,emptyPlaceholder:dp,emptyPlaceholderInline:up,emptyTextBadge:hp},Ln=({pointId:e,type:t="text",onEditText:s,onEditSource:r,driveUrl:a,currentValue:o,defaultValue:i,onSave:l,onReset:c,children:d,className:f,inline:m=!1,isSection:h,isNumbered:p,defaultNumbered:x,onNumberedChange:v,editTriggerId:b})=>{const{isDevMode:y,isDesktop:g,setHasUnpublishedChanges:S}=Ne(),[C,T]=u.useState(!1),[N,_]=u.useState(!1);if(u.useEffect(()=>{(!y||!g)&&C&&T(!1)},[y,g,C]),!y||!g)return n.jsx(n.Fragment,{children:d});const k=o!==void 0?o:e?typeof i=="object"?zo(e,i,y):hn(e,typeof i=="string"?i:"",y):"",w=i!==void 0?i:k,$=G=>{G.stopPropagation(),s?s():e&&T(!0)},I=(G,z,q)=>{l?l(G):e&&Kt(e,G,!0),S(!0)},j=()=>{c?c():e&&hs(e,!0),S(!0)},D=t==="image"?"image":t==="file"?"file":t==="link"||t==="source"?"link":"text";if(t==="source")return n.jsxs("div",{className:`${je.wrapper} ${f||""}`,children:[n.jsxs("div",{className:je.controlsBar,children:[n.jsx(he,{type:"button",variant:"admin",size:"xs","data-dev-edit-trigger":"true","data-canvas-edit-trigger":b,onClick:r||$,onMouseEnter:()=>_(!0),onMouseLeave:()=>_(!1),title:`Edit source for ${e||"item"}`,"aria-label":`Edit source for ${e||"item"}`,children:"✎ Edit"}),a&&n.jsx(he,{as:"a",href:a,target:"_blank",rel:"noopener noreferrer",variant:"admin",size:"xs",className:je.driveButton,title:"Open linked Google Drive folder",children:"Drive Folder ↗"})]}),n.jsx("div",{className:`${je.textContent} ${N?je.highlightedTarget:""}`,children:d}),e&&n.jsx(An,{isOpen:C,pointId:e,type:D,currentValue:k,defaultValue:w,onSave:I,onReset:j,onClose:()=>T(!1)})]});if(t==="indicator")return n.jsx("div",{className:`${je.wrapper} ${f||""}`,children:n.jsxs("div",{className:je.indicatorBox,children:[n.jsx("div",{className:je.controlsBar,children:n.jsx("span",{className:je.indicatorSlotBadge,children:"Live Slot · Awaiting Official Indicators"})}),d]})});if(t==="image")return n.jsxs("div",{className:`${je.imageWrapper} ${f||""}`,children:[n.jsx("div",{className:je.imageBadge,onClick:G=>G.stopPropagation(),children:n.jsx(he,{type:"button",variant:"admin",size:"xs","data-dev-edit-trigger":"true","data-canvas-edit-trigger":b,onClick:$,onMouseEnter:()=>_(!0),onMouseLeave:()=>_(!1),title:`Edit image for ${e||"item"}`,"aria-label":`Edit image for ${e||"item"}`,children:"✎ Edit"})}),n.jsx("div",{className:`${je.imageContent} ${N?je.highlightedTarget:""}`,children:d}),e&&n.jsx(An,{isOpen:C,pointId:e,type:"image",currentValue:k,defaultValue:w,onSave:I,onReset:j,onClose:()=>T(!1)})]});if(t==="file"||t==="link")return n.jsxs("div",{className:`${je.inlineWrapper} ${f||""}`,children:[n.jsx("span",{className:`${je.textContentInline} ${N?je.highlightedTarget:""}`,children:d}),n.jsx(he,{type:"button",variant:"admin",size:"xs","data-dev-edit-trigger":"true","data-canvas-edit-trigger":b,onClick:$,onMouseEnter:()=>_(!0),onMouseLeave:()=>_(!1),title:`Edit ${t} for ${e||"item"}`,"aria-label":`Edit ${t} for ${e||"item"}`,children:"✎ Edit"}),e&&n.jsx(An,{isOpen:C,pointId:e,type:D,currentValue:k,defaultValue:w,onSave:I,onReset:j,onClose:()=>T(!1)})]});const H=u.Children.toArray(d).some(G=>{if(typeof G=="string")return G.trim().length>0;if(typeof G=="number")return!0;if(u.isValidElement(G)){const z=G.props||{};return z.children&&typeof z.children=="string"?z.children.trim().length>0:!0}return!1}),L=typeof k=="string"&&(k==="Click Edit to add narrative text for this section."||k==="Enter narrative text here..."||k==="Evidence photograph pending"||k==="Narrative text pending"),U=t==="text"&&(!k||String(k).trim().length===0||L)&&(!H||L);return m?n.jsxs("span",{className:`${je.inlineWrapper} ${f||""}`,children:[n.jsx("span",{className:`${je.textContentInline} ${N?je.highlightedTarget:""}`,children:U?n.jsx("span",{className:je.emptyPlaceholderInline,children:n.jsx("span",{className:je.emptyTextBadge,children:"Empty"})}):d}),n.jsx(he,{type:"button",variant:"admin",size:"xs","data-dev-edit-trigger":"true","data-canvas-edit-trigger":b,onClick:$,onMouseEnter:()=>_(!0),onMouseLeave:()=>_(!1),title:`Edit ${e||"content"}`,"aria-label":`Edit ${e||"content"}`,children:"✎ Edit"}),e&&n.jsx(An,{isOpen:C,pointId:e,type:D,currentValue:U?"":k,defaultValue:U?"":w,isSection:h,isNumbered:p,defaultNumbered:x,onNumberedChange:v,onSave:I,onReset:j,onClose:()=>T(!1)})]}):n.jsxs("div",{className:`${je.textWrapper} ${f||""}`,children:[n.jsx("div",{className:je.textBadge,children:n.jsx(he,{type:"button",variant:"admin",size:"xs","data-dev-edit-trigger":"true","data-canvas-edit-trigger":b,onClick:$,onMouseEnter:()=>_(!0),onMouseLeave:()=>_(!1),title:`Edit ${e||"content"}`,"aria-label":`Edit ${e||"content"}`,children:"✎ Edit"})}),n.jsx("div",{className:`${je.textContent} ${N?je.highlightedTarget:""}`,children:U?n.jsx("div",{className:je.emptyPlaceholder,children:n.jsx("span",{className:je.emptyTextBadge,children:"Empty"})}):d}),e&&n.jsx(An,{isOpen:C,pointId:e,type:D,currentValue:U?"":k,defaultValue:U?"":w,isSection:h,isNumbered:p,defaultNumbered:x,onNumberedChange:v,onSave:I,onReset:j,onClose:()=>T(!1)})]})};function os(e,t,s){const{isDevMode:r}=Ne(),a=r,o=u.useCallback(m=>rd(e,m,a),[e,a]),i=u.useCallback(()=>ad(e,t,a),[e,t,a]),l=u.useSyncExternalStore(o,i,i),c=sd(e,a),d=u.useCallback(m=>{Kt(e,m,a)},[e,a]),f=u.useCallback(()=>{hs(e,a)},[e,a]);return{text:l,isModified:c,setText:d,setValue:d,resetText:f,resetValue:f}}const mp="_heroSection_1f0hs_6",fp="_heroBackgroundCard_1f0hs_23",pp="_ambientMesh_1f0hs_42",gp="_heroContainer_1f0hs_72",vp="_kickerWrap_1f0hs_86",xp="_kickerCenter_1f0hs_94",bp="_kickerPill_1f0hs_100",yp="_kickerPrefix_1f0hs_106",_p="_kickerMeaning_1f0hs_110",wp="_heroTitle_1f0hs_115",Sp="_titleLine_1f0hs_127",Cp="_heroSubtitle_1f0hs_155",kp="_subtitleLine_1f0hs_164",Np="_heroCtaWrap_1f0hs_169",jp="_ctaButtonCenter_1f0hs_178",Tp="_heroStartButton_1f0hs_184",Ze={heroSection:mp,heroBackgroundCard:fp,ambientMesh:pp,heroContainer:gp,kickerWrap:vp,kickerCenter:xp,kickerPill:bp,kickerPrefix:yp,kickerMeaning:_p,heroTitle:wp,titleLine:Sp,heroSubtitle:Cp,subtitleLine:kp,heroCtaWrap:Np,ctaButtonCenter:jp,heroStartButton:Tp},Ip="Folio Engine — Universal Scrollytelling & Dynamic Document Canvas",Ap="Autonomous Multi-Stage Sequence Platform",Ep="A configurable multi-stage sequence and dynamic document platform.",xi=({kickerText:e,title:t,subtitle:s,onStartJourney:r,heroCtaRef:a,heroSlotRef:o})=>{const i=typeof e=="string"?e:Ip,l=typeof t=="string"?t:Ap,c=typeof s=="string"?s:Ep,d=os("hero.kicker",i),f=os("hero.title",l),m=os("hero.subtitle",c),h=os("hero.cta","Start Journey"),p=d.text||i,x=()=>{if(!p)return null;if(typeof p=="string"&&p.includes(" — ")){const y=p.indexOf(" — "),g=p.slice(0,y+3),S=p.slice(y+3);return n.jsxs(n.Fragment,{children:[n.jsx("span",{className:Ze.kickerPrefix,children:g}),n.jsx("span",{className:Ze.kickerMeaning,children:S})]})}return p},v=()=>{const y=f.text||l;return n.jsx("span",{className:Ze.titleLine,children:y})},b=()=>{const y=m.text||c;return n.jsx("span",{className:Ze.subtitleLine,children:y})};return n.jsxs("section",{id:"hero",className:Ze.heroSection,"aria-labelledby":"hero-title",children:[n.jsx("div",{className:Ze.heroBackgroundCard,"aria-hidden":"true",children:n.jsx("div",{className:Ze.ambientMesh})}),n.jsxs("div",{className:Ze.heroContainer,children:[p&&n.jsx("div",{className:Ze.kickerWrap,children:n.jsx(Ln,{pointId:"hero.kicker",defaultValue:i,currentValue:d.text,children:n.jsx("div",{className:Ze.kickerCenter,children:n.jsx(or,{label:x(),variant:"white",className:Ze.kickerPill,ariaLabel:typeof p=="string"?p:void 0})})})}),n.jsx(Ln,{pointId:"hero.title",defaultValue:l,currentValue:f.text,children:n.jsx("h1",{id:"hero-title",className:Ze.heroTitle,children:v()})}),n.jsx(Ln,{pointId:"hero.subtitle",defaultValue:c,currentValue:m.text,children:n.jsx("p",{className:Ze.heroSubtitle,children:b()})}),n.jsx("div",{ref:o||a,className:Ze.heroCtaWrap,children:n.jsx(Ln,{pointId:"hero.cta",defaultValue:"Start Journey",currentValue:h.text,children:n.jsx("div",{className:Ze.ctaButtonCenter,children:n.jsx(he,{as:"button",type:"button",variant:"revolving-outline",outlineWidth:4,size:"lg",revolving:!0,pulse:!0,onClick:r,className:Ze.heroStartButton,"aria-label":"Start Journey through the Plan",children:h.text})})})})]})]})};let Vt=null,is=!0;if(typeof window<"u"){const e=t=>{var s;is&&((s=t.target)!=null&&s.closest('button, a, [role="button"]')||ma())};window.addEventListener("wheel",e,{passive:!0}),window.addEventListener("touchstart",e,{passive:!0})}function ma(){Vt!==null&&(cancelAnimationFrame(Vt),Vt=null,is=!0)}function $p(e){return 1-Math.pow(1-e,3)}function ir({top:e,duration:t,onComplete:s,interruptible:r=!0}){if(typeof window>"u")return;if(is=r,document.documentElement.style.scrollBehavior!=="auto"&&(document.documentElement.style.scrollBehavior="auto"),window.matchMedia("(prefers-reduced-motion: reduce)").matches){window.scrollTo(0,e),is=!0,s==null||s();return}Vt!==null&&(cancelAnimationFrame(Vt),Vt=null);const o=window.scrollY||window.pageYOffset,i=e-o;if(Math.abs(i)<2){is=!0,s==null||s();return}const l=t??Math.min(3e3,Math.max(1600,Math.round(1500+Math.sqrt(Math.abs(i))*32))),c=performance.now(),d=f=>{const m=f-c,h=Math.min(m/l,1),p=$p(h);window.scrollTo(0,Math.round(o+i*p)),h<1?Vt=requestAnimationFrame(d):(Vt=null,is=!0,s==null||s())};Vt=requestAnimationFrame(d)}const eu=e=>{const t=u.useRef(0),s=u.useRef(new Set),[r,a]=u.useState(1),[o,i]=u.useState("above"),[l,c]=u.useState(!1),d=u.useRef("above"),f=u.useRef(!1),m=u.useRef(1),h=u.useRef(!1),p=u.useCallback(()=>{if(!e.current)return;const b=window.innerHeight||document.documentElement.clientHeight,y=Math.min(260,Math.max(180,Math.round(b*.26))),g=e.current.querySelectorAll("[data-node]");let S=0,C="inside",T=1;if(g.length>=2){const _=g[0],k=g[g.length-1],w=_.getBoundingClientRect().top,$=k.getBoundingClientRect().top,I=$-w;if(I>0){const H=(y-w)/I;S=Math.min(Math.max(H,0),1)}const j=I/4;w>y+120?C="above":$<y-j*.75?C="below":C="inside";let D=1/0;g.forEach(H=>{const L=Number(H.dataset.node);if(!isNaN(L)){const U=H.getBoundingClientRect().top,G=Math.abs(y-U);G<D&&(D=G,T=L)}})}else{const _=e.current.getBoundingClientRect(),k=_.height-b;k>0&&(S=Math.min(Math.max((y-_.top)/k,0),1)),_.top>y?C="above":_.bottom<y&&(C="below")}t.current=S,s.current.forEach(_=>_(S)),d.current!==C&&(d.current=C,i(C));const N=C==="inside";f.current!==N&&(f.current=N,c(N)),m.current!==T&&(m.current=T,a(T))},[e]),x=u.useCallback(b=>(s.current.add(b),b(t.current),()=>{s.current.delete(b)}),[]),v=u.useCallback((b,y)=>{if(!e.current)return;const g=e.current.querySelector(`[data-node="${b}"]`);if(g){const S=g.getBoundingClientRect(),C=window.scrollY||window.pageYOffset,T=window.innerHeight,N=Math.min(260,Math.max(180,Math.round(T*.26))),_=C+S.top-N;ir({top:Math.max(0,_),interruptible:!1,onComplete:y})}else{const S=e.current.getBoundingClientRect(),C=window.scrollY||window.pageYOffset,T=window.innerHeight,N=Math.min(260,Math.max(180,Math.round(T*.26))),_=(b-1)/4,k=C+S.top+_*(S.height-T*.5)-N;ir({top:Math.max(0,k),interruptible:!1,onComplete:y})}},[e]);return u.useEffect(()=>{p();const b=()=>{h.current||(window.requestAnimationFrame(()=>{p(),h.current=!1}),h.current=!0)},y=()=>{p()};let g=null;return typeof ResizeObserver<"u"&&e.current&&(g=new ResizeObserver(()=>{h.current||(window.requestAnimationFrame(()=>{p(),h.current=!1}),h.current=!0)}),g.observe(e.current)),window.addEventListener("scroll",b,{passive:!0}),window.addEventListener("resize",y,{passive:!0}),window.addEventListener("orientationchange",y,{passive:!0}),()=>{g&&g.disconnect(),window.removeEventListener("scroll",b),window.removeEventListener("resize",y),window.removeEventListener("orientationchange",y)}},[p]),{progressRef:t,activeStage:r,scrollZone:o,isEngineActive:l,scrollToStage:v,subscribeProgress:x}},Lp="_trackContainer_5m98v_7",Mp="_svgTrack_5m98v_15",Dp="_foundationPath_5m98v_32",Rp="_spinePath_5m98v_41",Bp="_progressGlow_5m98v_52",Pp="_progressInk_5m98v_72",Xn={trackContainer:Lp,svgTrack:Mp,foundationPath:Dp,spinePath:Rp,progressGlow:Bp,progressInk:Pp};function Op(e,t,s,r,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*s.x+l*a*r.x,y:i*o*e.y+3*i*a*t.y+3*o*l*s.y+l*a*r.y}}function Fp(e,t,s,r,a=80){let o=0,i=e;for(let l=1;l<=a;l++){const c=Op(e,t,s,r,l/a);o+=Math.hypot(c.x-i.x,c.y-i.y),i=c}return o}function tu(e,t,s){var _,k;const r=(s==null?void 0:s.paddingRatio)??.06,a=(s==null?void 0:s.minPadding)??48,o=(s==null?void 0:s.maxPadding)??80,i=(s==null?void 0:s.trackStyle)??"conduit",l=(s==null?void 0:s.cornerFilletRadius)??36,c=Math.max(1,(s==null?void 0:s.nodeCount)??((_=s==null?void 0:s.nodes)==null?void 0:_.length)??5),d=Math.max(e,320),f=Math.max(t,480),m=Math.min(Math.max(d*r,a),o),h=m,p=d-m,x=Math.round(Math.max(160,Math.min(f*.26,240))),v=Math.round(Math.max(f,640)),b=Math.max(0,c-1)*v,y=[];for(let w=0;w<c;w++){const $=w+1,I=(k=s==null?void 0:s.nodes)==null?void 0:k[w],j=w%2===0?"left":"right",D=j==="left"?h:p,H=x+w*v,L=c>1?Number((w/(c-1)).toFixed(4)):0,U=(I==null?void 0:I.id)??"P"+$,G=["var(--color-node-1)","var(--color-node-2)","var(--color-node-3)","var(--color-node-4)","var(--color-node-5)"],z=(I==null?void 0:I.accentColorVar)??G[w%5],q=(I==null?void 0:I.label)??"Node "+$;y.push({stage:$,id:U,x:D,y:H,threshold:L,accentColorVar:z,label:q,flank:j})}const g=y[0];let S="M "+g.x.toFixed(1)+" "+g.y.toFixed(1);const C=[0];for(let w=0;w<y.length-1;w++){const $=y[w],I=y[w+1];if(i==="curved"){const j={x:$.x,y:$.y+v*.5},D={x:I.x,y:I.y-v*.5};S+=" C "+j.x.toFixed(1)+" "+j.y.toFixed(1)+", "+D.x.toFixed(1)+" "+D.y.toFixed(1)+", "+I.x.toFixed(1)+" "+I.y.toFixed(1);const H=Fp($,j,D,I);C.push(C[C.length-1]+H)}else{const j=I.x>$.x?1:-1,D=Math.abs(I.x-$.x),H=Math.min(l,D*.4,v*.15),L=Math.max(8,H),G=I.y-L-24,z=G-L;S+=" L "+$.x.toFixed(1)+" "+z.toFixed(1);const q=$.x+j*L;S+=" Q "+$.x.toFixed(1)+" "+G.toFixed(1)+", "+q.toFixed(1)+" "+G.toFixed(1);const P=I.x-j*L;S+=" L "+P.toFixed(1)+" "+G.toFixed(1);const F=G+L;S+=" Q "+I.x.toFixed(1)+" "+G.toFixed(1)+", "+I.x.toFixed(1)+" "+F.toFixed(1),S+=" L "+I.x.toFixed(1)+" "+I.y.toFixed(1);const R=(1+Math.log(1+Math.SQRT2)/Math.SQRT2)*L,W=z-$.y,se=Math.abs(P-q),re=I.y-F,le=W+R+se+R+re;C.push(C[C.length-1]+le)}}const T=C[C.length-1],N=x+b+v;return{pathData:S,totalLength:T,cumLengths:C,points:y,totalHeight:N,y0:x,travelY:b}}function nu(e,t){const s=Math.min(Math.max(e,0),1);if(s<=0)return 0;if(s>=1)return t[t.length-1]??0;const r=t.length-1;if(r<=0)return 0;const a=1/r,o=Math.min(Math.floor(s/a),r-1),i=(s-o*a)/a,l=t[o]??0,c=t[o+1]??l;return l+i*(c-l)}const gt=({pointId:e,defaultText:t,as:s="span",className:r,wrapperClassName:a,style:o,children:i,ariaLabel:l,onSave:c,onReset:d,onEditText:f,inline:m=!1,isSection:h,isNumbered:p,defaultNumbered:x,onNumberedChange:v,editTriggerId:b})=>{const{text:y}=os(e,t);let g;return typeof i=="function"?g=i(y):i!=null?g=i:g=n.jsx(s,{className:r,style:o,"aria-label":l,children:y}),n.jsx(Ln,{pointId:e,type:"text",defaultValue:t,currentValue:y,onEditText:f,onSave:c,onReset:d,className:a,inline:m,isSection:h,isNumbered:p,defaultNumbered:x,onNumberedChange:v,editTriggerId:b,children:g})},Up="_stationWrapper_mu6kf_11",Gp="_stationDormant_mu6kf_54",Hp="_stationActive_mu6kf_73",zp="_portalRing_mu6kf_81",qp="_ringCore_mu6kf_128",Vp="_stationNumber_mu6kf_160",Wp="_stationBody_mu6kf_222",Kp="_left_mu6kf_231",Yp="_right_mu6kf_236",Xp="_contentBlock_mu6kf_241",Jp="_depedBadge_mu6kf_262",Zp="_displayTitle_mu6kf_289",Qp="_summary_mu6kf_300",eg="_actionWrapper_mu6kf_313",tg="_exploreLink_mu6kf_326",ng="_exploreArrow_mu6kf_353",sg="_photoDockSlot_mu6kf_378",Ke={stationWrapper:Up,stationDormant:Gp,stationActive:Hp,portalRing:zp,ringCore:qp,stationNumber:Vp,stationBody:Wp,left:Kp,right:Yp,contentBlock:Xp,depedBadge:Jp,displayTitle:Zp,summary:Qp,actionWrapper:eg,exploreLink:tg,exploreArrow:ng,photoDockSlot:sg},su=1024,bi=u.memo(({page:e,x:t,y:s,trackWidth:r,flank:a,isActive:o,isSelected:i=!1,isConnected:l=!1,onExplore:c,onSelectStage:d})=>{const f=e.nodeNumber??e.index??1,m=f.toString().padStart(2,"0"),h=(e.tagline??e.title).toUpperCase(),p=e.subtitle??e.title,x=e.summary??e.annotation??"",v=u.useCallback(()=>{d==null||d(f)},[d,f]),b=u.useCallback(D=>{(D.key==="Enter"||D.key===" ")&&(D.preventDefault(),d==null||d(f))},[d,f]),y=u.useCallback(D=>{D.stopPropagation(),c(e.id)},[c,e.id]),g=o||i,S=a==="right"?Ke.right:Ke.left,C=g?Ke.stationActive:Ke.stationDormant,T=r??(typeof window<"u"?window.innerWidth:1200),N=T<su,_=N?52:60,k=N?16:32,w=N&&T<=768?340:440,$=N?0:Math.min(520,Math.max(320,T*.3))+48,I=r?a==="left"?r-(t+_)-k-$:t-_-k-$:w,j=Math.max(200,Math.min(w,Math.floor(I)));return n.jsxs("div",{className:Ke.stationWrapper+" "+C+" "+S,"data-node":f,"data-active":g?"true":"false","data-selected":i?"true":"false","data-connected":l?"true":"false",style:{left:t+"px",top:s+"px","--max-content-width":j+"px"},children:[n.jsx("button",{type:"button",className:Ke.portalRing,onClick:v,onKeyDown:b,"aria-label":"Milestone Stage "+m+": "+p+" ("+e.title+") — "+(g?"Active Selected Focal Zone":l?"Connected Milestone":"Upcoming Milestone"),"aria-current":g?"step":void 0,"aria-selected":g,title:"Node "+m+": "+p,children:n.jsx("span",{className:Ke.ringCore,children:n.jsx("span",{className:Ke.stationNumber,children:m})})}),n.jsxs("div",{className:Ke.stationBody,children:[n.jsxs("div",{className:Ke.contentBlock,children:[n.jsx("span",{className:Ke.depedBadge,children:n.jsx(gt,{pointId:`node.${e.id}.tagline`,defaultText:h,as:"span",inline:!0})}),n.jsx(gt,{pointId:`node.${e.id}.title`,defaultText:p,as:"h3",className:Ke.displayTitle}),n.jsx(gt,{pointId:`node.${e.id}.summary`,defaultText:x,as:"p",className:Ke.summary}),n.jsx("div",{className:Ke.actionWrapper,children:n.jsxs("div",{role:"button",tabIndex:0,className:Ke.exploreLink,onClick:y,onKeyDown:D=>{(D.key==="Enter"||D.key===" ")&&(D.preventDefault(),y(D))},"aria-label":"Explore Node Details for Node "+m+": "+p,children:[n.jsx("span",{children:"Explore Node Details"}),n.jsx("span",{className:Ke.exploreArrow,"aria-hidden":"true",children:"↓"})]})})]}),n.jsx("div",{className:Ke.photoDockSlot,"data-photo-dock":f,"aria-hidden":"true"})]})]})});bi.displayName="RoadmapNode";const yi=u.memo(({nodes:e=[],activeStage:t,subscribeProgress:s,className:r,onNodeClick:a,onExplore:o,options:i})=>{const l=u.useRef(null),c=u.useRef(null),d=u.useRef(null),f=u.useRef(new Map),[m,h]=u.useState(()=>({width:typeof window<"u"?document.documentElement.clientWidth||window.innerWidth:1200,height:typeof window<"u"?document.documentElement.clientHeight||window.innerHeight:800})),[p,x]=u.useState(t);u.useEffect(()=>{x(t)},[t]);const v=u.useCallback(g=>{x(g),a==null||a(g)},[a]),b=u.useCallback(g=>{if(o){o(g);return}const S=document.getElementById("page-section-"+g);if(S)S.scrollIntoView({behavior:"smooth"});else{const C=document.getElementById("sequence-roadmap");if(C){const T=C.offsetTop+C.offsetHeight+10;window.scrollTo({top:T,behavior:"smooth"})}}},[o]);u.useEffect(()=>{let g=null;const S=()=>{g&&cancelAnimationFrame(g),g=requestAnimationFrame(()=>{if(!l.current)return;const T=l.current.clientWidth,N=Math.round(l.current.getBoundingClientRect().width),_=typeof document<"u"?document.documentElement.clientWidth:0,k=typeof window<"u"?window.innerWidth:0,w=Math.round(T||N||_||k||1200),$=Math.round((typeof window<"u"?window.innerHeight:0)||(typeof document<"u"?document.documentElement.clientHeight:0)||800);w<=0||h(I=>Math.abs(I.width-w)<2&&Math.abs(I.height-$)<2?I:{width:w,height:$})})};S();let C=null;return typeof ResizeObserver<"u"&&l.current&&(C=new ResizeObserver(()=>{S()}),C.observe(l.current)),window.addEventListener("resize",S,{passive:!0}),window.addEventListener("orientationchange",S,{passive:!0}),()=>{g&&cancelAnimationFrame(g),C&&C.disconnect(),window.removeEventListener("resize",S),window.removeEventListener("orientationchange",S)}},[]);const y=u.useMemo(()=>tu(m.width,m.height,{...i,nodeCount:e.length>0?e.length:void 0,nodes:e.length>0?e.map((g,S)=>({stage:g.nodeNumber??g.index??S+1,id:g.id,accentColorVar:g.accentColor,label:g.title})):void 0}),[m.width,m.height,e,i]);return u.useEffect(()=>{if(l.current){const C=new Map;l.current.querySelectorAll("[data-node]").forEach(T=>{const N=Number(T.dataset.node);isNaN(N)||C.set(N,T)}),f.current=C}return s(C=>{const T=Math.min(Math.max(C,0),1),N=y.totalLength>0?nu(T,y.cumLengths)/y.totalLength:0,_=Math.max(0,1-N);d.current&&(d.current.style.strokeDashoffset=_.toFixed(5)),c.current&&(c.current.style.strokeDashoffset=_.toFixed(5));const k=.008;for(let w=0;w<y.points.length;w++){const $=y.points[w],I=T>=$.threshold-k,j=f.current.get($.stage);if(j){const D=I?"true":"false";j.dataset.connected!==D&&(j.dataset.connected=D)}}})},[s,y]),n.jsxs("div",{ref:l,className:Xn.trackContainer+" "+(r||""),style:{width:"100%",height:y.totalHeight+"px"},children:[n.jsx("svg",{className:Xn.svgTrack,width:m.width,height:y.totalHeight,viewBox:"0 0 "+m.width+" "+y.totalHeight,preserveAspectRatio:"none",role:"presentation","aria-hidden":"true",children:n.jsxs("g",{children:[n.jsx("path",{d:y.pathData,className:Xn.foundationPath}),n.jsx("path",{d:y.pathData,className:Xn.spinePath}),n.jsx("path",{ref:c,d:y.pathData,className:Xn.progressGlow,pathLength:1,style:{strokeDasharray:1,strokeDashoffset:1}}),n.jsx("path",{ref:d,d:y.pathData,className:Xn.progressInk,pathLength:1,style:{strokeDasharray:1,strokeDashoffset:1,opacity:1}})]})}),y.points.map((g,S)=>{const C=e[S]??{id:g.id,index:g.stage,title:g.label,subtitle:g.label,accentColor:g.accentColorVar},T=p===g.stage,N=t===g.stage;return n.jsx(bi,{page:C,x:g.x,y:g.y,trackWidth:m.width,flank:g.flank,isActive:N,isSelected:T,isConnected:g.stage===1,onExplore:b,onSelectStage:v},C.id)})]})});yi.displayName="RoadmapTrack";const rg="_roadmapSection_mduuo_7",ag={roadmapSection:rg},_i=u.forwardRef(({nodes:e,options:t,onStageChange:s,onExploreNode:r,onExplorePage:a},o)=>{const i=r??a,l=u.useRef(null),c=(e==null?void 0:e.length)??5,{activeStage:d,scrollZone:f,scrollToStage:m,subscribeProgress:h}=eu(l);return u.useEffect(()=>{s==null||s(d,f)},[d,f,s]),u.useImperativeHandle(o,()=>({scrollToStage:m,nextStage:p=>{d<c&&m(d+1,p)},prevStage:p=>{d>1&&m(d-1,p)}}),[d,m,c]),n.jsx("section",{ref:l,className:ag.roadmapSection,"aria-label":"Winding Progression Roadmap",id:"sequence-roadmap",children:n.jsx(yi,{nodes:e,options:t,activeStage:d,subscribeProgress:h,onNodeClick:m,onExplore:i})})});_i.displayName="RoadmapSection";const og="_siteFooter_y6722_11",ig="_footerContainer_y6722_19",lg="_footerGrid_y6722_33",cg="_brandColumn_y6722_40",dg="_brandGroup_y6722_45",ug="_brandName_y6722_53",hg="_navColumn_y6722_63",mg="_columnHeading_y6722_69",fg="_columnList_y6722_79",pg="_footerLink_y6722_88",gg="_footerBottom_y6722_118",vg="_statusBlock_y6722_129",xg="_statusIndicator_y6722_135",bg="_statusHeader_y6722_155",yg="_statusDot_y6722_162",_g="_statusTitle_y6722_172",wg="_statusSeparator_y6722_180",Sg="_statusDesc_y6722_186",Cg="_legalBlock_y6722_193",kg="_copyright_y6722_201",Ng="_legalSeparator_y6722_209",jg="_bottomLink_y6722_214",Te={siteFooter:og,footerContainer:ig,footerGrid:lg,brandColumn:cg,brandGroup:dg,brandName:ug,navColumn:hg,columnHeading:mg,columnList:fg,footerLink:pg,footerBottom:gg,statusBlock:vg,statusIndicator:xg,statusHeader:bg,statusDot:yg,statusTitle:_g,statusSeparator:wg,statusDesc:Sg,legalBlock:Cg,copyright:kg,legalSeparator:Ng,bottomLink:jg},Tg=[{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/"}],aa=({orgName:e="the host application",onRoadmapClick:t,onOverviewClick:s,onNodeClick:r})=>{const a=i=>{s&&(i.preventDefault(),s(i))},o=(i,l)=>{r&&(l.preventDefault(),r(i,l))};return n.jsx("footer",{className:Te.siteFooter,role:"contentinfo","aria-label":"Portal Footer",children:n.jsxs("div",{className:Te.footerContainer,children:[n.jsxs("nav",{className:Te.footerGrid,"aria-label":"Portal Navigation Links",children:[n.jsx("div",{className:Te.brandColumn,children:n.jsxs("a",{href:"/",className:Te.brandGroup,onClick:a,"aria-label":"Portal Home",children:[n.jsx(pr,{size:"md"}),n.jsx("span",{className:Te.brandName,children:"Portal"})]})}),n.jsxs("div",{className:Te.navColumn,children:[n.jsx("h3",{className:Te.columnHeading,children:"Nodes"}),n.jsx("ul",{className:Te.columnList,children:Tg.map(i=>n.jsx("li",{children:n.jsx("a",{href:i.href,className:Te.footerLink,onClick:l=>o(i.code,l),children:i.label})},i.code))})]}),n.jsxs("div",{className:Te.navColumn,children:[n.jsx("h3",{className:Te.columnHeading,children:"Portal"}),n.jsxs("ul",{className:Te.columnList,children:[n.jsx("li",{children:n.jsx("a",{href:"/",className:Te.footerLink,onClick:i=>{s&&(i.preventDefault(),s(i))},children:"Overview"})}),n.jsx("li",{children:n.jsx("a",{href:"/#roadmap",className:Te.footerLink,onClick:i=>{t&&(i.preventDefault(),t(i))},children:"Winding Roadmap"})})]})]})]}),n.jsxs("div",{className:Te.footerBottom,children:[n.jsx("div",{className:Te.statusBlock,children:n.jsxs("div",{className:Te.statusIndicator,role:"status","aria-label":"Folio Engine: Management, Accountability and Systematic collection of Data",children:[n.jsxs("div",{className:Te.statusHeader,children:[n.jsx("span",{className:Te.statusDot,"aria-hidden":"true"}),n.jsx("span",{className:Te.statusTitle,children:"Folio Engine"})]}),n.jsx("span",{className:Te.statusSeparator,"aria-hidden":"true",children:"—"}),n.jsx("span",{className:Te.statusDesc,children:"Management, Accountability and Systematic collection of Data"})]})}),n.jsxs("div",{className:Te.legalBlock,children:[n.jsxs("p",{className:Te.copyright,children:["© ",new Date().getFullYear()," ",e]}),n.jsx("span",{className:Te.legalSeparator,"aria-hidden":"true",children:"·"}),n.jsx("a",{href:"#privacy",className:Te.bottomLink,children:"Data Privacy"})]})]})]})})},Ig="_fabContainer_1vlq5_8",Ag="_positionRight_1vlq5_23",Eg="_positionLeft_1vlq5_28",$g="_visible_1vlq5_33",Lg="_hidden_1vlq5_40",Mg="_fabButton_1vlq5_50",Dg="_fabLabel_1vlq5_64",Rg="_fabArrow_1vlq5_70",Bg="_fabArrowDown_1vlq5_78",Pg="_fabArrowUp_1vlq5_82",Lt={fabContainer:Ig,positionRight:Ag,positionLeft:Eg,visible:$g,hidden:Lg,fabButton:Mg,fabLabel:Dg,fabArrow:Rg,fabArrowDown:Bg,fabArrowUp:Pg},To=({label:e,isVisible:t,position:s="right",direction:r="down",revolving:a=!0,pulse:o,onClick:i,className:l="","aria-label":c})=>{const d=r==="up",f=s==="left",m=o!==void 0?o:!f,[h,p]=u.useState(0);u.useEffect(()=>{if(typeof window>"u"||!window.visualViewport)return;const b=()=>{const g=window.visualViewport;if(!g)return;const S=Math.max(0,window.innerHeight-(g.height+g.offsetTop));p(S)},y=window.visualViewport;return y.addEventListener("resize",b),y.addEventListener("scroll",b),()=>{y.removeEventListener("resize",b),y.removeEventListener("scroll",b)}},[]);const x=f?"Return to the previous milestone":d?"Scroll back to the top of the portal":"Advance to the next milestone",v=n.jsx("span",{className:`${Lt.fabArrow} ${d?Lt.fabArrowUp:Lt.fabArrowDown}`,"aria-hidden":"true",children:d?"↑":"↓"});return n.jsx("div",{className:`${Lt.fabContainer} ${f?Lt.positionLeft:Lt.positionRight} ${t?Lt.visible:Lt.hidden} ${l}`,style:{"--keyboard-offset":`${h}px`},"aria-hidden":!t,children:n.jsxs(he,{variant:"revolving-outline",outlineWidth:3,revolving:a,pulse:m,onClick:i,className:Lt.fabButton,"aria-label":c||x,tabIndex:t?0:-1,children:[f&&v,n.jsx("span",{className:Lt.fabLabel,children:e}),!f&&v]})})},Og="_breadcrumbNav_3mtf1_12",Fg="_breadcrumbInner_3mtf1_17",Ug="_list_3mtf1_25",Gg="_item_3mtf1_47",Hg="_itemCurrent_3mtf1_55",zg="_separator_3mtf1_59",qg="_link_3mtf1_69",Vg="_button_3mtf1_70",Wg="_current_3mtf1_113",Kg="_itemIcon_3mtf1_124",Yg="_itemLabel_3mtf1_132",Xg="_itemBadge_3mtf1_141",Jg="_endSlot_3mtf1_148",He={breadcrumbNav:Og,breadcrumbInner:Fg,list:Ug,item:Gg,itemCurrent:Hg,separator:zg,link:qg,button:Vg,current:Wg,itemIcon:Kg,itemLabel:Yg,itemBadge:Xg,endSlot:Jg},Zg=()=>n.jsx("span",{className:He.separator,"aria-hidden":"true",children:"/"}),wi=u.memo(({items:e,separator:t=n.jsx(Zg,{}),className:s,ariaLabel:r="Breadcrumb navigation",endSlot:a})=>!e||e.length===0?null:n.jsx("nav",{className:`${He.breadcrumbNav} ${s||""}`,"aria-label":r,children:n.jsxs("div",{className:He.breadcrumbInner,children:[n.jsx("ol",{className:He.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}`),f=typeof o.label=="string"?o.label:void 0;return n.jsxs("li",{className:`${He.item} ${c?He.itemCurrent:""}`,children:[i>0&&t,c&&!o.href&&!o.onClick?n.jsxs("span",{className:He.current,"aria-current":"page",title:f,children:[o.icon&&n.jsx("span",{className:He.itemIcon,children:o.icon}),n.jsx("span",{className:He.itemLabel,children:o.label}),o.badge&&n.jsx("span",{className:He.itemBadge,children:o.badge})]}):o.href?n.jsxs("a",{href:o.href,className:He.link,onClick:o.onClick,"aria-current":c?"page":void 0,title:f,children:[o.icon&&n.jsx("span",{className:He.itemIcon,children:o.icon}),n.jsx("span",{className:He.itemLabel,children:o.label}),o.badge&&n.jsx("span",{className:He.itemBadge,children:o.badge})]}):n.jsxs("button",{type:"button",className:He.button,onClick:o.onClick,"aria-current":c?"page":void 0,title:f,children:[o.icon&&n.jsx("span",{className:He.itemIcon,children:o.icon}),n.jsx("span",{className:He.itemLabel,children:o.label}),o.badge&&n.jsx("span",{className:He.itemBadge,children:o.badge})]})]},d)})}),a&&n.jsx("div",{className:He.endSlot,children:a})]})}));wi.displayName="Breadcrumb";const Qg="_pageHeader_fl56i_11",ev="_kicker_fl56i_19",tv="_title_fl56i_28",nv="_subtitle_fl56i_38",sv="_extra_fl56i_48",rn={pageHeader:Qg,kicker:ev,title:tv,subtitle:nv,extra:sv},Si=u.memo(({title:e,titlePointId:t,kicker:s,kickerPointId:r,subtitle:a,subtitlePointId:o,accentColor:i,className:l,children:c})=>{const{isDevMode:d,isDesktop:f}=Ne();return n.jsxs("header",{className:`${rn.pageHeader} ${l||""}`,style:{"--title-accent":i},children:[s||d&&f&&r?r?n.jsx(gt,{pointId:r,defaultText:s||"",as:"div",className:rn.kicker}):n.jsx("div",{className:rn.kicker,children:s}):null,t?n.jsx(gt,{pointId:t,defaultText:e,as:"h1",className:rn.title}):n.jsx("h1",{className:rn.title,children:e}),a||d&&f&&o?o?n.jsx(gt,{pointId:o,defaultText:a||"",as:"p",className:rn.subtitle}):n.jsx("p",{className:rn.subtitle,children:a}):null,c&&n.jsx("div",{className:rn.extra,children:c})]})});Si.displayName="PageTitle";function ru(e,t={}){const{offsetPx:s=140,defaultActiveId:r=e[0]||""}=t,[a,o]=u.useState(r),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 f=[];for(const h of e){const p=document.getElementById(h);p&&f.push(p)}if(f.length===0)return;let m=f[0].id;for(const h of f)if(h.getBoundingClientRect().top<=s)m=h.id;else break;o(m)},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,s]),a}const rv="_sidebarContainer_5hq97_12",av="_sidebarBreadcrumb_5hq97_23",ov="_sidebarBreadcrumbSticky_5hq97_40",iv="_breadcrumbBackBtn_5hq97_47",lv="_breadcrumbArrow_5hq97_79",cv="_sidebarHeading_5hq97_91",dv="_navList_5hq97_102",uv="_navItem_5hq97_111",hv="_navLink_5hq97_116",mv="_navLinkActive_5hq97_142",fv="_itemNumber_5hq97_156",pv="_itemLabel_5hq97_164",bt={sidebarContainer:rv,sidebarBreadcrumb:av,sidebarBreadcrumbSticky:ov,breadcrumbBackBtn:iv,breadcrumbArrow:lv,sidebarHeading:cv,navList:dv,navItem:uv,navLink:hv,navLinkActive:mv,itemNumber:fv,itemLabel:pv},au=({title:e="Contents",items:t=[],activeId:s,accentColor:r,onItemClick:a,className:o,nodeNumber:i,nodeTitle:l,onBack:c})=>{const d=u.useMemo(()=>t.map(y=>y.id||(y.href.startsWith("#")?y.href.slice(1):"")).filter(Boolean),[t]),[f,m]=u.useState(null),h=ru(d,{defaultActiveId:d[0]||"",offsetPx:140}),p=s||f||h,x=u.useCallback((y,g)=>{y.preventDefault(),a==null||a(g);const S=g.id||(g.href.startsWith("#")?g.href.slice(1):"");S&&m(S);const C=document.getElementById(S);if(C){const _=C.getBoundingClientRect().top+window.pageYOffset-100;window.scrollTo({top:Math.max(0,_),behavior:"smooth"})}},[a]);u.useEffect(()=>{if(!f)return;const y=g=>{var S;(S=g.target)!=null&&S.closest("button, a")||m(null)};return window.addEventListener("wheel",y,{passive:!0}),window.addEventListener("touchmove",y,{passive:!0}),()=>{window.removeEventListener("wheel",y),window.removeEventListener("touchmove",y)}},[f]);const[v,b]=u.useState(!1);return u.useEffect(()=>{if(typeof window>"u")return;const y=()=>{const g=window.scrollY||window.pageYOffset;b(g>40)};return y(),window.addEventListener("scroll",y,{passive:!0}),()=>window.removeEventListener("scroll",y)},[]),n.jsxs("aside",{className:`${bt.sidebarContainer} ${o||""}`,"aria-label":`${e} navigation`,style:{"--sidebar-accent":r},children:[c&&n.jsx("div",{className:`${bt.sidebarBreadcrumb} ${v?bt.sidebarBreadcrumbSticky:""}`,"aria-hidden":!v,children:n.jsxs("button",{type:"button",className:bt.breadcrumbBackBtn,onClick:c,"aria-label":"Return to Roadmap",title:"Return to Roadmap",tabIndex:v?0:-1,children:[n.jsx("svg",{className:bt.breadcrumbArrow,viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:n.jsx("path",{d:"M10 13L5 8l5-5"})}),n.jsx("span",{children:"Roadmap"})]})}),n.jsx("div",{className:bt.sidebarHeading,children:e}),n.jsx("nav",{children:n.jsx("ul",{className:bt.navList,children:t.map(y=>{const g=y.id||(y.href.startsWith("#")?y.href.slice(1):""),S=y.isActive??(!!g&&p===g);return n.jsx("li",{className:bt.navItem,children:n.jsxs("a",{href:y.href,className:`${bt.navLink} ${S?bt.navLinkActive:""}`,onClick:C=>x(C,y),"aria-current":S?"true":void 0,children:[y.number&&n.jsx("span",{className:bt.itemNumber,children:y.number}),n.jsx("span",{className:bt.itemLabel,children:y.label})]})},y.href)})})})]})};function st(e){return e==null?"":String(e).trim().replace(/\s+/g," ")}function Za(e){if(e==null)return null;const t=String(e).trim();if(t===""||t==="-"||t.startsWith("#"))return null;const s=t.replace(/[₱$,%]/g,"").trim(),r=Number(s);return Number.isFinite(r)?r:null}function Ql(e){const t=e.trim().toLowerCase();return t.startsWith("total")||t.startsWith("grand total")||t.startsWith("average")||t.startsWith("mean")}function ec(e){let t=0;const s=e.trim().toUpperCase();for(let r=0;r<s.length;r++)t=t*26+(s.charCodeAt(r)-64);return t-1}function ct(e){let t=e+1,s="";for(;t>0;){const r=(t-1)%26;s=String.fromCharCode(65+r)+s,t=Math.floor((t-r)/26)}return s}function Ar(e){if(!e||typeof e!="string")return null;const s=e.trim().match(/^(?:(?:'([^']+)'|([A-Za-z0-9_\s-]+))!)?([A-Za-z]+)(\d*):([A-Za-z]+)(\d*)$/);if(!s)return null;const[,r,a,o,i,l,c]=s,d=r||a?st(r||a):void 0,f=ec(o),m=i?parseInt(i,10)-1:0,h=ec(l),p=c?parseInt(c,10)-1:void 0;return f<0||m<0||h<0||p!==void 0&&p<0||f>h||p!==void 0&&m>p?null:{...d?{sheetName:d}:{},startCol:f,startRow:m,endCol:h,...p!==void 0?{endRow:p}:{}}}function gv(e){if(!e||e.length===0)return null;let t=-1,s=-1,r=-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 f=c[d];f!=null&&String(f).trim()!==""&&((t===-1||l<t)&&(t=l),(s===-1||l>s)&&(s=l),(r===-1||d<r)&&(r=d),(a===-1||d>a)&&(a=d))}}if(t===-1||r===-1)return null;const o=`${ct(r)}${t+1}`,i=`${ct(a)}${s+1}`;return`${o}:${i}`}function ou(e,t,s,r){const a=[];s&&a.push([`# Title: ${st(s)}${r?` (${st(r)})`:""}`]);const o=["Category",...t.map(i=>st(i.name))];a.push(o);for(let i=0;i<e.length;i++){const l=[st(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(`
2
+ `)?`"${l.replace(/"/g,'""')}"`:l).join(",")).join(`
3
+ `)}function vv(e=new Date){const t=c=>String(c).padStart(2,"0"),s=e.getFullYear(),r=t(e.getMonth()+1),a=t(e.getDate()),o=t(e.getHours()),i=t(e.getMinutes()),l=t(e.getSeconds());return`${s}-${r}-${a}_${o}${i}${l}`}function Qa(e){return!e||typeof e!="string"?"":e.trim().replace(/[/\\:]+/g,"-").replace(/[*?"<>|]+/g,"").replace(/\s+/g," ").trim().replace(/^[.-]+|[.-]+$/g,"")}function xv(e){const t=Qa(e.title||""),s=Qa(e.sheetName||""),r=Qa(e.chartId||""),a=t||s||r||"chart-data",o=vv(e.date||new Date);return`${a}_${o}.csv`}function oa(e,t){return e==null||t==null?NaN:e<t?-1:e>t?1:e>=t?0:NaN}function bv(e,t){return e==null||t==null?NaN:t<e?-1:t>e?1:t>=e?0:NaN}function iu(e){let t,s,r;e.length!==2?(t=oa,s=(l,c)=>oa(e(l),c),r=(l,c)=>e(l)-c):(t=e===oa||e===bv?e:yv,s=e,r=e);function a(l,c,d=0,f=l.length){if(d<f){if(t(c,c)!==0)return f;do{const m=d+f>>>1;s(l[m],c)<0?d=m+1:f=m}while(d<f)}return d}function o(l,c,d=0,f=l.length){if(d<f){if(t(c,c)!==0)return f;do{const m=d+f>>>1;s(l[m],c)<=0?d=m+1:f=m}while(d<f)}return d}function i(l,c,d=0,f=l.length){const m=a(l,c,d,f-1);return m>d&&r(l[m-1],c)>-r(l[m],c)?m-1:m}return{left:a,center:i,right:o}}function yv(){return 0}function _v(e){return e===null?NaN:+e}const wv=iu(oa),Sv=wv.right;iu(_v).center;function Cv(e,t){let s,r;for(const a of e)a!=null&&(s===void 0?a>=a&&(s=r=a):(s>a&&(s=a),r<a&&(r=a)));return[s,r]}class tc extends Map{constructor(t,s=jv){if(super(),Object.defineProperties(this,{_intern:{value:new Map},_key:{value:s}}),t!=null)for(const[r,a]of t)this.set(r,a)}get(t){return super.get(nc(this,t))}has(t){return super.has(nc(this,t))}set(t,s){return super.set(kv(this,t),s)}delete(t){return super.delete(Nv(this,t))}}function nc({_intern:e,_key:t},s){const r=t(s);return e.has(r)?e.get(r):s}function kv({_intern:e,_key:t},s){const r=t(s);return e.has(r)?e.get(r):(e.set(r,s),s)}function Nv({_intern:e,_key:t},s){const r=t(s);return e.has(r)&&(s=e.get(r),e.delete(r)),s}function jv(e){return e!==null&&typeof e=="object"?e.valueOf():e}const Tv=Math.sqrt(50),Iv=Math.sqrt(10),Av=Math.sqrt(2);function fa(e,t,s){const r=(t-e)/Math.max(0,s),a=Math.floor(Math.log10(r)),o=r/Math.pow(10,a),i=o>=Tv?10:o>=Iv?5:o>=Av?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<=s&&s<2?fa(e,t,s*2):[l,c,d]}function Ev(e,t,s){if(t=+t,e=+e,s=+s,!(s>0))return[];if(e===t)return[e];const r=t<e,[a,o,i]=r?fa(t,e,s):fa(e,t,s);if(!(o>=a))return[];const l=o-a+1,c=new Array(l);if(r)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 Io(e,t,s){return t=+t,e=+e,s=+s,fa(e,t,s)[2]}function $v(e,t,s){t=+t,e=+e,s=+s;const r=t<e,a=r?Io(t,e,s):Io(e,t,s);return(r?-1:1)*(a<0?1/-a:a)}function Lv(e,t,s){e=+e,t=+t,s=(a=arguments.length)<2?(t=e,e=0,1):a<3?1:+s;for(var r=-1,a=Math.max(0,Math.ceil((t-e)/s))|0,o=new Array(a);++r<a;)o[r]=e+r*s;return o}function Ci(e,t){switch(arguments.length){case 0:break;case 1:this.range(e);break;default:this.range(t).domain(e);break}return this}const sc=Symbol("implicit");function lu(){var e=new tc,t=[],s=[],r=sc;function a(o){let i=e.get(o);if(i===void 0){if(r!==sc)return r;e.set(o,i=t.push(o)-1)}return s[i%s.length]}return a.domain=function(o){if(!arguments.length)return t.slice();t=[],e=new tc;for(const i of o)e.has(i)||e.set(i,t.push(i)-1);return a},a.range=function(o){return arguments.length?(s=Array.from(o),a):s.slice()},a.unknown=function(o){return arguments.length?(r=o,a):r},a.copy=function(){return lu(t,s).unknown(r)},Ci.apply(a,arguments),a}function cu(){var e=lu().unknown(void 0),t=e.domain,s=e.range,r=0,a=1,o,i,l=!1,c=0,d=0,f=.5;delete e.unknown;function m(){var h=t().length,p=a<r,x=p?a:r,v=p?r:a;o=(v-x)/Math.max(1,h-c+d*2),l&&(o=Math.floor(o)),x+=(v-x-o*(h-c))*f,i=o*(1-c),l&&(x=Math.round(x),i=Math.round(i));var b=Lv(h).map(function(y){return x+o*y});return s(p?b.reverse():b)}return e.domain=function(h){return arguments.length?(t(h),m()):t()},e.range=function(h){return arguments.length?([r,a]=h,r=+r,a=+a,m()):[r,a]},e.rangeRound=function(h){return[r,a]=h,r=+r,a=+a,l=!0,m()},e.bandwidth=function(){return i},e.step=function(){return o},e.round=function(h){return arguments.length?(l=!!h,m()):l},e.padding=function(h){return arguments.length?(c=Math.min(1,d=+h),m()):c},e.paddingInner=function(h){return arguments.length?(c=Math.min(1,h),m()):c},e.paddingOuter=function(h){return arguments.length?(d=+h,m()):d},e.align=function(h){return arguments.length?(f=Math.max(0,Math.min(1,h)),m()):f},e.copy=function(){return cu(t(),[r,a]).round(l).paddingInner(c).paddingOuter(d).align(f)},Ci.apply(m(),arguments)}function ki(e,t,s){e.prototype=t.prototype=s,s.constructor=e}function du(e,t){var s=Object.create(e.prototype);for(var r in t)s[r]=t[r];return s}function Er(){}var lr=.7,pa=1/lr,ps="\\s*([+-]?\\d+)\\s*",cr="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",Pt="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",Mv=/^#([0-9a-f]{3,8})$/,Dv=new RegExp(`^rgb\\(${ps},${ps},${ps}\\)$`),Rv=new RegExp(`^rgb\\(${Pt},${Pt},${Pt}\\)$`),Bv=new RegExp(`^rgba\\(${ps},${ps},${ps},${cr}\\)$`),Pv=new RegExp(`^rgba\\(${Pt},${Pt},${Pt},${cr}\\)$`),Ov=new RegExp(`^hsl\\(${cr},${Pt},${Pt}\\)$`),Fv=new RegExp(`^hsla\\(${cr},${Pt},${Pt},${cr}\\)$`),rc={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};ki(Er,dr,{copy(e){return Object.assign(new this.constructor,this,e)},displayable(){return this.rgb().displayable()},hex:ac,formatHex:ac,formatHex8:Uv,formatHsl:Gv,formatRgb:oc,toString:oc});function ac(){return this.rgb().formatHex()}function Uv(){return this.rgb().formatHex8()}function Gv(){return uu(this).formatHsl()}function oc(){return this.rgb().formatRgb()}function dr(e){var t,s;return e=(e+"").trim().toLowerCase(),(t=Mv.exec(e))?(s=t[1].length,t=parseInt(t[1],16),s===6?ic(t):s===3?new dt(t>>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):s===8?Vr(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):s===4?Vr(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=Dv.exec(e))?new dt(t[1],t[2],t[3],1):(t=Rv.exec(e))?new dt(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=Bv.exec(e))?Vr(t[1],t[2],t[3],t[4]):(t=Pv.exec(e))?Vr(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=Ov.exec(e))?dc(t[1],t[2]/100,t[3]/100,1):(t=Fv.exec(e))?dc(t[1],t[2]/100,t[3]/100,t[4]):rc.hasOwnProperty(e)?ic(rc[e]):e==="transparent"?new dt(NaN,NaN,NaN,0):null}function ic(e){return new dt(e>>16&255,e>>8&255,e&255,1)}function Vr(e,t,s,r){return r<=0&&(e=t=s=NaN),new dt(e,t,s,r)}function Hv(e){return e instanceof Er||(e=dr(e)),e?(e=e.rgb(),new dt(e.r,e.g,e.b,e.opacity)):new dt}function Ao(e,t,s,r){return arguments.length===1?Hv(e):new dt(e,t,s,r??1)}function dt(e,t,s,r){this.r=+e,this.g=+t,this.b=+s,this.opacity=+r}ki(dt,Ao,du(Er,{brighter(e){return e=e==null?pa:Math.pow(pa,e),new dt(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=e==null?lr:Math.pow(lr,e),new dt(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new dt(On(this.r),On(this.g),On(this.b),ga(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:lc,formatHex:lc,formatHex8:zv,formatRgb:cc,toString:cc}));function lc(){return`#${Mn(this.r)}${Mn(this.g)}${Mn(this.b)}`}function zv(){return`#${Mn(this.r)}${Mn(this.g)}${Mn(this.b)}${Mn((isNaN(this.opacity)?1:this.opacity)*255)}`}function cc(){const e=ga(this.opacity);return`${e===1?"rgb(":"rgba("}${On(this.r)}, ${On(this.g)}, ${On(this.b)}${e===1?")":`, ${e})`}`}function ga(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function On(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function Mn(e){return e=On(e),(e<16?"0":"")+e.toString(16)}function dc(e,t,s,r){return r<=0?e=t=s=NaN:s<=0||s>=1?e=t=NaN:t<=0&&(e=NaN),new Nt(e,t,s,r)}function uu(e){if(e instanceof Nt)return new Nt(e.h,e.s,e.l,e.opacity);if(e instanceof Er||(e=dr(e)),!e)return new Nt;if(e instanceof Nt)return e;e=e.rgb();var t=e.r/255,s=e.g/255,r=e.b/255,a=Math.min(t,s,r),o=Math.max(t,s,r),i=NaN,l=o-a,c=(o+a)/2;return l?(t===o?i=(s-r)/l+(s<r)*6:s===o?i=(r-t)/l+2:i=(t-s)/l+4,l/=c<.5?o+a:2-o-a,i*=60):l=c>0&&c<1?0:i,new Nt(i,l,c,e.opacity)}function qv(e,t,s,r){return arguments.length===1?uu(e):new Nt(e,t,s,r??1)}function Nt(e,t,s,r){this.h=+e,this.s=+t,this.l=+s,this.opacity=+r}ki(Nt,qv,du(Er,{brighter(e){return e=e==null?pa:Math.pow(pa,e),new Nt(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?lr:Math.pow(lr,e),new Nt(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,s=this.l,r=s+(s<.5?s:1-s)*t,a=2*s-r;return new dt(eo(e>=240?e-240:e+120,a,r),eo(e,a,r),eo(e<120?e+240:e-120,a,r),this.opacity)},clamp(){return new Nt(uc(this.h),Wr(this.s),Wr(this.l),ga(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=ga(this.opacity);return`${e===1?"hsl(":"hsla("}${uc(this.h)}, ${Wr(this.s)*100}%, ${Wr(this.l)*100}%${e===1?")":`, ${e})`}`}}));function uc(e){return e=(e||0)%360,e<0?e+360:e}function Wr(e){return Math.max(0,Math.min(1,e||0))}function eo(e,t,s){return(e<60?t+(s-t)*e/60:e<180?s:e<240?t+(s-t)*(240-e)/60:t)*255}const Ni=e=>()=>e;function Vv(e,t){return function(s){return e+s*t}}function Wv(e,t,s){return e=Math.pow(e,s),t=Math.pow(t,s)-e,s=1/s,function(r){return Math.pow(e+r*t,s)}}function Kv(e){return(e=+e)==1?hu:function(t,s){return s-t?Wv(t,s,e):Ni(isNaN(t)?s:t)}}function hu(e,t){var s=t-e;return s?Vv(e,s):Ni(isNaN(e)?t:e)}const hc=(function e(t){var s=Kv(t);function r(a,o){var i=s((a=Ao(a)).r,(o=Ao(o)).r),l=s(a.g,o.g),c=s(a.b,o.b),d=hu(a.opacity,o.opacity);return function(f){return a.r=i(f),a.g=l(f),a.b=c(f),a.opacity=d(f),a+""}}return r.gamma=e,r})(1);function Yv(e,t){t||(t=[]);var s=e?Math.min(t.length,e.length):0,r=t.slice(),a;return function(o){for(a=0;a<s;++a)r[a]=e[a]*(1-o)+t[a]*o;return r}}function Xv(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function Jv(e,t){var s=t?t.length:0,r=e?Math.min(s,e.length):0,a=new Array(r),o=new Array(s),i;for(i=0;i<r;++i)a[i]=ji(e[i],t[i]);for(;i<s;++i)o[i]=t[i];return function(l){for(i=0;i<r;++i)o[i]=a[i](l);return o}}function Zv(e,t){var s=new Date;return e=+e,t=+t,function(r){return s.setTime(e*(1-r)+t*r),s}}function va(e,t){return e=+e,t=+t,function(s){return e*(1-s)+t*s}}function Qv(e,t){var s={},r={},a;(e===null||typeof e!="object")&&(e={}),(t===null||typeof t!="object")&&(t={});for(a in t)a in e?s[a]=ji(e[a],t[a]):r[a]=t[a];return function(o){for(a in s)r[a]=s[a](o);return r}}var Eo=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,to=new RegExp(Eo.source,"g");function ex(e){return function(){return e}}function tx(e){return function(t){return e(t)+""}}function nx(e,t){var s=Eo.lastIndex=to.lastIndex=0,r,a,o,i=-1,l=[],c=[];for(e=e+"",t=t+"";(r=Eo.exec(e))&&(a=to.exec(t));)(o=a.index)>s&&(o=t.slice(s,o),l[i]?l[i]+=o:l[++i]=o),(r=r[0])===(a=a[0])?l[i]?l[i]+=a:l[++i]=a:(l[++i]=null,c.push({i,x:va(r,a)})),s=to.lastIndex;return s<t.length&&(o=t.slice(s),l[i]?l[i]+=o:l[++i]=o),l.length<2?c[0]?tx(c[0].x):ex(t):(t=c.length,function(d){for(var f=0,m;f<t;++f)l[(m=c[f]).i]=m.x(d);return l.join("")})}function ji(e,t){var s=typeof t,r;return t==null||s==="boolean"?Ni(t):(s==="number"?va:s==="string"?(r=dr(t))?(t=r,hc):nx:t instanceof dr?hc:t instanceof Date?Zv:Xv(t)?Yv:Array.isArray(t)?Jv:typeof t.valueOf!="function"&&typeof t.toString!="function"||isNaN(t)?Qv:va)(e,t)}function sx(e,t){return e=+e,t=+t,function(s){return Math.round(e*(1-s)+t*s)}}function rx(e){return function(){return e}}function ax(e){return+e}var mc=[0,1];function ls(e){return e}function $o(e,t){return(t-=e=+e)?function(s){return(s-e)/t}:rx(isNaN(t)?NaN:.5)}function ox(e,t){var s;return e>t&&(s=e,e=t,t=s),function(r){return Math.max(e,Math.min(t,r))}}function ix(e,t,s){var r=e[0],a=e[1],o=t[0],i=t[1];return a<r?(r=$o(a,r),o=s(i,o)):(r=$o(r,a),o=s(o,i)),function(l){return o(r(l))}}function lx(e,t,s){var r=Math.min(e.length,t.length)-1,a=new Array(r),o=new Array(r),i=-1;for(e[r]<e[0]&&(e=e.slice().reverse(),t=t.slice().reverse());++i<r;)a[i]=$o(e[i],e[i+1]),o[i]=s(t[i],t[i+1]);return function(l){var c=Sv(e,l,1,r)-1;return o[c](a[c](l))}}function cx(e,t){return t.domain(e.domain()).range(e.range()).interpolate(e.interpolate()).clamp(e.clamp()).unknown(e.unknown())}function dx(){var e=mc,t=mc,s=ji,r,a,o,i=ls,l,c,d;function f(){var h=Math.min(e.length,t.length);return i!==ls&&(i=ox(e[0],e[h-1])),l=h>2?lx:ix,c=d=null,m}function m(h){return h==null||isNaN(h=+h)?o:(c||(c=l(e.map(r),t,s)))(r(i(h)))}return m.invert=function(h){return i(a((d||(d=l(t,e.map(r),va)))(h)))},m.domain=function(h){return arguments.length?(e=Array.from(h,ax),f()):e.slice()},m.range=function(h){return arguments.length?(t=Array.from(h),f()):t.slice()},m.rangeRound=function(h){return t=Array.from(h),s=sx,f()},m.clamp=function(h){return arguments.length?(i=h?!0:ls,f()):i!==ls},m.interpolate=function(h){return arguments.length?(s=h,f()):s},m.unknown=function(h){return arguments.length?(o=h,m):o},function(h,p){return r=h,a=p,f()}}function ux(){return dx()(ls,ls)}function hx(e){return Math.abs(e=Math.round(e))>=1e21?e.toLocaleString("en").replace(/,/g,""):e.toString(10)}function xa(e,t){if(!isFinite(e)||e===0)return null;var s=(e=t?e.toExponential(t-1):e.toExponential()).indexOf("e"),r=e.slice(0,s);return[r.length>1?r[0]+r.slice(2):r,+e.slice(s+1)]}function Ns(e){return e=xa(Math.abs(e)),e?e[1]:NaN}function mx(e,t){return function(s,r){for(var a=s.length,o=[],i=0,l=e[0],c=0;a>0&&l>0&&(c+l+1>r&&(l=Math.max(1,r-c)),o.push(s.substring(a-=l,a+l)),!((c+=l+1)>r));)l=e[i=(i+1)%e.length];return o.reverse().join(t)}}function fx(e){return function(t){return t.replace(/[0-9]/g,function(s){return e[+s]})}}var px=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;function ba(e){if(!(t=px.exec(e)))throw new Error("invalid format: "+e);var t;return new Ti({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]})}ba.prototype=Ti.prototype;function Ti(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+""}Ti.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 gx(e){e:for(var t=e.length,s=1,r=-1,a;s<t;++s)switch(e[s]){case".":r=a=s;break;case"0":r===0&&(r=s),a=s;break;default:if(!+e[s])break e;r>0&&(r=0);break}return r>0?e.slice(0,r)+e.slice(a+1):e}var ya;function vx(e,t){var s=xa(e,t);if(!s)return ya=void 0,e.toPrecision(t);var r=s[0],a=s[1],o=a-(ya=Math.max(-8,Math.min(8,Math.floor(a/3)))*3)+1,i=r.length;return o===i?r:o>i?r+new Array(o-i+1).join("0"):o>0?r.slice(0,o)+"."+r.slice(o):"0."+new Array(1-o).join("0")+xa(e,Math.max(0,t+o-1))[0]}function fc(e,t){var s=xa(e,t);if(!s)return e+"";var r=s[0],a=s[1];return a<0?"0."+new Array(-a).join("0")+r:r.length>a+1?r.slice(0,a+1)+"."+r.slice(a+1):r+new Array(a-r.length+2).join("0")}const pc={"%":(e,t)=>(e*100).toFixed(t),b:e=>Math.round(e).toString(2),c:e=>e+"",d:hx,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)=>fc(e*100,t),r:fc,s:vx,X:e=>Math.round(e).toString(16).toUpperCase(),x:e=>Math.round(e).toString(16)};function gc(e){return e}var vc=Array.prototype.map,xc=["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"];function xx(e){var t=e.grouping===void 0||e.thousands===void 0?gc:mx(vc.call(e.grouping,Number),e.thousands+""),s=e.currency===void 0?"":e.currency[0]+"",r=e.currency===void 0?"":e.currency[1]+"",a=e.decimal===void 0?".":e.decimal+"",o=e.numerals===void 0?gc:fx(vc.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(m,h){m=ba(m);var p=m.fill,x=m.align,v=m.sign,b=m.symbol,y=m.zero,g=m.width,S=m.comma,C=m.precision,T=m.trim,N=m.type;N==="n"?(S=!0,N="g"):pc[N]||(C===void 0&&(C=12),T=!0,N="g"),(y||p==="0"&&x==="=")&&(y=!0,p="0",x="=");var _=(h&&h.prefix!==void 0?h.prefix:"")+(b==="$"?s:b==="#"&&/[boxX]/.test(N)?"0"+N.toLowerCase():""),k=(b==="$"?r:/[%p]/.test(N)?i:"")+(h&&h.suffix!==void 0?h.suffix:""),w=pc[N],$=/[defgprs%]/.test(N);C=C===void 0?6:/[gprs]/.test(N)?Math.max(1,Math.min(21,C)):Math.max(0,Math.min(20,C));function I(j){var D=_,H=k,L,U,G;if(N==="c")H=w(j)+H,j="";else{j=+j;var z=j<0||1/j<0;if(j=isNaN(j)?c:w(Math.abs(j),C),T&&(j=gx(j)),z&&+j==0&&v!=="+"&&(z=!1),D=(z?v==="("?v:l:v==="-"||v==="("?"":v)+D,H=(N==="s"&&!isNaN(j)&&ya!==void 0?xc[8+ya/3]:"")+H+(z&&v==="("?")":""),$){for(L=-1,U=j.length;++L<U;)if(G=j.charCodeAt(L),48>G||G>57){H=(G===46?a+j.slice(L+1):j.slice(L))+H,j=j.slice(0,L);break}}}S&&!y&&(j=t(j,1/0));var q=D.length+j.length+H.length,P=q<g?new Array(g-q+1).join(p):"";switch(S&&y&&(j=t(P+j,P.length?g-H.length:1/0),P=""),x){case"<":j=D+j+H+P;break;case"=":j=D+P+j+H;break;case"^":j=P.slice(0,q=P.length>>1)+D+j+H+P.slice(q);break;default:j=P+D+j+H;break}return o(j)}return I.toString=function(){return m+""},I}function f(m,h){var p=Math.max(-8,Math.min(8,Math.floor(Ns(h)/3)))*3,x=Math.pow(10,-p),v=d((m=ba(m),m.type="f",m),{suffix:xc[8+p/3]});return function(b){return v(x*b)}}return{format:d,formatPrefix:f}}var Kr,mu,fu;bx({thousands:",",grouping:[3],currency:["$",""]});function bx(e){return Kr=xx(e),mu=Kr.format,fu=Kr.formatPrefix,Kr}function yx(e){return Math.max(0,-Ns(Math.abs(e)))}function _x(e,t){return Math.max(0,Math.max(-8,Math.min(8,Math.floor(Ns(t)/3)))*3-Ns(Math.abs(e)))}function wx(e,t){return e=Math.abs(e),t=Math.abs(t)-e,Math.max(0,Ns(t)-Ns(e))+1}function Sx(e,t,s,r){var a=$v(e,t,s),o;switch(r=ba(r??",f"),r.type){case"s":{var i=Math.max(Math.abs(e),Math.abs(t));return r.precision==null&&!isNaN(o=_x(a,i))&&(r.precision=o),fu(r,i)}case"":case"e":case"g":case"p":case"r":{r.precision==null&&!isNaN(o=wx(a,Math.max(Math.abs(e),Math.abs(t))))&&(r.precision=o-(r.type==="e"));break}case"f":case"%":{r.precision==null&&!isNaN(o=yx(a))&&(r.precision=o-(r.type==="%")*2);break}}return mu(r)}function Cx(e){var t=e.domain;return e.ticks=function(s){var r=t();return Ev(r[0],r[r.length-1],s??10)},e.tickFormat=function(s,r){var a=t();return Sx(a[0],a[a.length-1],s??10,r)},e.nice=function(s){s==null&&(s=10);var r=t(),a=0,o=r.length-1,i=r[a],l=r[o],c,d,f=10;for(l<i&&(d=i,i=l,l=d,d=a,a=o,o=d);f-- >0;){if(d=Io(i,l,s),d===c)return r[a]=i,r[o]=l,t(r);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 pu(){var e=ux();return e.copy=function(){return cx(e,pu())},Ci.apply(e,arguments),Cx(e)}function js(e,t,s=!0){const r=pu().domain(e).range(t);return s?r.nice():r}function bc(e,t,s=.2){return cu().domain(e).range(t).padding(s)}const no=[1,2,5,10,20,25,50,100];function kx(e){if(e<=0||!Number.isFinite(e))return 1;if(e<=100){let o=no[0],i=Math.abs(e-o);for(let l=1;l<no.length;l++){const c=no[l],d=Math.abs(e-c);d<i&&(i=d,o=c)}return o}const t=Math.pow(10,Math.floor(Math.log10(e))),s=e/t;let r=1,a=Math.abs(s-1);for(const o of[1,2,2.5,5,10]){const i=Math.abs(s-o);i<a&&(a=i,r=o)}return Math.round(r*t)}function yc(e){const t=e.filter(m=>typeof m=="number"&&Number.isFinite(m));if(t.length<2)return 1;const s=[...t].sort((m,h)=>m-h),r=s.length,a=(r-1)*.25,o=(r-1)*.75,i=m=>{const h=Math.floor(m),p=m-h;return h+1<r?s[h]+p*(s[h+1]-s[h]):s[h]},l=i(a),d=i(o)-l;let f;if(d>0)f=2*d/Math.cbrt(r);else{const m=gu(s);if(m.stdDev>0)f=3.5*m.stdDev/Math.cbrt(r);else{const h=s[r-1]-s[0],p=Math.ceil(Math.log2(r)+1);f=h>0?h/p:1}}return kx(f)}function gu(e){const t=e.filter(h=>typeof h=="number"&&Number.isFinite(h)),s=t.length;if(s===0)return{n:0,mean:0,median:0,mode:void 0,stdDev:0};const a=t.reduce((h,p)=>h+p,0)/s,o=[...t].sort((h,p)=>h-p);let i=0;s%2===1?i=o[Math.floor(s/2)]:i=(o[s/2-1]+o[s/2])/2;const l=new Map;let c=0;for(const h of t){const p=(l.get(h)||0)+1;l.set(h,p),p>c&&(c=p)}let d;if(c>1){const h=[];for(const[p,x]of l.entries())x===c&&h.push(p);h.sort((p,x)=>p-x),d=h.length===1?h[0]:h.length<=3?h.join(", "):"Multimodal"}else{const h=Ii(t);if(h.length>0){let p=h[0];for(const x of h)x.count>p.count&&(p=x);d=`${p.x0}–${p.x1}`}}const f=t.reduce((h,p)=>h+Math.pow(p-a,2),0)/s,m=Math.sqrt(f);return{n:s,mean:Number(a.toFixed(2)),median:Number(i.toFixed(2)),mode:d,stdDev:Number(m.toFixed(2))}}function Ii(e,t){const s=e.filter(m=>typeof m=="number"&&Number.isFinite(m));if(s.length===0)return[];const r=typeof t=="number"?{binCount:t}:t||{},a=r.min!==void 0?r.min:Math.min(...s),o=r.max!==void 0?r.max:Math.max(...s);let i;if(r.strategy==="custom")if(r.bucketSize&&r.bucketSize>0)i=r.bucketSize;else if(r.binCount&&r.binCount>0){const m=o-a;i=m>0?Math.max(1,Math.round(m/r.binCount)):1}else i=yc(s);else if(r.bucketSize&&r.bucketSize>0)i=r.bucketSize;else if(r.binCount&&r.binCount>0&&r.strategy!=="auto"){const m=o-a;i=m>0?Math.max(1,Math.round(m/r.binCount)):1}else i=yc(s);(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 m=l;m<c;m+=i){const h=Number(m.toFixed(4)),p=Number((m+i).toFixed(4));d.push({x0:h,x1:p,count:0})}d.length===0&&d.push({x0:a,x1:a+i,count:0});const f=d.length-1;for(const m of s)for(let h=0;h<=f;h++){const p=d[h];if(h===f?m>=p.x0&&m<=p.x1:m>=p.x0&&m<p.x1){p.count++;break}}return d}function _c(e){const t=e.filter(a=>a!==null&&Number.isFinite(a));if(t.length===0)return[0,100];const[s,r]=Cv(t);return[s??0,r??100]}function ur(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 s=0;s<e.length-1;s++){const r=e[s===0?0:s-1],a=e[s],o=e[s+1],i=e[s+2<e.length?s+2:s+1],l=a.x+(o.x-r.x)/6,c=a.y+(o.y-r.y)/6,d=o.x-(i.x-a.x)/6,f=o.y-(i.y-a.y)/6;t+=` C ${l.toFixed(2)} ${c.toFixed(2)}, ${d.toFixed(2)} ${f.toFixed(2)}, ${o.x.toFixed(2)} ${o.y.toFixed(2)}`}return t}function wc(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 Sc(e,t,s,r,a={}){if(s<=0||r<=0)return"";const o=Math.min(s/2,r/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 ${s.toFixed(2)} v ${r.toFixed(2)} h ${(-s).toFixed(2)} Z`:[`M ${(e+i).toFixed(2)} ${t.toFixed(2)}`,`h ${(s-i-l).toFixed(2)}`,l>0?`a ${l.toFixed(2)} ${l.toFixed(2)} 0 0 1 ${l.toFixed(2)} ${l.toFixed(2)}`:"",`v ${(r-l-c).toFixed(2)}`,c>0?`a ${c.toFixed(2)} ${c.toFixed(2)} 0 0 1 ${(-c).toFixed(2)} ${c.toFixed(2)}`:"",`h ${(-(s-c-d)).toFixed(2)}`,d>0?`a ${d.toFixed(2)} ${d.toFixed(2)} 0 0 1 ${(-d).toFixed(2)} ${(-d).toFixed(2)}`:"",`v ${(-(r-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 Nx(e,t,s,r="asc"){if(!s||s==="sheet_order"||e.length===0){if(r==="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(s==="category")a.sort((l,c)=>{const d=(e[l]||"").localeCompare(e[c]||"",void 0,{numeric:!0,sensitivity:"base"});return r==="desc"?-d:d});else{const l=t.find(c=>c.name===s);a.sort((c,d)=>{let f=0,m=0;if(l)f=typeof l.data[c]=="number"&&Number.isFinite(l.data[c])?l.data[c]:0,m=typeof l.data[d]=="number"&&Number.isFinite(l.data[d])?l.data[d]:0;else for(const h of t){const p=h.data[c],x=h.data[d];typeof p=="number"&&Number.isFinite(p)&&(f+=p),typeof x=="number"&&Number.isFinite(x)&&(m+=x)}return r==="desc"?m-f:f-m})}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 Lo(e){const t=e.filter(v=>typeof v.x=="number"&&Number.isFinite(v.x)&&typeof v.y=="number"&&Number.isFinite(v.y)),s=t.length;if(s<2)return{slope:0,intercept:0,r:0,rSquared:0,n:s};const r=t.reduce((v,b)=>v+b.x,0),a=t.reduce((v,b)=>v+b.y,0),o=r/s,i=a/s;let l=0,c=0,d=0;for(const v of t){const b=v.x-o,y=v.y-i;l+=b*b,c+=y*y,d+=b*y}if(l===0)return{slope:0,intercept:Number(i.toFixed(4)),r:0,rSquared:0,n:s};const f=d/l,m=i-f*o,h=Math.sqrt(l*c),p=h>0?d/h:0,x=p*p;return{slope:Number(f.toFixed(4)),intercept:Number(m.toFixed(4)),r:Number(p.toFixed(4)),rSquared:Number(x.toFixed(4)),n:s}}function jx(e,t,s){const r=e.filter(m=>typeof m.x=="number"&&Number.isFinite(m.x)&&typeof m.y=="number"&&Number.isFinite(m.y)),a=r.length;if(a<=2)return[];const i=r.reduce((m,h)=>m+h.x,0)/a;let l=0,c=0;for(const m of r){const h=m.x-i;l+=h*h;const p=m.y-(t*m.x+s);c+=p*p}if(l===0)return[];const d=Math.sqrt(c/(a-2));return Array.from(new Set(r.map(m=>m.x))).sort((m,h)=>m-h).map(m=>{const h=d*Math.sqrt(1/a+Math.pow(m-i,2)/l),p=t*m+s,x=1.96*h;return{x:m,y0:Number((p-x).toFixed(4)),y1:Number((p+x).toFixed(4))}})}function Cc(e,t,s=2){const r=e.filter(f=>typeof f.x=="number"&&Number.isFinite(f.x)&&typeof f.y=="number"&&Number.isFinite(f.y)),a=r.length;if(a<=s||t.length===0)return[];const i=r.reduce((f,m)=>f+m.x,0)/a;let l=0;for(const f of r){const m=f.x-i;l+=m*m}if(l===0)return[];let c=0;for(const f of r){let m=t[0].y,h=Math.abs(t[0].x-f.x);for(let x=1;x<t.length;x++){const v=Math.abs(t[x].x-f.x);v<h&&(h=v,m=t[x].y)}const p=f.y-m;c+=p*p}const d=Math.sqrt(c/Math.max(1,a-s));return t.map(f=>{const h=1.96*(d*Math.sqrt(1/a+Math.pow(f.x-i,2)/l));return{x:f.x,y0:Number((f.y-h).toFixed(4)),y1:Number((f.y+h).toFixed(4))}})}function Tx(e,t=.5){const s=e.filter(i=>typeof i.x=="number"&&Number.isFinite(i.x)&&typeof i.y=="number"&&Number.isFinite(i.y)),r=s.length;if(r<2)return s.map(i=>({x:i.x,y:i.y}));const a=[...s].sort((i,l)=>i.x-l.x),o=Math.max(2,Math.floor(t*r));return a.map(i=>{const l=i.x,c=a.map(T=>Math.abs(T.x-l)),f=[...c].sort((T,N)=>T-N)[o-1]||1;let m=0,h=0,p=0;const x=c.map(T=>{if(f===0)return 1;const N=T/f;return N>=1?0:Math.pow(1-Math.pow(N,3),3)});for(let T=0;T<r;T++){const N=x[T];m+=N,h+=N*a[T].x,p+=N*a[T].y}if(m===0)return{x:l,y:i.y};const v=h/m,b=p/m;let y=0,g=0;for(let T=0;T<r;T++){const N=x[T],_=a[T].x-v,k=a[T].y-b;y+=N*_*_,g+=N*_*k}if(y===0)return{x:l,y:Number(b.toFixed(4))};const S=g/y,C=b+S*(l-v);return{x:l,y:Number(C.toFixed(4))}})}function Ix(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 s=t.reduce((a,o)=>a+o.x,0),r=t.reduce((a,o)=>a+o.y,0);return{meanX:Number((s/t.length).toFixed(4)),meanY:Number((r/t.length).toFixed(4))}}function Ax(e,t,s="asc"){if(!t||t==="sheet_order"||t==="sheet"||e.length===0)return s==="desc"?[...e].reverse():[...e];const r=[...e];return t==="x"||t==="horizontal"||t==="Horizontal Number"?r.sort((a,o)=>s==="desc"?o.x-a.x:a.x-o.x):t==="y"||t==="vertical"||t==="Vertical Number"?r.sort((a,o)=>s==="desc"?o.y-a.y:a.y-o.y):t==="label"||t==="dot_label"||t==="category"||t==="Point Label"?r.sort((a,o)=>{const i=(a.label||"").localeCompare(o.label||"",void 0,{numeric:!0});return s==="desc"?-i:i}):(t==="group"||t==="category_group"||t==="Group / Category")&&r.sort((a,o)=>{const i=(a.group||"").localeCompare(o.group||"",void 0,{numeric:!0});return s==="desc"?-i:i}),r}function Ex(e,t=40){const s=e.filter(U=>typeof U.x=="number"&&Number.isFinite(U.x)&&typeof U.y=="number"&&Number.isFinite(U.y)),r=s.length;if(r<3){const U=Lo(s),G=[...s].map(F=>F.x).sort((F,R)=>F-R),z=G[0]??0,q=G[G.length-1]??100,P=[];for(let F=0;F<=t;F++){const R=z+F/t*(q-z);P.push({x:R,y:U.slope*R+U.intercept})}return{a:0,b:U.slope,c:U.intercept,rSquared:U.rSquared,points:P}}const a=s.reduce((U,G)=>U+G.x,0)/r,o=s.reduce((U,G)=>U+G.y,0)/r;let i=0,l=0,c=0,d=0;const f=r;let m=0,h=0,p=0;for(const U of s){const G=U.x-a,z=U.y,q=G*G;i+=q*q,l+=q*G,c+=q,d+=G,m+=z,h+=G*z,p+=q*z}const x=i*(c*f-d*d)-l*(l*f-d*c)+c*(l*d-c*c);if(Math.abs(x)<1e-12){const U=Lo(s),G=[...s].map(F=>F.x).sort((F,R)=>F-R),z=G[0]??0,q=G[G.length-1]??100,P=[];for(let F=0;F<=t;F++){const R=z+F/t*(q-z);P.push({x:R,y:U.slope*R+U.intercept})}return{a:0,b:U.slope,c:U.intercept,rSquared:U.rSquared,points:P}}const v=p*(c*f-d*d)-l*(h*f-d*m)+c*(h*d-c*m),b=i*(h*f-d*m)-p*(l*f-d*c)+c*(l*m-h*c),y=i*(c*m-h*d)-l*(l*m-p*d)+p*(l*d-c*c),g=v/x,S=b/x,C=y/x;let T=0,N=0;for(const U of s){const G=U.x-a,z=g*G*G+S*G+C;T+=(U.y-o)*(U.y-o),N+=(U.y-z)*(U.y-z)}const _=T>0?Math.max(0,1-N/T):0,k=[...s].map(U=>U.x).sort((U,G)=>U-G),w=k[0],I=k[k.length-1]-w||1,j=[];for(let U=0;U<=t;U++){const G=w+U/t*I,z=G-a,q=g*z*z+S*z+C;j.push({x:G,y:q})}const D=g,H=S-2*g*a,L=C-S*a+g*a*a;return{a:D,b:H,c:L,rSquared:_,points:j}}const so={};function Xt(e){if(!e||typeof e!="string")return null;const t=e.trim(),s=t.match(/\/spreadsheets\/(?:u\/\d+\/)?d\/([a-zA-Z0-9-_]{20,})/);return s&&s[1]?s[1]:/^[a-zA-Z0-9-_]{25,80}$/.test(t)?t:null}function vu(e){if(!e||typeof e!="string")return null;const t=e.match(/[#?&]gid=([0-9]+)/);return t&&t[1]?t[1]:null}function Ai(){var t;const e=typeof{url:typeof document>"u"?require("url").pathToFileURL(__filename).href:Le&&Le.tagName.toUpperCase()==="SCRIPT"&&Le.src||new URL("folio.cjs",document.baseURI).href}<"u"&&(so==null?void 0:so.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 xu(e){if(!e||typeof e!="object")return[];const t=e.sheets;if(!Array.isArray(t))return[];const s=[];for(let r=0;r<t.length;r++){const a=t[r];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:r;s.push({title:o,sheetId:l,index:c})}}return s}function $x(e){if(!e||typeof e!="string")return[];const t=/items\.push\(\{\s*name:\s*"([^"\\]*(?:\\.[^"\\]*)*)"[^}]*gid:\s*"([0-9-]+)"/g;let s;const r=[];for(;(s=t.exec(e))!==null;){let a=s[1];try{a=JSON.parse(`"${a}"`)}catch{}const o=s[2],i=Number(o)||0;r.push({title:a.trim(),sheetId:i,index:r.length})}return r}async function bu(e,t,s){const r=Xt(e)||e;if(!r)return[];const a=(s==null?void 0:s.timeoutMs)??6e3,o=Ai();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(r)}?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 f=await d.json(),m=xu(f);if(m&&m.length>0)return m}}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(r)}/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 f=await d.text(),m=$x(f);if(m&&m.length>0)return m}}catch{}return[]}async function Lx(e,t){var i;const s=Xt(e);if(!s)return{accessible:!1,spreadsheetId:null,error:"Invalid Google Sheets URL format. Please paste a valid Google Spreadsheet link."};const r=vu(e),a=Ai(),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(s)}?fields=properties.title,sheets.properties&key=${encodeURIComponent(a)}`,f=await fetch(d,{method:"GET",headers:{Accept:"application/json"},signal:l==null?void 0:l.signal});if(c&&clearTimeout(c),f.ok){const m=await f.json(),h=xu(m);return{accessible:!0,spreadsheetId:s,sheetGid:r,title:(i=m.properties)==null?void 0:i.title,tabs:h}}}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(s)}/gviz/tq?tqx=out:csv&tq=SELECT+1+LIMIT+1`,f=await fetch(d,{method:"GET",headers:{Accept:"text/csv,text/plain,*/*"},signal:l==null?void 0:l.signal});if(c&&clearTimeout(c),!f.ok)return{accessible:!1,spreadsheetId:s,sheetGid:r,error:"Access Restricted: Please set Google Sheet sharing to 'Anyone with the link can view'."};const m=await f.text();if(m.includes("<!DOCTYPE html")||m.includes("ServiceLogin")||m.includes("accounts.google.com"))return{accessible:!1,spreadsheetId:s,sheetGid:r,error:"Access Restricted: Please set Google Sheet sharing to 'Anyone with the link can view'."};const[h,p]=await Promise.all([bu(s,t==null?void 0:t.apiKey,{timeoutMs:4e3}),Mx(s,t==null?void 0:t.apiKey,{timeoutMs:4e3})]);return{accessible:!0,spreadsheetId:s,sheetGid:r,tabs:h.length>0?h:void 0,modifiedTime:p||void 0}}catch{return{accessible:!1,spreadsheetId:s,sheetGid:r,error:"Unable to verify sheet access. Ensure the sheet is public and shared with 'Anyone with the link can view'."}}}function Mo(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 Mx(e,t,s){const r=Xt(e)||e;if(!r)return null;const a=Ai();if(!a)return null;const o=s==null?void 0:s.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(r)}?fields=modifiedTime&key=${encodeURIComponent(a)}`,d={Accept:"application/json"};typeof window>"u"&&(d.Referer="https://engine.example.com");const f=await fetch(c,{method:"GET",headers:d,signal:i==null?void 0:i.signal});if(l&&clearTimeout(l),f.ok){const m=await f.json();if(m&&typeof m.modifiedTime=="string")return m.modifiedTime}return null}catch{return l&&clearTimeout(l),null}}function Ei(e){if(!e||typeof e!="string")return[];const t=[];let s=[],r="",a=!1;for(let o=0;o<e.length;o++){const i=e[o],l=e[o+1];a?i==='"'?l==='"'?(r+='"',o++):a=!1:r+=i:i==='"'?a=!0:i===","?(s.push(r.trim()),r=""):i==="\r"||(i===`
4
+ `?(s.push(r.trim()),t.push(s),s=[],r=""):r+=i)}return(r.length>0||s.length>0)&&(s.push(r.trim()),t.push(s)),t.filter(o=>o.some(i=>i.length>0))}function Dx(e,t){if(!e||e.length===0)return[];const s=[],r=t.endRow!==void 0?Math.min(t.endRow,e.length-1):e.length-1;for(let a=t.startRow;a<=r;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]:"");s.push(i)}return s}function yu(e){var a;if(!e||e.length===0)return[];const t=e.length,s=Math.max(...e.map(o=>o?o.length:0));if(s===0)return[];const r=[];for(let o=0;o<s;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:"")}r.push(i)}return r}function Rx(e,t,s){if(!s||s==="none"||e.length===0)return{categories:e,series:t};const r=e.map((i,l)=>l);r.sort((i,l)=>{if(s==="category-asc")return(e[i]||"").localeCompare(e[l]||"",void 0,{numeric:!0,sensitivity:"base"});if(s==="category-desc")return(e[l]||"").localeCompare(e[i]||"",void 0,{numeric:!0,sensitivity:"base"});let c=0,d=0;for(const f of t){const m=f.data[i],h=f.data[l];typeof m=="number"&&Number.isFinite(m)&&(c+=m),typeof h=="number"&&Number.isFinite(h)&&(d+=h)}return s==="desc"?d-c:c-d});const a=r.map(i=>e[i]),o=t.map(i=>({...i,data:r.map(l=>i.data[l])}));return{categories:a,series:o}}function ns(e){const{chartId:t,title:s,subtitle:r,unit:a,asOfDate:o="SY 2024-2025",chartType:i="bar",nodeId:l,visualConfig:c={},rawMatrix:d,csvText:f}=e;let m=c.unit||a||"",h=d?[...d]:Ei(f||"");if(c.range){const L=Ar(c.range);L&&(h=Dx(h,L))}if(c.transpose&&(h=yu(h)),h.length===0)return{chartId:t,title:st(s),subtitle:r?st(r):void 0,unit:m,asOfDate:o,chartType:i,nodeId:l,visualConfig:c,categories:[],series:[],sanitizedCsvContent:""};const p=h[0]||[],x=typeof c.categoryColIndex=="number"?c.categoryColIndex:0,v=[],b=[];if(Array.isArray(c.includedSeriesIndices)&&c.includedSeriesIndices.length>0)for(const L of c.includedSeriesIndices)L!==x&&L>=0&&L<p.length&&(v.push(L),b.push(st(p[L])||`Col ${L+1}`));else for(let L=0;L<p.length;L++)L!==x&&(v.push(L),b.push(st(p[L])||`Col ${L+1}`));b.length===0&&p.length===1&&(v.push(0),b.push(st(p[0])||"Value"));const y=c.excludeSummaryRows!==!1;let g=[];const S=b.map(()=>[]);for(let L=1;L<h.length;L++){const U=h[L],G=st(U[x]||`Row ${L}`);if(!(y&&Ql(G))){g.push(G);for(let z=0;z<v.length;z++){const q=v[z],P=U[q],F=Za(P);S[z].push(F)}}}let C=b.map((L,U)=>({name:L,data:S[U]||[]})),T;c.sortField?T=Nx(g,C,c.sortField,c.sortDirection||"asc"):T=Rx(g,C,c.sortBy);const N=T.categories,_=T.series;let k=i;k==="auto"&&(k=(_.length>1,"bar"));let w,$;if(k==="histogram"){$=_.flatMap(G=>G.data);const L=$.filter(G=>G!==null&&Number.isFinite(G));w=Ii(L,{strategy:c.binStrategy,binCount:c.binCount,bucketSize:c.bucketSize}).map(G=>({x0:G.x0,x1:G.x1,count:G.count}))}let I;if(k==="scatter"){I=[];const L=typeof c.scatterXColIndex=="number"?c.scatterXColIndex:p.length>1?1:0,U=typeof c.scatterYColIndex=="number"?c.scatterYColIndex:p.length>2?2:p.length>1?1:0,G=typeof c.scatterLabelColIndex=="number"?c.scatterLabelColIndex:x,z=c.scatterGroupColIndex;if(h.length>1)for(let q=1;q<h.length;q++){const P=h[q],F=st(P[x]||`Row ${q}`);if(y&&Ql(F))continue;const R=P[L],W=P[U],se=Za(R),re=Za(W);if(se!==null&&re!==null){const le=typeof G=="number"&&G>=0&&P[G]?st(P[G]):F,M=typeof z=="number"&&z>=0&&P[z]?st(P[z]):void 0;I.push({x:se,y:re,label:le,group:M})}}if(I.length===0&&_.length>=2){const q=N.length;for(let P=0;P<q;P++){const F=_[0].data[P],R=_[1].data[P];F!==null&&R!==null&&I.push({x:F,y:R,label:N[P],group:_[0].name})}}c.sortField&&(I=Ax(I,c.sortField,c.sortDirection||"asc"))}const j=ou(N,_,s,m),H=Mo(c.lastModifiedTime)||o;return{chartId:t,title:st(s),subtitle:r?st(r):void 0,unit:m,asOfDate:H,chartType:k,nodeId:l,visualConfig:c,categories:N,series:_,bins:w,rawValues:$,scatterPoints:I,sanitizedCsvContent:j}}async function $i(e){const{sheetUrl:t,tabName:s,sheetGid:r,range:a,timeoutMs:o=8e3}=e;if(!t||typeof t!="string")return[];const i=Xt(t);if(!i)return[];const l=r||vu(t)||void 0;let c=`https://docs.google.com/spreadsheets/d/${encodeURIComponent(i)}/gviz/tq?tqx=out:csv`;l?c+=`&gid=${encodeURIComponent(l)}`:s&&s.trim()&&(c+=`&sheet=${encodeURIComponent(s.trim())}`),a&&a.trim()&&(c+=`&range=${encodeURIComponent(a.trim())}`),c+=`&_folio_t=${Date.now()}`;const d=typeof AbortController<"u"?new AbortController:null,f=d?setTimeout(()=>d.abort(),o):null;try{const m=await fetch(c,{method:"GET",headers:{Accept:"text/csv,text/plain,*/*"},signal:d==null?void 0:d.signal});if(f&&clearTimeout(f),!m.ok)return[];const h=await m.text();return h.includes("<!DOCTYPE html")||h.includes("accounts.google.com")||h.includes("ServiceLogin")?[]:Ei(h)}catch{return f&&clearTimeout(f),[]}}const Ts=e=>(e||me.getStorageNamespace())+"_chart_source_",Bx=Ts(),$r=e=>(e||me.getStorageNamespace())+"_chart_sources_manifest",Px=$r(),_a="engine-chart-source-change";function Ua(e,t){if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(_a,{detail:{chartId:e,config:t}}))}catch{}}const gs=new Map;function Ga(e){try{return typeof window<"u"&&window.localStorage?window.localStorage.getItem(e):null}catch{return null}}function kc(e,t){try{return typeof window<"u"&&window.localStorage?(window.localStorage.setItem(e,t),!0):!1}catch{return!1}}function ro(e){try{typeof window<"u"&&window.localStorage&&window.localStorage.removeItem(e)}catch{}}function Li(e){const t=e.visual_config??{},s=t.__cached_dataset,r={...t};return delete r.__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:r,cachedDataset:e.cached_dataset??s??null,updatedAt:e.updated_at??new Date().toISOString(),updatedBy:e.updated_by??"coordinator"}}function _u(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 Ox(e){const{sheetUrl:t,...s}=e;return s}function Is(e){if(gs.has(e))return gs.get(e);const t=Ga(`${Ts()}${e}`);if(t)try{const s=JSON.parse(t);return gs.set(e,s),s}catch{return null}return null}function jt(e){if(!e||!e.chartId)return!1;gs.set(e.chartId,e);const t=kc(`${Ts()}${e.chartId}`,JSON.stringify(e));try{const s=$r(),r=Ga(s),a=r?JSON.parse(r):[];a.includes(e.chartId)||(a.push(e.chartId),kc(s,JSON.stringify(a)))}catch{}return Ua(e.chartId,e),t||typeof window>"u"}async function wu(e,t){if(!e)return null;if(!(t!=null&&t.forceRefresh)){const r=Is(e);if(r)return r}const s=qe();if(s)try{const r=typeof AbortController<"u"?new AbortController:null,a=r?setTimeout(()=>r.abort(),6e3):null,o=`${s.url}/rest/v1/chart_sources?chart_id=eq.${encodeURIComponent(e)}&select=*`,i=await fetch(o,{method:"GET",headers:{apikey:s.anonKey,Authorization:`Bearer ${s.anonKey}`,"Content-Type":"application/json"},signal:r==null?void 0:r.signal});if(a&&clearTimeout(a),i.ok){const l=await i.json();if(Array.isArray(l)&&l.length>0){const c=Li(l[0]);return jt(c),c}}}catch{}return Is(e)}async function Fx(e,t){const s=qe();if(s)try{const a=typeof AbortController<"u"?new AbortController:null,o=a?setTimeout(()=>a.abort(),6e3):null,i=`${s.url}/rest/v1/chart_sources?node_id=eq.${encodeURIComponent(e)}&select=*`,l=await fetch(i,{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),l.ok){const c=await l.json();if(Array.isArray(c)){const d=c.map(Li);for(const f of d)jt(f);return d}}}catch{}const r=[];try{const a=Ga($r()),o=a?JSON.parse(a):[];for(const i of o){const l=Is(i);l&&l.nodeId===e&&r.push(l)}}catch{}return r}async function As(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 s={...e,updatedAt:new Date().toISOString()},r=jt(s),a=qe();if(!a)return{success:r,savedLocally:r,savedToCloud:!1,details:"Offline mode: Supabase cloud is not configured."};try{const o=t||a.anonKey,i=_u(s),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:r,savedToCloud:!0};let f=null,m="";try{(d.headers.get("content-type")||"").includes("application/json")?f=await d.json():m=await d.text()}catch{}const h=d.status,p=f==null?void 0:f.code,x=(f==null?void 0:f.message)||m||d.statusText;if(h===400&&i.cached_dataset!==void 0&&x.includes("cached_dataset")&&x.includes("column"))try{const{cached_dataset:b,...y}=i,g=typeof AbortController<"u"?new AbortController:null,S=g?setTimeout(()=>g.abort(),8e3):null;let C;try{C=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(y),signal:g==null?void 0:g.signal})}finally{S&&clearTimeout(S)}if(C.ok)return{success:!0,savedLocally:r,savedToCloud:!0}}catch{}let v="";return h===404||p==="PGRST205"?v="Supabase table 'chart_sources' not found (HTTP 404, PGRST205). Database migration required.":h===401||h===403||p==="PGRST301"?v=`Supabase write permission denied (HTTP ${h}: Row-Level Security policy).`:h===400||h===422?v=`Database schema rejected payload (HTTP ${h}: ${x||"Constraint violation"}).`:h===409?v=`Database conflict (HTTP 409: ${x||"Duplicate constraint"}).`:h>=500?v=`Supabase cloud server unavailable (HTTP ${h}).`:v=`Supabase rejected request (HTTP ${h}: ${x}).`,{success:r,savedLocally:r,savedToCloud:!1,error:v,errorCode:p,statusCode:h,details:(f==null?void 0:f.details)||(f==null?void 0:f.hint)}}catch(o){const i=o instanceof DOMException&&o.name==="AbortError";return{success:r,savedLocally:r,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 ss(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 s=e,r=t==="deploy"?"deploy":"save";if(!s.savedLocally&&!s.savedToCloud)return`Failed to ${r} chart configuration: ${s.error||"Local storage and cloud sync failed."}`;if(s.savedLocally&&!s.savedToCloud)return t==="deploy"?`Failed to deploy to Supabase: ${s.error||"Cloud service unavailable."} (Saved to local browser cache)`:`Saved locally to browser, but cloud sync failed: ${s.error||"Database unavailable."}`}return e instanceof Error?`Failed to ${t} chart configuration: ${e.message}`:`Failed to ${t} chart configuration: ${String(e)}`}async function Ux(e,t){return(await As(e,t)).success}function Gx(e){if(e)gs.delete(e),ro(`${Ts()}${e}`);else{gs.clear();try{const t=$r(),s=Ga(t),r=s?JSON.parse(s):[];for(const a of r)ro(`${Ts()}${a}`);ro(t)}catch{}}}const Yr=$e.bakedChartsData,Do=e=>me.getStorageKey("chart_matrix_"+e);function kn(e,t){var s,r;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||((s=t.visualConfig)==null?void 0:s.unit)||((r=e.visualConfig)==null?void 0:r.unit)}}:e}function Xr(e){return e.map(t=>Array.isArray(t)?t.map(s=>s==null?"":String(s)):[])}function Hx({chartId:e,nodeId:t,initialDataset:s,pollIntervalMs:r,isDevMode:a=!1}){const[o]=u.useState(()=>Is(e)),[i]=u.useState(()=>{try{if(typeof window<"u"&&window.localStorage){let w=window.localStorage.getItem(Do(e));if(w||(w=window.localStorage.getItem("folio_chart_matrix_"+e)),w){const $=JSON.parse(w);if(Array.isArray($)&&$.length>0)return ns({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:$})}}}catch{}if(o!=null&&o.cachedDataset&&o.cachedDataset.length>0)return ns({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:Xr(o.cachedDataset)});if(s)return kn(s,o);const k=Yr.find(w=>w.chartId===e);if(k)return kn(k,o);if(t){const w=Yr.find($=>$.nodeId===t);if(w)return kn(w,o)}return null}),[l,c]=u.useState(i),[d,f]=u.useState(o),[m,h]=u.useState(null),[p,x]=u.useState(()=>i?"success":"pending_data"),[v,b]=u.useState(),[y,g]=u.useState(()=>(o==null?void 0:o.updatedAt)||(i?new Date().toISOString():void 0)),S=u.useRef(!0),C=u.useCallback(async()=>{if(e)try{const k=await wu(e,{forceRefresh:!0});if(!S.current)return;if(k){if(f(k),jt(k),g(k.updatedAt||new Date().toISOString()),k.cachedDataset&&k.cachedDataset.length>0){const w=ns({chartId:e,title:k.titleOverride||"",subtitle:k.subtitleOverride,unit:k.unitOverride,chartType:k.defaultType,nodeId:t,visualConfig:k.visualConfig,rawMatrix:Xr(k.cachedDataset)});S.current&&(c(w),x("success"));return}c(w=>{if(!w){const $=Yr.find(I=>I.chartId===e);return $?kn($,k):null}return kn(w,k)}),x("success")}else c(w=>{if(w)return w;const $=Yr.find(I=>I.chartId===e);return $?kn($,Is(e)):null}),x(w=>w==="syncing"?"success":w)}catch(k){if(!S.current)return;const w=k instanceof Error?k.message:"Failed to sync chart configuration";b(w),x($=>$==="syncing"?"success":$)}},[e,t]),T=u.useCallback(async()=>{if(!e)return null;const k=d||o;if(!(k!=null&&k.sheetUrl))throw new Error("No Google Sheet linked to this chart.");x("syncing"),b(void 0);try{const w=await $i({sheetUrl:k.sheetUrl,tabName:k.tabName,sheetGid:k.sheetGid,range:k.range,timeoutMs:8e3});if(!S.current)return null;if(w&&w.length>0){try{typeof window<"u"&&window.localStorage&&window.localStorage.setItem(Do(e),JSON.stringify(w))}catch{}const $=ns({chartId:e,title:k.titleOverride||"",subtitle:k.subtitleOverride,unit:k.unitOverride,chartType:k.defaultType,nodeId:t,visualConfig:k.visualConfig,rawMatrix:Xr(w)}),I={...k,cachedDataset:w,updatedAt:new Date().toISOString()};return await As(I),jt(I),Ua(e,I),c($),f(I),g(I.updatedAt),x("success"),w}else return x("success"),[]}catch(w){if(!S.current)return null;const $=w instanceof Error?w.message:"Failed to sync live sheet data";throw b($),x("error"),w}},[e,d,o,t]);u.useEffect(()=>{S.current=!0,C();let k=null;return a&&r&&r>0&&(k=window.setInterval(C,r)),()=>{S.current=!1,k&&clearInterval(k)}},[C,r,a]),u.useEffect(()=>{if(typeof window>"u")return;const k=w=>{const $=w;if($.detail&&$.detail.chartId===e){if($.detail.config){const I=$.detail.config;if(f(I),I.cachedDataset&&I.cachedDataset.length>0){const j=ns({chartId:e,title:I.titleOverride||"",subtitle:I.subtitleOverride,unit:I.unitOverride,chartType:I.defaultType,nodeId:t,visualConfig:I.visualConfig,rawMatrix:Xr(I.cachedDataset)});c(j),x("success");return}}C()}};return window.addEventListener(_a,k),()=>{window.removeEventListener(_a,k)}},[e,t,C]);const N=u.useMemo(()=>l?m?kn(l,m):l:null,[l,m]),_=u.useMemo(()=>!d&&!m?null:{...d||{},...m||{}},[d,m]);return{dataset:N,config:_,status:p,errorMessage:v,lastSyncedAt:y,reload:C,syncLiveSheet:T,setOverrideConfig:h}}const zx=Mi;function Mi(e){const{isDevMode:t}=Ne(),[s,r]=u.useState(()=>It(e,t)),[a,o]=u.useTransition(),i=u.useRef(s);i.current=s;const l=u.useRef(null);u.useEffect(()=>{const w=It(e,t);return i.current=w,r(w),ei(e,I=>{I.updatedAt!==l.current&&i.current.updatedAt!==I.updatedAt&&(i.current=I,o(()=>{r(I)}))},t)},[e,t]),u.useEffect(()=>{if(!t&&e){let w=!1;return fetch(`/api/public/node/${e}`).then($=>$.ok?$.json():null).then($=>{if(!(w||!$||$.nodeId!==e)){if($.chartDatasets&&typeof $.chartDatasets=="object")try{for(const[I,j]of Object.entries($.chartDatasets))if(j&&typeof j=="object"){const D=j;if(D.sanitizedCsvContent){const H=Ei(D.sanitizedCsvContent);H&&H.length>0&&typeof window<"u"&&window.localStorage&&window.localStorage.setItem(Do(I),JSON.stringify(H))}jt({chartId:I,nodeId:e||"access",sheetUrl:"",defaultType:D.chartType||"bar",titleOverride:D.title,subtitleOverride:D.subtitle,unitOverride:D.unit,visualConfig:D.visualConfig,updatedAt:D.asOfDate||new Date().toISOString(),updatedBy:"edge-prebake"})}}catch{}if($.canvas&&Array.isArray($.canvas.sections)&&($.canvas.updatedAt!==i.current.updatedAt||$.canvas.sections.length!==i.current.sections.length)){i.current=$.canvas;try{Rs($.canvas,{silent:!0})}catch{}o(()=>{r($.canvas)})}}}).catch(()=>{}),()=>{w=!0}}},[e,t]);const{pushAction:c}=Ir(),[d,f]=u.useState(null),m=u.useCallback(()=>{f(null)},[]),h=u.useCallback(w=>{const $=w(i.current),I=jr($,t);!I.ok&&t?f("Edit not saved — browser storage full."):I.ok&&f(null);const j=I.document;l.current=j.updatedAt,i.current=j,o(()=>{r(j)})},[t]),p=u.useCallback((w,$)=>{h(I=>_o(I,w,$))},[h]),x=u.useCallback((w,$,I)=>{h(j=>wo(j,w,$,I))},[h]),v=u.useCallback((w,$,I,j)=>{h(D=>So(D,w,$,I,j))},[h]),b=u.useCallback((w,$)=>{const I=sa(i.current,w);if(h(j=>kd(j,w,$)),I){const j="title"in I.item&&typeof I.item.title=="string"&&I.item.title?I.item.title:I.kind;c({type:I.kind==="section"?"canvas_remove_section":I.kind==="subsection"?"canvas_remove_subsection":"canvas_remove_leaf",description:`Delete ${I.kind} "${j}"`,undo:()=>{I.kind==="section"?p(I.item,I.index):I.kind==="subsection"?x(I.sectionId,I.item,I.index):v(I.sectionId,I.item,I.index,I.subsectionId)},redo:()=>b(w,$)})}},[h,c,p,x,v]),y=u.useCallback(w=>{const $=i.current,I=yo($.sections.length,$.nodeId),j=typeof w=="number"?w:$.sections.length;h(D=>_o(D,I,j)),c({type:"canvas_insert_section",description:`Add section "${I.title}"`,undo:()=>b(I.id),redo:()=>p(I,j)})},[h,c,b,p]),g=u.useCallback((w,$)=>{const I=i.current,j=I.sections.find(L=>L.id===w),D=wh(I.nodeId),H=typeof $=="number"?$:j?j.elements.length:0;h(L=>wo(L,w,D,H)),c({type:"canvas_insert_subsection",description:`Add subsection "${D.title}"`,undo:()=>b(D.id,w),redo:()=>x(w,D,H)})},[h,c,b,x]),S=u.useCallback((w,$,I,j)=>{h(D=>So(D,w,$,I,j)),c({type:"canvas_insert_leaf",description:`Add ${$.type} element`,undo:()=>b($.id,j||w),redo:()=>v(w,$,I,j)})},[h,c,b,v]),C=u.useCallback((w,$,I)=>{h(j=>Sd(j,w,$,I)),c({type:"canvas_move_item",description:`Move item ${$}`,undo:()=>C(w,$==="up"?"down":"up",I),redo:()=>C(w,$,I)})},[h,c]),T=u.useCallback((w,$,I)=>{const j=sa(i.current,w),D=j?j.subsectionId||j.sectionId:void 0,H=j?j.index:void 0;h(L=>Cd(L,w,$,I)),j&&D&&c({type:"canvas_relocate_item",description:"Relocate item",undo:()=>T(w,D,H),redo:()=>T(w,$,I)})},[h,c]),N=u.useCallback((w,$)=>{const I=sa(i.current,w),j={};if(I){const D=I.item;for(const H of Object.keys($))j[H]=D[H]}h(D=>Nd(D,w,$)),I&&c({type:"canvas_update_item",description:`Update ${I.kind} properties`,undo:()=>N(w,j),redo:()=>N(w,$)})},[h,c]),_=u.useCallback(()=>{o(()=>{const w=Qo(e,t);r(w)})},[e,t]),k=u.useCallback(async()=>(await ti(e)).success,[e]);return{document:s,isPending:a,addSection:y,addSubsection:g,addElement:S,restoreSection:p,restoreSubsection:x,restoreElement:v,moveItem:C,relocateItem:T,removeItem:b,updateItem:N,resetToDefault:_,deployToCloud:k,saveError:d,clearSaveError:m}}const qx="_sectionHeader_1tbu5_11",Vx="_sectionNumber_1tbu5_18",Wx="_sectionTitle_1tbu5_28",Kx="_extra_1tbu5_45",Jn={sectionHeader:qx,sectionNumber:Vx,sectionTitle:Wx,extra:Kx},Ha=u.memo(({title:e,titlePointId:t,number:s,defaultNumbered:r,subtitle:a,subtitlePointId:o,as:i="h2",id:l,accentColor:c,className:d,children:f,editTriggerId:m,onEdit:h})=>{const p=i,x=r!==void 0?r:s!=null,v=t?`${t}.isNumbered`:"",{text:b}=os(v,x?"true":"false"),y=v?b==="true":x,g=s??1,S=y?typeof g=="number"?String(g).padStart(2,"0"):String(g):null;return n.jsxs("div",{className:`${Jn.sectionHeader} ${d||""}`,style:{"--section-accent":c},children:[S&&n.jsxs("span",{className:Jn.sectionNumber,children:["Section ",S]}),t?n.jsx(gt,{pointId:t,defaultText:e,as:p,className:Jn.sectionTitle,ariaLabel:l,isSection:!0,isNumbered:y,defaultNumbered:x,editTriggerId:m,onEditText:h,children:C=>n.jsx(p,{id:l,className:Jn.sectionTitle,children:C})}):n.jsx(p,{id:l,className:Jn.sectionTitle,children:e}),f&&n.jsx("div",{className:Jn.extra,children:f})]})});Ha.displayName="SectionTitle";const Yx="_section_1iiq7_12",Xx="_sectionBody_1iiq7_22",Jx="_subsection_1iiq7_28",Zx="_subsectionBody_1iiq7_41",Qx="_galleryWrapper_1iiq7_53",hr={section:Yx,sectionBody:Xx,subsection:Jx,subsectionBody:Zx,galleryWrapper:Qx},Di=u.memo(({section:e,nodeId:t,nodeTitle:s,accentColor:r,isDevMode:a,className:o,computedNumber:i,children:l,onEdit:c})=>{const d=e.id.startsWith("sec-")?e.id:`sec-${e.id}`,f=e.titlePointId||`node.${t}.section.${e.id}.title`,m=i!==void 0?i!==null:e.isNumbered!==void 0?e.isNumbered:e.number!==void 0&&e.number!==null,h=e.isNumbered!==void 0?e.isNumbered:m,p=h?i!==void 0?i:e.number:null,x=e.title;return n.jsxs("section",{id:d,className:`${hr.section} ${o||""}`.trim(),"aria-label":x,"data-toc-title":x,"data-toc-number":p||void 0,"data-toc-numbered":h?"true":"false",children:[n.jsx(Ha,{number:p,defaultNumbered:h,title:x,titlePointId:f,as:"h2",accentColor:r,editTriggerId:e.id,onEdit:c}),n.jsx("div",{className:hr.sectionBody,children:l})]})});Di.displayName="CanvasSection";const Ri=u.memo(({subsection:e,nodeId:t,accentColor:s,isDevMode:r,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 n.jsxs("div",{id:l,className:`${hr.subsection} ${a||""}`.trim(),role:"region","aria-label":e.title,children:[n.jsx(Ha,{title:e.title,titlePointId:c,as:"h3",accentColor:s,defaultNumbered:!1,editTriggerId:e.id,onEdit:i}),n.jsx("div",{className:hr.subsectionBody,children:o})]})});Ri.displayName="CanvasSubsection";const eb="_textWrapper_hx1sj_10",tb="_bodyText_hx1sj_18",nb="_quoteWrapper_hx1sj_26",sb="_quoteText_hx1sj_32",rb="_photoCardContainer_hx1sj_43",ab="_photoCardBody_hx1sj_54",ob="_photoCard_hx1sj_43",ib="_photoButton_hx1sj_84",lb="_photoImage_hx1sj_105",cb="_photoCaption_hx1sj_118",db="_driveContainer_hx1sj_127",ub="_driveBadge_hx1sj_135",hb="_placeholderCard_hx1sj_161",mb="_placeholderIconWrapper_hx1sj_175",fb="_cameraIcon_hx1sj_187",pb="_placeholderText_hx1sj_192",gb="_chartContainer_hx1sj_198",ze={textWrapper:eb,bodyText:tb,quoteWrapper:nb,quoteText:sb,photoCardContainer:rb,photoCardBody:ab,photoCard:ob,photoButton:ib,photoImage:lb,photoCaption:cb,driveContainer:db,driveBadge:ub,placeholderCard:hb,placeholderIconWrapper:mb,cameraIcon:fb,placeholderText:pb,chartContainer:gb},Bi=u.memo(({element:e,accentColor:t,className:s,onEdit:r})=>{const a=e.as==="blockquote",o=a&&t?{borderLeftColor:t,color:t}:void 0;return n.jsx("div",{className:a?`${ze.quoteWrapper} ${s||""}`.trim():`${ze.textWrapper} ${s||""}`.trim(),style:o,children:n.jsx(gt,{pointId:"",defaultText:e.content,as:a?"blockquote":"p",className:a?ze.quoteText:ze.bodyText,editTriggerId:e.id,onEditText:r})})});Bi.displayName="CanvasText";function Su({isOpen:e,onClose:t,hash:s="#source"}){u.useEffect(()=>{if(!e)return;const r=window.location.href;window.history.pushState({modal:"source-lightbox"},"",s);const a=()=>{t()};return window.addEventListener("popstate",a),()=>{window.removeEventListener("popstate",a),window.location.hash===s&&window.history.replaceState(null,"",r)}},[e,t,s])}function vb(e){return!e||!e.closest?!1:!!e.closest('button, a, input, select, textarea, [role="tablist"], [data-no-swipe]')}function xb({onSwipeLeft:e,onSwipeRight:t,onSwipeDown:s,minDistance:r=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),f=(N,_,k)=>{if(a||vb(k)){c.current=!1;return}o.current=N,i.current=_,l.current=Date.now(),c.current=!0},m=(N,_)=>{if(!c.current||a){c.current=!1;return}if(c.current=!1,Date.now()-d.current<350)return;const k=N-o.current,w=_-i.current,$=Date.now()-l.current,I=Math.abs(k),j=Math.abs(w),H=$<280&&(I>28||j>28)?Math.min(r,30):r;if(w>H&&j>I*1.3){d.current=Date.now(),s==null||s();return}I>H&&I>j&&(d.current=Date.now(),k<0?e==null||e():t==null||t())},h=()=>{c.current=!1},p=u.useCallback(N=>{N.touches.length>0&&f(N.touches[0].clientX,N.touches[0].clientY,N.target)},[a]),x=u.useCallback(N=>{},[]),v=u.useCallback(N=>{N.changedTouches.length>0&&m(N.changedTouches[0].clientX,N.changedTouches[0].clientY)},[a,r,s,e,t]),b=u.useCallback(()=>{h()},[]),y=u.useCallback(N=>{N.pointerType==="mouse"&&N.button!==0||f(N.clientX,N.clientY,N.target)},[a]),g=u.useCallback(N=>{},[]),S=u.useCallback(N=>{N.pointerType==="mouse"&&N.button!==0||m(N.clientX,N.clientY)},[a,r,s,e,t]),C=u.useCallback(()=>{h()},[]),T=u.useCallback(()=>Date.now()-d.current<350,[]);return{onTouchStart:p,onTouchMove:x,onTouchEnd:v,onTouchCancel:b,onPointerDown:y,onPointerMove:g,onPointerUp:S,onPointerCancel:C,wasSwipeJustTriggered:T}}function bb(e,t){const[s,r]=u.useState(e),[a,o]=u.useState(e?"loading":"idle"),[i,l]=u.useState(0);u.useEffect(()=>{r(e)},[e]),u.useEffect(()=>{if(!s){o("idle");return}let d=!0;o("loading");const f=new Image;if(f.referrerPolicy="no-referrer",f.src=s,f.complete&&f.naturalWidth>0){o("loaded");return}return f.onload=()=>{d&&o("loaded")},f.onerror=()=>{d&&(t&&s!==t?r(t):o("error"))},()=>{d=!1,f.onload=null,f.onerror=null}},[s,t,i]);const c=u.useCallback(()=>{r(e),l(d=>d+1)},[e]);return{status:a,isLoading:a==="loading",isLoaded:a==="loaded",isError:a==="error",resolvedSrc:s,retry:c}}const yb="_imageContainer_ofyas_12",_b="_skeletonShimmer_ofyas_21",wb="_image_ofyas_12",Sb="_imageLoaded_ofyas_59",Cb="_errorFallback_ofyas_63",kb="_errorIcon_ofyas_79",Nb="_errorMessage_ofyas_84",jb="_retryButton_ofyas_92",an={imageContainer:yb,skeletonShimmer:_b,image:wb,imageLoaded:Sb,errorFallback:Cb,errorIcon:kb,errorMessage:Nb,retryButton:jb},Cu=({src:e,fallbackSrc:t,srcSet:s,sizes:r,alt:a="",className:o="",imageClassName:i="",aspectRatio:l,objectFit:c="cover",showRetry:d=!0,loading:f="lazy",decoding:m="async",onLoad:h,onError:p})=>{const{status:x,isLoading:v,isLoaded:b,isError:y,resolvedSrc:g,retry:S}=bb(e,t);u.useEffect(()=>{b&&h&&h()},[b,h]),u.useEffect(()=>{y&&p&&p()},[y,p]);const C=l?{aspectRatio:l}:{};return n.jsxs("div",{className:`${an.imageContainer} ${o}`,style:C,"data-status":x,children:[v&&n.jsx("div",{className:an.skeletonShimmer,"aria-hidden":"true"}),y&&n.jsxs("div",{className:an.errorFallback,role:"alert",children:[n.jsx("span",{className:an.errorIcon,"aria-hidden":"true",children:"⚠"}),n.jsx("p",{className:an.errorMessage,children:"Failed to load photo"}),d&&n.jsx("button",{type:"button",className:an.retryButton,onClick:T=>{T.stopPropagation(),S()},"aria-label":"Retry loading photograph",children:"Retry"})]}),g&&n.jsx("img",{src:g,srcSet:s,sizes:r,alt:a,referrerPolicy:"no-referrer",draggable:!1,className:`${an.image} ${b?an.imageLoaded:""} ${i}`,style:{objectFit:c},loading:f,decoding:m})]})},Tb="_stripContainer_1rgdz_11",Ib="_thumbButton_1rgdz_38",Ab="_thumbActive_1rgdz_76",Eb="_thumbImage_1rgdz_90",$b="_thumbFallback_1rgdz_98",Ks={stripContainer:Tb,thumbButton:Ib,thumbActive:Ab,thumbImage:Eb,thumbFallback:$b},Lb=({items:e,currentIndex:t,accentColor:s,onNavigate:r})=>{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 f=u.useCallback((h,p)=>{p&&!c[h]?d(x=>({...x,[h]:!0})):o(x=>({...x,[h]:!0}))},[c]),m=u.useCallback((h,p)=>{h.key==="ArrowRight"?(h.preventDefault(),h.stopPropagation(),p<e.length-1&&r(p+1)):h.key==="ArrowLeft"?(h.preventDefault(),h.stopPropagation(),p>0&&r(p-1)):h.key==="Home"?(h.preventDefault(),h.stopPropagation(),r(0)):h.key==="End"&&(h.preventDefault(),h.stopPropagation(),r(e.length-1))},[e.length,r]);return e.length<=1?null:n.jsx("div",{ref:i,role:"tablist","aria-label":"Available photographs",className:Ks.stripContainer,onClick:h=>h.stopPropagation(),children:e.map((h,p)=>{var _,k,w,$;const x=p===t,v=h.driveFileId||((_=h.id)!=null&&_.startsWith("drive-")?h.id.replace(/^drive-/,""):"")||$e.extractDriveFileId(((k=h.photo)==null?void 0:k.src)||h.imageSrc||""),b=h.thumbnailUrl||((w=h.photo)==null?void 0:w.src)||h.imageSrc||"",y=v&&!b.includes("/api/media/drive/")?$e.buildEdgeMediaUrl(v,{width:320}):b,g=v?`https://drive.google.com/thumbnail?id=${encodeURIComponent(v)}&sz=w320`:void 0,C=c[p]&&g?g:y,T=(($=h.photo)==null?void 0:$.caption)||h.title||`Photo ${p+1}`,N=a[p];return n.jsx("button",{ref:x?l:null,type:"button",role:"tab","aria-selected":x,"aria-label":`Photo ${p+1} of ${e.length}: ${T}`,className:`${Ks.thumbButton} ${x?Ks.thumbActive:""}`,onClick:I=>{I.stopPropagation(),r(p)},onKeyDown:I=>m(I,p),style:x&&s?{"--lightbox-thumb-active-border":s}:void 0,children:C&&!N?n.jsx("img",{src:C,alt:"","aria-hidden":"true",loading:"lazy",decoding:"async",draggable:!1,className:Ks.thumbImage,onError:()=>f(p,g)}):n.jsx("span",{className:Ks.thumbFallback,"aria-hidden":"true",children:p+1})},h.id||`thumb-${p}`)})})},Mb="_backdrop_3coip_12",Db="_srOnly_3coip_37",Rb="_headerBar_3coip_53",Bb="_chromeHidden_3coip_67",Pb="_counterPill_3coip_73",Ob="_closeButton_3coip_87",Fb="_closeIcon_3coip_119",Ub="_stage_3coip_128",Gb="_stageZoomed_3coip_143",Hb="_imageFrame_3coip_147",zb="_imageFrameZoomed_3coip_159",qb="_lightboxImageWrapper_3coip_163",Vb="_lightboxImage_3coip_163",Wb="_navButton_3coip_192",Kb="_navPrev_3coip_221",Yb="_navNext_3coip_225",Xb="_navIcon_3coip_243",Jb="_footerBar_3coip_272",Zb="_footerHidden_3coip_286",Qb="_photoStripWrapper_3coip_292",ey="_footerTopRow_3coip_299",ty="_metadataBlock_3coip_307",ny="_titleRow_3coip_313",sy="_photoTitle_3coip_320",ry="_sourceGroup_3coip_330",ay="_driveButton_3coip_336",oy="_driveIcon_3coip_369",we={backdrop:Mb,srOnly:Db,headerBar:Rb,chromeHidden:Bb,counterPill:Pb,closeButton:Ob,closeIcon:Fb,stage:Ub,stageZoomed:Gb,imageFrame:Hb,imageFrameZoomed:zb,lightboxImageWrapper:qb,lightboxImage:Vb,navButton:Wb,navPrev:Kb,navNext:Yb,navIcon:Xb,footerBar:Jb,footerHidden:Zb,photoStripWrapper:Qb,footerTopRow:ey,metadataBlock:ty,titleRow:ny,photoTitle:sy,sourceGroup:ry,driveButton:ay,driveIcon:oy},ku=({isOpen:e,items:t,currentIndex:s,driveFolderUrl:r,accentColor:a,onClose:o,onNavigate:i,onEditSource:l,onEditPhoto:c})=>{var K,Q,X,ee;const[d,f]=u.useState(!1),[m,h]=u.useState(!0),{isDevMode:p,isDesktop:x}=Ne(),v=p&&x,b=u.useRef(null),y=u.useRef(null),g=u.useRef(null),S=u.useRef(0);Su({isOpen:e,onClose:o});const C=t.length>0,T=Math.max(0,Math.min(s,Math.max(0,t.length-1))),N=C?t[T]:null;u.useEffect(()=>{f(!1)},[T]);const _=u.useCallback(()=>{T<t.length-1&&i(T+1)},[T,t.length,i]),k=u.useCallback(()=>{T>0&&i(T-1)},[T,i]),{onTouchStart:w,onTouchMove:$,onTouchEnd:I,onTouchCancel:j,onPointerDown:D,onPointerMove:H,onPointerUp:L,onPointerCancel:U,wasSwipeJustTriggered:G}=xb({onSwipeLeft:_,onSwipeRight:k,onSwipeDown:o,minDistance:45,disabled:d});u.useEffect(()=>{if(!e)return;b.current=document.activeElement;const V=window.innerWidth-document.documentElement.clientWidth,J=document.body.style.overflow,Y=document.body.style.paddingRight;document.body.style.overflow="hidden",V>0&&(document.body.style.paddingRight=`${V}px`);const te=window.setTimeout(()=>{var oe;(oe=y.current)==null||oe.focus()},50);return()=>{window.clearTimeout(te),document.body.style.overflow=J,document.body.style.paddingRight=Y,b.current&&typeof b.current.focus=="function"&&b.current.focus()}},[e]),u.useEffect(()=>{if(!e)return;const V=J=>{J.key==="Escape"?(J.preventDefault(),J.stopPropagation(),J.stopImmediatePropagation(),o()):J.key==="ArrowRight"?(J.preventDefault(),_()):J.key==="ArrowLeft"&&(J.preventDefault(),k())};return window.addEventListener("keydown",V,!0),()=>{window.removeEventListener("keydown",V,!0)}},[e,_,k,o]);const z=u.useRef(null),q=u.useCallback(()=>{h(!0),z.current&&window.clearTimeout(z.current),z.current=window.setTimeout(()=>{h(!1)},3500)},[]);u.useEffect(()=>{if(e)return q(),()=>{z.current&&window.clearTimeout(z.current)}},[e,q,T]);const P=u.useCallback(V=>{if(G())return;const J=V.target;if(J.closest("button")||J.closest("a"))return;const Y=Date.now(),te=Y-S.current;S.current=Y,te<300?f(oe=>!oe):h(oe=>{const B=!oe;return B?q():z.current&&window.clearTimeout(z.current),B})},[q,G]);if(!e||!N)return null;const F=((K=N.photo)==null?void 0:K.src)||N.imageSrc||"",R=((Q=N.photo)==null?void 0:Q.alt)||N.title,W=((X=N.photo)==null?void 0:X.caption)||N.title,se=N.driveFileId||((ee=N.id)!=null&&ee.startsWith("drive-")?N.id.replace(/^drive-/,""):"")||$e.extractDriveFileId(F),re=se&&!F.includes("/api/media/drive/")?$e.buildEdgeMediaUrl(se,{width:1600}):F,le=se?`https://drive.google.com/thumbnail?id=${encodeURIComponent(se)}&sz=w1600`:void 0,M=n.jsxs("div",{ref:g,role:"dialog","aria-modal":"true","aria-label":"Photo Lightbox",className:we.backdrop,onMouseMove:q,onPointerMove:V=>{q(),H(V)},onPointerDown:V=>{q(),D(V)},onPointerUp:L,onPointerCancel:U,onTouchStart:V=>{q(),w(V)},onTouchMove:V=>{q(),$(V)},onTouchEnd:I,onTouchCancel:j,style:a?{"--lightbox-accent":a}:void 0,children:[n.jsxs("div",{"aria-live":"polite",className:we.srOnly,children:["Showing photo ",T+1," of ",t.length,": ",W]}),n.jsxs("header",{className:`${we.headerBar} ${m?"":we.chromeHidden}`,children:[t.length>1?n.jsxs("div",{className:we.counterPill,children:[n.jsx("span",{children:T+1}),n.jsx("span",{children:"/"}),n.jsx("span",{children:t.length})]}):n.jsx("div",{}),n.jsx("button",{ref:y,type:"button",className:we.closeButton,onClick:o,"aria-label":"Close photo lightbox",children:n.jsx("span",{className:we.closeIcon,"aria-hidden":"true",children:"✕"})})]}),n.jsxs("div",{className:`${we.stage} ${d?we.stageZoomed:""}`,onClick:P,children:[T>0&&n.jsx("button",{type:"button",className:`${we.navButton} ${we.navPrev} ${m?"":we.chromeHidden}`,onClick:V=>{V.stopPropagation(),k()},"aria-label":"Previous photograph",children:n.jsx("span",{className:we.navIcon,"aria-hidden":"true",children:"‹"})}),T<t.length-1&&n.jsx("button",{type:"button",className:`${we.navButton} ${we.navNext} ${m?"":we.chromeHidden}`,onClick:V=>{V.stopPropagation(),_()},"aria-label":"Next photograph",children:n.jsx("span",{className:we.navIcon,"aria-hidden":"true",children:"›"})}),n.jsx("div",{className:`${we.imageFrame} ${d?we.imageFrameZoomed:""}`,children:n.jsx("div",{className:we.lightboxImageWrapper,children:n.jsx(Cu,{src:re,fallbackSrc:le,alt:R,className:we.lightboxImage,imageClassName:we.lightboxImage,objectFit:"contain",loading:"eager",decoding:"async",showRetry:!0})})})]}),n.jsxs("footer",{className:`${we.footerBar} ${m?"":we.footerHidden}`,children:[t.length>1&&n.jsx("div",{className:we.photoStripWrapper,children:n.jsx(Lb,{items:t,currentIndex:T,accentColor:a,onNavigate:i})}),n.jsxs("div",{className:we.footerTopRow,children:[n.jsx("div",{className:we.metadataBlock,children:n.jsxs("div",{className:we.titleRow,children:[n.jsx("h3",{className:we.photoTitle,children:W}),v&&c&&n.jsx(he,{type:"button",variant:"admin",size:"xs",onClick:V=>{V.stopPropagation(),c(N)},title:"Edit photo details","aria-label":"Edit photo details",children:"✎ Edit"})]})}),n.jsxs("div",{className:we.sourceGroup,children:[r&&n.jsxs("a",{href:r,target:"_blank",rel:"noopener noreferrer",className:we.driveButton,"aria-label":"Open Google Drive source",children:[n.jsx("span",{children:"Source"}),n.jsx("span",{className:we.driveIcon,"aria-hidden":"true",children:"↗"})]}),v&&l&&n.jsx(he,{type:"button",variant:"admin",size:"xs",onClick:V=>{V.stopPropagation(),l()},title:"Edit Google Drive source","aria-label":"Edit Google Drive source",children:"✎ Edit"})]})]})]})]});return typeof document>"u"?M:fr.createPortal(M,document.body)},iy=$e.baselineSourcesRaw;function Qt(e){return!e||typeof e!="string"?"":e.trim().toLowerCase().replace(/^node-/,"")}function ly(e){const t=Qt(e);if(!t)return null;const s=iy[t]??null,r=`source.${t}.source`,a=zo(r,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??(s==null?void 0:s.folderUrl)??"",folderTitle:i??(s==null?void 0:s.folderTitle)??"Official Google Drive Folder",description:s==null?void 0:s.description,lastVerified:s==null?void 0:s.lastVerified}}return s}const Nu=/^https:\/\/(?:drive\.google\.com\/(?:drive\/(?:u\/\d+\/)?folders\/|open\?id=))([a-zA-Z0-9_-]{15,})/;function cy(e){return!e||typeof e!="string"?!1:Nu.test(e.trim())}const mr=e=>(e||me.getStorageNamespace())+"_evidence_cache_v2",Pi=mr(),wa="engine-evidence-source-change",dy=$e.baselineSourcesRaw;let _t=null,Ys=null;function Ro(){const e={};for(const[t,s]of Object.entries(dy))e[t]={pointId:s.pointId,folderUrl:s.folderUrl,folderTitle:s.folderTitle,description:s.description,updatedBy:"Coordinator",lastVerified:s.lastVerified??new Date().toISOString().split("T")[0],createdAt:"2025-10-01T00:00:00Z"};return e}function za(e){if(!Array.isArray(e.syncedPhotos)||e.syncedPhotos.length===0)return e;let t=!1;const s=e.syncedPhotos.map(r=>{var c,d,f,m,h,p,x,v,b,y,g;if(!(r.fullImageUrl&&r.fullImageUrl.includes("/drive-storage/")||r.thumbnailUrl&&r.thumbnailUrl.includes("/drive-storage/")||r.imageSrc&&r.imageSrc.includes("/drive-storage/")||((c=r.photo)==null?void 0:c.src)&&r.photo.src.includes("/drive-storage/")))return r;t=!0;const o=r.driveFileId||((d=r.id)!=null&&d.startsWith("drive-")?r.id.replace(/^drive-/,""):"");if(!o)return r;const i=`https://drive.google.com/thumbnail?id=${encodeURIComponent(o)}&sz=w1600`,l=`https://drive.google.com/thumbnail?id=${encodeURIComponent(o)}&sz=w320`;return{...r,thumbnailUrl:(f=r.thumbnailUrl)!=null&&f.includes("/drive-storage/")?l:r.thumbnailUrl,fullImageUrl:(m=r.fullImageUrl)!=null&&m.includes("/drive-storage/")?i:r.fullImageUrl,imageSrc:(h=r.imageSrc)!=null&&h.includes("/drive-storage/")?i:r.imageSrc,photo:{src:(x=(p=r.photo)==null?void 0:p.src)!=null&&x.includes("/drive-storage/")?i:((v=r.photo)==null?void 0:v.src)||i,alt:((b=r.photo)==null?void 0:b.alt)||"",caption:(y=r.photo)==null?void 0:y.caption,showCaption:(g=r.photo)==null?void 0:g.showCaption}}});return t?{...e,syncedPhotos:s}:e}function ju(){const e=Se();if(!e)return null;try{const t=e.getItem(mr());if(!t)return null;const s=JSON.parse(t),r={};for(const[a,o]of Object.entries(s))r[a]=za(o);return r}catch{return null}}function Tu(e){const t=Se();if(t)try{t.setItem(mr(),JSON.stringify(e))}catch{try{const s={};for(const[r,a]of Object.entries(e))s[r]={...a,syncedPhotos:void 0};t.setItem(mr(),JSON.stringify(s))}catch{}}}function uy(e,t){if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(wa,{detail:{pointId:e,record:t}}))}catch{}}function hy(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 za(t)}async function Oi(e){if(_t!==null&&!(e!=null&&e.forceRefresh))return _t;if(Ys&&!(e!=null&&e.forceRefresh))return Ys;Ys=(async()=>{const t=Ro(),s=ju();s&&Object.assign(t,s);const r=qe();if(r)try{const a=typeof AbortController<"u"?new AbortController:null,o=a?setTimeout(()=>a.abort(),6e3):null,i=await fetch(`${r.url}/rest/v1/engine_sources?select=*`,{method:"GET",headers:{apikey:r.anonKey,Authorization:`Bearer ${r.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=hy(c);t[d.pointId]=d}Tu(t)}}}catch{}return _t=t,_t})();try{return await Ys}finally{Ys=null}}async function qa(e){const t=Qt(e);return t?(await Oi())[t]??null:null}function vs(e){const t=Qt(e);if(!t)return null;if(_t&&_t[t])return _t[t];const s=ju();return s&&s[t]?(_t||(_t={...Ro(),...s}),s[t]):Ro()[t]??null}async function Es(e,t){const s=Qt(e.pointId);if(!s)throw new Error("Invalid pointId: cannot be empty");const r=new Date().toISOString(),a=await qa(s),o=za({pointId:s,folderUrl:e.folderUrl,folderTitle:e.folderTitle,description:e.description??(a==null?void 0:a.description),updatedBy:e.updatedBy??"Coordinator",lastVerified:r,createdAt:(a==null?void 0:a.createdAt)??r,syncedPhotos:e.syncedPhotos??(a==null?void 0:a.syncedPhotos)}),i=_t??await Oi();i[s]=o,_t=i,Tu(i),uy(s,o);const l=qe();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 my(){_t=null;const e=Se();if(e)try{e.removeItem(Pi)}catch{}}const ao={};function Fi(e){if(!e||typeof e!="string")return null;const t=e.trim().match(Nu);return t&&t[1]?t[1]:null}function fy(){var t;const e=typeof{url:typeof document>"u"?require("url").pathToFileURL(__filename).href:Le&&Le.tagName.toUpperCase()==="SCRIPT"&&Le.src||new URL("folio.cjs",document.baseURI).href}<"u"&&(ao==null?void 0:ao.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 Iu(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 Nc(e){var r,a,o,i,l;const t=Fi(e);if(!t)return{status:"invalid_format",message:"Invalid URL format. Please paste a Google Drive folder link."};const s=fy();if(s)try{const c=typeof AbortController<"u"?new AbortController:null,d=c?setTimeout(()=>c.abort(),6e3):null,f=Iu(e),m={Accept:"application/json"};f&&(m["X-Goog-Drive-Resource-Keys"]=`${t}/${f}`);const h=`https://www.googleapis.com/drive/v3/files/${encodeURIComponent(t)}?fields=id,name,mimeType&supportsAllDrives=true&includeItemsFromAllDrives=true&key=${encodeURIComponent(s)}`,p=await fetch(h,{method:"GET",headers:m,signal:c==null?void 0:c.signal});if(d&&clearTimeout(d),p.ok){const g=await p.json();return g.mimeType==="application/vnd.google-apps.folder"?{status:"valid",folderId:g.id,folderTitle:g.name,mimeType:g.mimeType,message:`Publicly accessible folder verified: "${g.name}"`}:{status:"not_a_folder",folderId:g.id,folderTitle:g.name,mimeType:g.mimeType,message:`Notice: This link points to an individual file ("${g.name}"), not a folder archive.`}}const x=await p.json().catch(()=>null),v=((o=(a=(r=x==null?void 0:x.error)==null?void 0:r.errors)==null?void 0:a[0])==null?void 0:o.reason)||((i=x==null?void 0:x.error)==null?void 0:i.status)||"",b=((l=x==null?void 0:x.error)==null?void 0:l.message)||p.statusText||"";if(v==="API_KEY_HTTP_REFERRER_BLOCKED"||v==="ipRefererBlocked"||v==="accessNotConfigured"||v==="SERVICE_DISABLED"||v==="keyInvalid"||v==="dailyLimitExceeded"||v==="rateLimitExceeded"||v==="userRateLimitExceeded"||b.toLowerCase().includes("referrer")||b.toLowerCase().includes("api key")||b.toLowerCase().includes("quota")||b.toLowerCase().includes("blocked")){const g=b?`[API Key: ${b}]`:`[API Reason: ${v}]`;return console.warn("[DriveVerification] Google Drive API Key or Referrer restriction detected:",b||v),{status:"unverified",folderId:t,message:`Folder format is valid, but Google Drive API reported a key/referrer issue ${g}. Ensure access is set to "Anyone with the link can view".`,apiError:{statusCode:p.status,reason:v,rawMessage:b}}}if(p.status===404)try{const g=`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(s)}`;if((await fetch(g,{method:"GET",headers:m})).ok)return{status:"valid",folderId:t,message:"Publicly accessible folder verified."}}catch{}if(p.status===403){const g=b?` [HTTP 403: ${b}]`:" [HTTP 403: Forbidden]";return{status:"restricted",folderId:t,message:`Folder is restricted or requires login${g}. Set General Access to "Anyone with the link can view".`,apiError:{statusCode:403,reason:v,rawMessage:b}}}if(p.status===404){const g=b?` [HTTP 404: ${b}]`:" [HTTP 404: Not Found]";return{status:"restricted",folderId:t,message:`Folder not found or inaccessible via API${g}. Set General Access to "Anyone with the link can view".`,apiError:{statusCode:404,reason:v,rawMessage:b}}}return{status:"unverified",folderId:t,message:`Folder link format is valid, but Google Drive API returned HTTP ${p.status} (${b||"Unexpected error"}). Ensure access is set to "Anyone with the link can view".`,apiError:{statusCode:p.status,reason:v,rawMessage:b}}}catch(c){const f=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: ${f}]. Ensure access is set to "Anyone with the link can view".`,apiError:{rawMessage:f}}}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 oo={};function py(){var t;const e=typeof{url:typeof document>"u"?require("url").pathToFileURL(__filename).href:Le&&Le.tagName.toUpperCase()==="SCRIPT"&&Le.src||new URL("folio.cjs",document.baseURI).href}<"u"&&(oo==null?void 0:oo.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 gy(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 vy(e,t){return e.localeCompare(t,void 0,{numeric:!0,sensitivity:"base"})}function xy(e,t,s=!1){return s&&t?$e.buildEdgeMediaUrl(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 by(e,t,s=!1){return s&&t?$e.buildEdgeMediaUrl(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 yy(e,t,s){if(e.length===0&&t.length===0)return{items:[],stats:{added:0,removed:0,retained:0,total:0,hasChanged:!1}};const r=new Map;for(let m=0;m<e.length;m++)r.set(e[m].driveFileId,e[m]);const a=[...t].sort((m,h)=>vy(m.name,h.name)),o=new Set,i=[];let l=0,c=0;for(let m=0;m<a.length;m++){const h=a[m];o.add(h.id);const p=r.get(h.id),x=by(h.thumbnailLink,h.id),v=xy(h.thumbnailLink,h.id);if(p)c++,i.push({...p,orderIndex:m,thumbnailUrl:x,fullImageUrl:v,imageSrc:v,photo:{...p.photo,src:v,alt:p.title,caption:p.title,showCaption:!0}});else{l++;const b=gy(h.name),y=h.createdTime?h.createdTime.split("T")[0]:"2026-10-09";i.push({id:`drive-${h.id}`,pointId:s,driveFileId:h.id,originalFileName:h.name,title:b,category:"MOV Photo",date:y,dateStamp:y,imageSrc:v,thumbnailUrl:x,fullImageUrl:v,photo:{src:v,alt:b,caption:b,showCaption:!0},orderIndex:m,isCustomTitle:!1})}}let d=0;for(let m=0;m<e.length;m++)o.has(e[m].driveFileId)||d++;const f=l>0||d>0||i.length!==e.length;return{items:i,stats:{added:l,removed:d,retained:c,total:i.length,hasChanged:f}}}async function _y(e){var v,b,y,g,S;const t=e?e.trim():"",s=t.includes("/")?Fi(t):t;if(!s)throw new Error("Invalid Google Drive folder link or folder ID.");const r=py();if(!r)throw new Error("Google Drive API Key is not configured in VITE_GOOGLE_DRIVE_API_KEY.");const a=Iu(t),o={Accept:"application/json"};a&&(o["X-Goog-Drive-Resource-Keys"]=`${s}/${a}`);const i=`'${s}' 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(r)}`,d=await fetch(c,{method:"GET",headers:o});if(!d.ok){const C=await d.json().catch(()=>null),T=((y=(b=(v=C==null?void 0:C.error)==null?void 0:v.errors)==null?void 0:b[0])==null?void 0:y.reason)||((g=C==null?void 0:C.error)==null?void 0:g.status)||"",N=((S=C==null?void 0:C.error)==null?void 0:S.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?T==="API_KEY_HTTP_REFERRER_BLOCKED"||T==="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 m=(await d.json()).files??[],h=C=>!!(C.mimeType&&C.mimeType.startsWith("image/")||/\.(jpe?g|png|webp|gif|heic|tiff|bmp|avif)$/i.test(C.name)),p=m.filter(h),x=m.filter(C=>C.mimeType==="application/vnd.google-apps.folder");if(x.length>0)try{const C=x.slice(0,5).map(async N=>{const _=`'${N.id}' in parents and trashed = false`,k=`https://www.googleapis.com/drive/v3/files?q=${encodeURIComponent(_)}&fields=${encodeURIComponent(l)}&pageSize=50&supportsAllDrives=true&includeItemsFromAllDrives=true&key=${encodeURIComponent(r)}`,w=await fetch(k,{method:"GET",headers:o});return w.ok?((await w.json()).files??[]).filter(h):[]}),T=await Promise.all(C);for(const N of T)p.push(...N)}catch{}return p}async function Au(e,t,s=[],r){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 _y(o),l=yy(s,i,a),c=vs(a)||await qa(a),d=(c==null?void 0:c.folderTitle)||"Official Google Drive Folder",f=c==null?void 0:c.description,m=await Es({pointId:a,folderUrl:o,folderTitle:d,description:f,syncedPhotos:l.items,updatedBy:"Drive Sync Engine"},r);return{items:l.items,stats:l.stats,source:m}}const wy="_subtitle_iysop_8",Sy="_body_iysop_16",Cy="_fieldGroup_iysop_22",ky="_label_iysop_28",Ny="_input_iysop_36",jy="_inputInvalid_iysop_60",Ty="_urlInputRow_iysop_64",Iy="_feedbackText_iysop_70",Ay="_feedbackSuccess_iysop_77",Ey="_feedbackChecking_iysop_84",$y="_errorAlert_iysop_92",Ly="_actions_iysop_102",My="_actionAuxiliary_iysop_110",Dy="_actionPrimary_iysop_115",Ry="_testLink_iysop_122",Ve={subtitle:wy,body:Sy,fieldGroup:Cy,label:ky,input:Ny,inputInvalid:jy,urlInputRow:Ty,feedbackText:Iy,feedbackSuccess:Ay,feedbackChecking:Ey,errorAlert:$y,actions:Ly,actionAuxiliary:My,actionPrimary:Dy,testLink:Ry},Ui=({isOpen:e,pointId:t,initialTitle:s="",initialUrl:r="",onClose:a,onSuccess:o})=>{const{isDevMode:i,isDesktop:l}=Ne(),[c,d]=u.useState(s),[f,m]=u.useState(r),[h,p]=u.useState(!1),[x,v]=u.useState("idle"),[b,y]=u.useState(null),[g,S]=u.useState(null),[C,T]=u.useState(null),N=u.useRef(null);u.useEffect(()=>{e&&(!i||!l)&&a()},[e,i,l,a]),u.useEffect(()=>{if(e){const L=!r||r.trim().length===0;d(L||(s==="Official Google Drive Folder"||s==="Evidence Folder"||s==="Attach Drive Folder")?"":s),m(r),p(!1),v("idle"),y(null),S(null);const G=setTimeout(()=>{var z;(z=N.current)==null||z.focus()},50);return()=>clearTimeout(G)}},[e,s,r]);const _=u.useMemo(()=>e?c.trim()!==s.trim()||f.trim()!==r.trim():!1,[e,c,f,s,r]);Fa(e&&_,`link-folder-${t}`);const k=f.trim(),w=cy(k),$=k.length>0&&!w,I=w&&!h,j=u.useCallback(async()=>{var L;if(!(!w||!k)){p(!0),v("verifying"),S(null);try{const U=await Nc(k);y(U),U.status==="valid"?!c.trim()&&U.folderTitle&&d(U.folderTitle):U.status==="restricted"||U.status==="not_a_folder"?S(U.message||null):U.status==="unverified"&&((L=U.message)!=null&&L.includes("["))&&S(U.message)}catch{}finally{p(!1),v("idle")}}},[w,k,c]),D=u.useCallback(async()=>{if(!(!w||!k||h)){p(!0),S(null);try{const L=Fi(k);let U=b;if((!U||U.folderId!==L)&&(v("verifying"),U=await Nc(k),y(U)),U.status==="not_a_folder"||U.status==="invalid_format"){S(U.message||"Invalid folder format."),p(!1),v("idle");return}if(U.status==="restricted"){S(U.message||'Access restricted. Set Google Drive folder permissions to "Anyone with the link can view".'),p(!1),v("idle");return}v("saving");const G=c.trim()||U.folderTitle||"Official Google Drive Folder";await Es({pointId:t,folderUrl:k,folderTitle:G,updatedBy:"Administrator"});try{Au(t,k,[])}catch{}T("Folder link updated successfully."),o==null||o(k,G),a()}catch(L){S(L instanceof Error?L.message:"Failed to update folder link.")}finally{p(!1),v("idle")}}},[w,k,h,b,c,t,o,a]),H=C?n.jsx(Ot,{message:C,type:"success",onDismiss:()=>T(null)}):null;return n.jsxs(n.Fragment,{children:[n.jsxs(ut,{isOpen:e,onClose:a,onConfirm:I?()=>D():void 0,title:"Link Folder",maxWidth:"480px",role:"dialog","aria-modal":"true",ariaLabelledBy:"link-folder-title",ariaDescribedBy:"link-folder-desc",children:[n.jsx("p",{id:"link-folder-desc",className:Ve.subtitle,children:"Attach a Google Drive folder for photos and documents."}),n.jsxs("div",{className:Ve.body,children:[n.jsxs("div",{className:Ve.fieldGroup,children:[n.jsx("label",{htmlFor:"folder-title-input",className:Ve.label,children:"Folder Label"}),n.jsx("input",{ref:N,id:"folder-title-input",type:"text",className:Ve.input,value:c,onChange:L=>d(L.target.value),placeholder:"e.g. Media & Documentation Folder",disabled:h})]}),n.jsxs("div",{className:Ve.fieldGroup,children:[n.jsx("label",{htmlFor:"folder-url-input",className:Ve.label,children:"Google Drive Folder URL"}),n.jsxs("div",{className:Ve.urlInputRow,children:[n.jsx("input",{id:"folder-url-input",type:"url",className:`${Ve.input} ${$?Ve.inputInvalid:""}`,value:f,onChange:L=>{m(L.target.value),y(null),S(null)},placeholder:"https://drive.google.com/drive/folders/...",disabled:h}),n.jsx(he,{variant:"secondary",size:"xs",type:"button",onClick:j,disabled:!w||h,title:"Verify public access via Google Drive API",children:x==="verifying"&&h?"Checking...":"Verify"})]}),x==="verifying"&&h&&n.jsx("div",{className:Ve.feedbackChecking,children:"Checking Google Drive permissions..."}),x!=="verifying"&&(b==null?void 0:b.status)==="valid"&&n.jsxs("div",{className:Ve.feedbackSuccess,children:["✓ Public folder verified (",b.folderTitle,")"]}),x!=="verifying"&&$&&n.jsx("div",{className:Ve.feedbackText,children:"Please enter a valid Google Drive folder link."})]}),g&&n.jsx("div",{className:Ve.errorAlert,role:"alert",children:g}),n.jsxs("div",{className:Ve.actions,children:[n.jsx("div",{className:Ve.actionAuxiliary,children:w&&n.jsx("a",{href:k,target:"_blank",rel:"noopener noreferrer",className:Ve.testLink,title:"Open folder in a new tab to verify access",children:"Test Link ↗"})}),n.jsxs("div",{className:Ve.actionPrimary,children:[n.jsx(he,{variant:"secondary",size:"sm",type:"button",onClick:a,disabled:h,children:"Cancel"}),n.jsx(he,{variant:"primary",size:"sm",type:"button",onClick:()=>D(),disabled:!I,children:x==="verifying"?"Verifying...":x==="saving"?"Saving...":"Save"})]})]})]})]}),H]})},Gi=u.memo(({element:e,accentColor:t,isDevMode:s,className:r,onEdit:a})=>{const{isDevMode:o,isDesktop:i}=Ne(),l=!!(s||o&&i),c=e,[d,f]=u.useState(!1),[m,h]=u.useState(!1);u.useEffect(()=>{!l&&m&&h(!1)},[l,m]);const p=!!(c.src&&c.src.trim().length>0),x=!!(c.driveUrl&&c.driveUrl.trim().length>0),v=u.useMemo(()=>$e.extractDriveFileId(c.rawDriveUrl||"")||$e.extractDriveFileId(c.src||"")||$e.extractDriveFileId(c.driveUrl||"")||null,[c.rawDriveUrl,c.src,c.driveUrl]),b=u.useMemo(()=>{if(c.srcSet)return c.srcSet;if(v)return $e.buildEdgeSrcSet(v)},[c.srcSet,v]),g=c.sizes||"(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 800px",S=u.useMemo(()=>c.src?v&&!c.src.includes("/api/media/drive/")?$e.buildEdgeMediaUrl(v,{width:800}):c.src:"",[c.src,v]),[C,T]=u.useState(S);u.useEffect(()=>{T(S)},[S]);const N=u.useCallback(()=>{if(v){const j=c.rawDriveUrl||`https://drive.google.com/thumbnail?id=${encodeURIComponent(v)}&sz=w1600`;C!==j&&T(j)}},[v,c.rawDriveUrl,C]),_=u.useMemo(()=>{if(!c.src)return[];const j=v?$e.buildEdgeMediaUrl(v,{width:1600}):c.rawDriveUrl||c.src;return[{id:e.id,driveFileId:v||void 0,title:c.caption||c.alt||"Evidence photograph",dateStamp:new Date().toISOString().slice(0,10),photo:{src:j,alt:c.alt||c.caption||"Evidence photograph",caption:c.caption||"",showCaption:!!c.caption},imageSrc:j}]},[e.id,v,c.src,c.rawDriveUrl,c.alt,c.caption]),k=u.useCallback(()=>{p&&f(!0)},[p]),w=u.useCallback(()=>{f(!1)},[]),$=u.useCallback(j=>{},[]),I=()=>p?n.jsxs("div",{className:`${ze.photoCard} ${r||""}`.trim(),children:[n.jsx("button",{type:"button",className:ze.photoButton,onClick:k,"aria-label":`View source photograph in full screen: ${c.caption||c.alt||"Evidence photo"}`,children:n.jsx("img",{src:C,srcSet:b,sizes:g,alt:c.alt||c.caption||"Evidence photograph",className:ze.photoImage,loading:"lazy",decoding:"async",referrerPolicy:"no-referrer",onError:N,style:c.aspectRatio?{aspectRatio:c.aspectRatio}:void 0})}),c.caption?n.jsx("p",{className:ze.photoCaption,children:c.caption}):null,x?n.jsx("div",{className:ze.driveContainer,children:n.jsx("a",{href:c.driveUrl,target:"_blank",rel:"noopener noreferrer",className:ze.driveBadge,"aria-label":"Official Google Drive folder",children:"Drive Folder ↗"})}):null]}):n.jsxs("div",{className:`${ze.placeholderCard} ${r||""}`.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:[n.jsx("div",{className:ze.placeholderIconWrapper,"aria-hidden":"true",children:n.jsxs("svg",{className:ze.cameraIcon,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n.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"}),n.jsx("circle",{cx:"12",cy:"13",r:"4"})]})}),n.jsx("span",{className:ze.placeholderText,children:"Evidence photograph pending"}),x?n.jsx("div",{className:ze.driveContainer,children:n.jsx("a",{href:c.driveUrl,target:"_blank",rel:"noopener noreferrer",className:ze.driveBadge,"aria-label":"Official Google Drive folder",children:"Drive Folder ↗"})}):null]});return n.jsxs(n.Fragment,{children:[n.jsx("div",{className:`${ze.photoCardContainer} ${r||""}`.trim(),children:n.jsx("div",{className:ze.photoCardBody,children:I()})}),p&&d?n.jsx(ku,{isOpen:d,items:_,currentIndex:0,driveFolderUrl:c.driveUrl,accentColor:t,onClose:w,onNavigate:()=>{}}):null,l?n.jsx(Ui,{isOpen:m,pointId:e.pointId||`canvas.photo.${e.id}`,initialTitle:x&&(c.caption||c.alt)||"",initialUrl:c.driveUrl||"",onClose:()=>h(!1),onSuccess:$}):null]})});Gi.displayName="CanvasPhoto";const io=JSON.parse('[{"id":"access","index":0,"nodeNumber":1,"title":"Project Initiation","subtitle":"Discovery, Scoping & Baseline Requirements","summary":"Establishing foundational project parameters, stakeholder alignment, and baseline operational requirements.","tagline":"Stage 01 · Initial Phase","accentColor":"#0284c7","accentTint":"#e0f2fe","heroImage":{"src":"https://images.unsplash.com/photo-1451187580459-43490279c0fa?w=1200&q=80&auto=format&fit=crop","alt":"Abstract network graph illustrating project baseline parameters","caption":"Baseline project scoping and preliminary operational requirements.","showCaption":true},"annotation":"Stage 01 outlines initial project parameters and documentation.","stages":[{"step":1,"stageName":"Current Assessment","narrative":"Evaluating existing operational workflows and establishing initial baseline metrics."},{"step":2,"stageName":"Requirements Definition","narrative":"Defining core project requirements, functional criteria, and resource allocation targets."},{"step":3,"stageName":"Process Alignment","narrative":"Standardizing task execution plans, administrative schedules, and procedural guidelines."},{"step":4,"stageName":"Milestone Deliverables","narrative":"Fulfilling initial milestone criteria and verifying procedural compliance documentation."},{"step":5,"stageName":"Stakeholder Review","narrative":"Providing routine progress updates and operational status briefings to project leads."}],"sourceItems":[{"id":"src-acc-01","title":"Project Scoping & Charter Brief","dateStamp":"2026-01-15","photo":{"src":"https://images.unsplash.com/photo-1504639725590-34d0984388bd?w=800&q=80","alt":"Standard project documentation and technical briefing","caption":"Baseline project scoping and preliminary operational documentation.","showCaption":false},"imageSrc":"https://images.unsplash.com/photo-1504639725590-34d0984388bd?w=800&q=80","reference":"Operational Briefing Doc 101"},{"id":"src-acc-02","title":"Resource Allocation Matrix","dateStamp":"2026-02-10","photo":{"src":"https://images.unsplash.com/photo-1551288049-bebda4e38f71?w=800&q=80","alt":"Resource allocation matrix and schedule table","caption":"Resource allocation matrix and procedural benchmarks.","showCaption":false},"imageSrc":"https://images.unsplash.com/photo-1551288049-bebda4e38f71?w=800&q=80","reference":"Planning Document Ref 204"}],"metadata":{"category":"planning","stability":"stable","version":"1.0.0"}},{"id":"equity","index":1,"nodeNumber":2,"title":"System Planning","subtitle":"Functional Analysis & Workflow Specification","summary":"Detailed analysis of operational workflows, data specifications, and departmental integration criteria.","tagline":"Stage 02 · Analysis Phase","accentColor":"#881337","accentTint":"#ffe4e6","heroImage":{"src":"https://images.unsplash.com/photo-1518770660439-4636190af475?w=1200&q=80&auto=format&fit=crop","alt":"System schematics and workflow architecture diagram","caption":"Workflow mapping and procedural specification review.","showCaption":true},"annotation":"Stage 02 defines procedural workflows and operational specifications.","stages":[{"step":1,"stageName":"Workflow Review","narrative":"Assessing current task sequences and identifying operational dependencies across units."},{"step":2,"stageName":"Specification Mapping","narrative":"Documenting detailed functional criteria and outlining operational boundaries."},{"step":3,"stageName":"Standardization","narrative":"Establishing uniform reporting templates and administrative operating guidelines."},{"step":4,"stageName":"Review Checkpoints","narrative":"Confirming alignment between planned workflows and overall operational criteria."},{"step":5,"stageName":"Team Coordination","narrative":"Sharing documented specifications and coordinating task schedules across departments."}],"sourceItems":[{"id":"src-eq-01","title":"Functional Specifications Sheet","dateStamp":"2026-03-01","photo":{"src":"https://images.unsplash.com/photo-1581291518857-4e27b48ff24e?w=800&q=80","alt":"Functional specifications checklist and procedural audit","caption":"Procedural verification across functional components.","showCaption":false},"imageSrc":"https://images.unsplash.com/photo-1581291518857-4e27b48ff24e?w=800&q=80","reference":"System Specification Document 2026-A"}],"metadata":{"category":"analysis","stability":"active","version":"1.0.0"}},{"id":"quality","index":2,"nodeNumber":3,"title":"Execution & Implementation","subtitle":"Scheduled Deliverables & Core Execution","summary":"Carrying out scheduled milestones, core task execution, and standard operational activities.","tagline":"Stage 03 · Execution Phase","accentColor":"#f59e0b","accentTint":"#fef3c7","heroImage":{"src":"https://images.unsplash.com/photo-1460925895917-afdab827c52f?w=1200&q=80&auto=format&fit=crop","alt":"Operational dashboard displaying routine project metrics","caption":"Implementation phase tracking scheduled deliverables and operational metrics.","showCaption":true},"annotation":"Stage 03 focuses on active implementation and milestone delivery.","stages":[{"step":1,"stageName":"Task Scheduling","narrative":"Organizing active work streams and allocating resources according to the schedule."},{"step":2,"stageName":"Activity Rollout","narrative":"Executing routine operational tasks and tracking day-to-day project milestones."},{"step":3,"stageName":"Progress Monitoring","narrative":"Maintaining central task logs and recording progress against defined benchmarks."},{"step":4,"stageName":"Deliverable Verification","narrative":"Verifying completed work items against established criteria and output requirements."},{"step":5,"stageName":"Operational Reporting","narrative":"Compiling regular progress reports and updating central project tracking tools."}],"sourceItems":[{"id":"src-qual-01","title":"Milestone Delivery Record","dateStamp":"2026-03-20","photo":{"src":"https://images.unsplash.com/photo-1551836022-d5d88e9218df?w=800&q=80","alt":"Operational milestone progress tracking chart","caption":"Delivery verification records across core work streams.","showCaption":false},"imageSrc":"https://images.unsplash.com/photo-1551836022-d5d88e9218df?w=800&q=80","reference":"Delivery Status Report Q1"}],"metadata":{"category":"execution","stability":"active","version":"1.0.0"}},{"id":"resiliency","index":3,"nodeNumber":4,"title":"Testing & Quality Assurance","subtitle":"Operational Verification & Compliance Checks","summary":"Conducting systematic quality assurance checks, compliance audits, and procedural evaluations.","tagline":"Stage 04 · Review Phase","accentColor":"#15803d","accentTint":"#dcfce7","heroImage":{"src":"https://images.unsplash.com/photo-1526374965328-7f61d4dc18c5?w=1200&q=80&auto=format&fit=crop","alt":"Quality assurance testing logs and review data","caption":"Systematic verification procedures ensuring procedural quality and compliance.","showCaption":true},"annotation":"Stage 04 ensures procedural consistency and operational quality.","stages":[{"step":1,"stageName":"Quality Review","narrative":"Reviewing completed deliverables against established operational guidelines."},{"step":2,"stageName":"Compliance Check","narrative":"Verifying procedural compliance with standard organizational requirements."},{"step":3,"stageName":"Remediation Procedures","narrative":"Addressing identified feedback and refining procedural workflows accordingly."},{"step":4,"stageName":"Verification Sign-Off","narrative":"Confirming full compliance and signing off on verified milestone requirements."},{"step":5,"stageName":"Documentation Filing","narrative":"Archiving verification checklists and filing quarterly quality audit summaries."}],"sourceItems":[{"id":"src-res-01","title":"Quality Audit Checklist","dateStamp":"2026-04-05","photo":{"src":"https://images.unsplash.com/photo-1544197150-b99a580bb7a8?w=800&q=80","alt":"Quality audit records and verification checklist","caption":"Audit summary records and verification checklist data.","showCaption":false},"imageSrc":"https://images.unsplash.com/photo-1544197150-b99a580bb7a8?w=800&q=80","reference":"Audit Summary Log QA-44"}],"metadata":{"category":"verification","stability":"active","version":"1.0.0"}},{"id":"governance","index":4,"nodeNumber":5,"title":"Operations & Maintenance","subtitle":"Routine Administration & Lifecycle Management","summary":"Managing ongoing operations, regular maintenance schedules, and long-term administrative reporting.","tagline":"Stage 05 · Maintenance Phase","accentColor":"#d97706","accentTint":"#ffedd5","heroImage":{"src":"https://images.unsplash.com/photo-1507679799987-c73779587ccf?w=1200&q=80&auto=format&fit=crop","alt":"Administrative office workspace representing routine operations","caption":"Ongoing administration and routine maintenance operations.","showCaption":true},"annotation":"Stage 05 coordinates ongoing administrative processes and routine oversight.","stages":[{"step":1,"stageName":"Operational Handover","narrative":"Transitioning completed project components into routine administrative management."},{"step":2,"stageName":"Maintenance Scheduling","narrative":"Establishing recurring service calendars and standard upkeep procedures."},{"step":3,"stageName":"Performance Tracking","narrative":"Monitoring ongoing operational metrics and tracking periodic indicators."},{"step":4,"stageName":"Administrative Oversight","narrative":"Maintaining central documentation and reviewing operational logs periodically."},{"step":5,"stageName":"Lifecycle Reporting","narrative":"Providing periodic administrative summaries and ongoing lifecycle updates."}],"sourceItems":[{"id":"src-gov-01","title":"Administrative Operations Log","dateStamp":"2026-04-18","photo":{"src":"https://images.unsplash.com/photo-1563986768609-322da13575f3?w=800&q=80","alt":"Administrative documentation and operational log UI","caption":"Periodic operational review records and maintenance logs.","showCaption":false},"imageSrc":"https://images.unsplash.com/photo-1563986768609-322da13575f3?w=800&q=80","reference":"Operations Manual Standard 2026"}],"metadata":{"category":"operations","stability":"active","version":"1.0.0"}}]');function Hi(e){var x,v;const t=Qt(e),[s,r]=u.useState(()=>t?vs(t):null),[a,o]=u.useState(()=>!s&&!!t),[i,l]=u.useState(!1),[c,d]=u.useState(null);u.useEffect(()=>{if(!t){r(null),o(!1);return}let b=!0;const y=vs(t);y&&r(y),qa(t).then(T=>{b&&(T&&r(T),o(!1))}).catch(T=>{b&&(d(T instanceof Error?T.message:"Failed to fetch live source source"),o(!1))});const g=T=>{const N=T;N.detail&&Qt(N.detail.pointId)===t&&r(N.detail.record)},S=`source.${t}.source`,C=qo(T=>{if((T.key===S||T.key==="*")&&b){const N=vs(t);N&&r(N)}},!1);return window.addEventListener(wa,g),()=>{b=!1,window.removeEventListener(wa,g),C()}},[t]);const f=u.useCallback(async(b,y,g)=>{if(!t)throw new Error("Cannot update source source: invalid or empty pointId");l(!0),d(null);try{const S=y&&y.trim().length>0?y.trim():(s==null?void 0:s.folderTitle)||"Official Google Drive Folder",C=await Es({pointId:t,folderUrl:b.trim(),folderTitle:S,description:g??(s==null?void 0:s.description),updatedBy:"Coordinator"});return r(C),C}catch(S){const C=S instanceof Error?S.message:"Failed to save source source";throw d(C),S}finally{l(!1)}},[t,s]),m=((x=s==null?void 0:s.folderUrl)==null?void 0:x.trim())||"",h=((v=s==null?void 0:s.folderTitle)==null?void 0:v.trim())||"Official Google Drive Folder",p=m.length>0;return{source:s,folderUrl:m,folderTitle:h,description:s==null?void 0:s.description,lastVerified:s==null?void 0:s.lastVerified,isLoading:a,isUpdating:i,error:c,updateFolder:f,hasFolder:p}}function By(e){const{source:t,folderUrl:s}=Hi(e),[r,a]=u.useTransition(),[o,i]=u.useState(!1),[l,c]=u.useState(null),[d,f]=u.useState(null),[m,h]=u.useState(null),p=Qt(e);u.useEffect(()=>{if(typeof window>"u"||!p)return;const g=S=>{if(S.key===Pi){const C=vs(p);C&&C.syncedPhotos!==void 0&&h(C.syncedPhotos)}};return window.addEventListener("storage",g),()=>{window.removeEventListener("storage",g)}},[p]),u.useEffect(()=>{h(null)},[t]);const x=m??(t==null?void 0:t.syncedPhotos)??[],v=m!==null||(t==null?void 0:t.syncedPhotos)!==void 0,b=u.useMemo(()=>o||r?"syncing":l?"sync_error":v?x.length>0?"synced_success":"synced_empty":"never_synced",[o,r,l,v,x.length]),y=u.useCallback(async()=>{if(!s)return c("No Google Drive folder linked to this node."),null;i(!0),c(null);try{const g=await Au(e,s,x);return a(()=>{f(g.stats)}),g.stats}catch(g){const S=g instanceof Error?g.message:"Failed to sync photos from Google Drive.";throw c(S),g}finally{i(!1)}},[e,s,x]);return{syncedPhotos:x,syncState:b,hasSynced:v,isSyncing:o||r,error:l,lastStats:d,syncPhotos:y}}const jc=({title:e="No items found"})=>n.jsx("div",{children:e}),Py="_sourceFigure_1keci_15",Oy="_collageItem_1keci_27",Fy="_photoCard_1keci_33",Uy="_clickable_1keci_51",Gy="_disabled_1keci_82",Hy="_sourceImageWrapper_1keci_88",zy="_aspectLandscape_1keci_96",qy="_aspectSquare_1keci_100",Vy="_aspectAuto_1keci_104",Wy="_overflowOverlay_1keci_109",Ky="_overflowBadge_1keci_135",Yy="_sourceImage_1keci_88",Xy="_captionWrapper_1keci_158",Jy="_photoCaption_1keci_167",at={sourceFigure:Py,collageItem:Oy,photoCard:Fy,clickable:Uy,disabled:Gy,sourceImageWrapper:Hy,aspectLandscape:zy,aspectSquare:qy,aspectAuto:Vy,overflowOverlay:Wy,overflowBadge:Ky,sourceImage:Yy,captionWrapper:Xy,photoCaption:Jy},Tc=({item:e,accentColor:t,onClick:s,onEditTitle:r,onEditPhoto:a,disabled:o=!1,className:i="",overlayCount:l,aspectRatio:c="landscape",hideCaption:d=!1})=>{var D;const{isDevMode:f,isDesktop:m}=Ne(),h=f&&m,p=e.photo??{src:e.imageSrc||"",alt:e.title,caption:e.title,showCaption:!1},x=u.useCallback(()=>{s&&s(e)},[s,e]),v=u.useCallback(H=>{(H.key==="Enter"||H.key===" ")&&s&&(H.preventDefault(),s(e))},[s,e]),b=!o&&!!s,y=!!(l&&l>0),g=p.caption??e.title,S=!!((y||p.showCaption)&&g),C=y?`+${l} more photos`:g,T=c==="square"?at.aspectSquare:c==="auto"?at.aspectAuto:at.aspectLandscape,N=b?y?`View gallery photos, +${l} more in archive`:`View source photo: ${g||e.title}`:void 0,_=t?{"--card-accent":t}:void 0,k=e.driveFileId||((D=e.id)!=null&&D.startsWith("drive-")?e.id.replace(/^drive-/,""):"")||$e.extractDriveFileId(p.src||e.imageSrc||""),w=k&&!p.src.includes("/api/media/drive/")?$e.buildEdgeMediaUrl(k,{width:800}):p.src,$=k?$e.buildEdgeSrcSet(k):void 0,I="(max-width: 640px) 100vw, (max-width: 1024px) 50vw, 400px",j=k?`https://drive.google.com/thumbnail?id=${encodeURIComponent(k)}&sz=w1600`:void 0;return n.jsxs("figure",{className:`${at.sourceFigure} ${d?at.collageItem:""} ${o?at.disabled:""} ${i}`,style:_,children:[n.jsx("div",{className:`${at.photoCard} ${b?at.clickable:""} ${o?at.disabled:""}`,onClick:b?x:void 0,onKeyDown:b?v:void 0,role:b?"button":void 0,tabIndex:b?0:void 0,"aria-label":N,"aria-disabled":o?!0:void 0,children:n.jsxs("div",{className:`${at.sourceImageWrapper} ${T}`,children:[n.jsx(Cu,{src:w,srcSet:$,sizes:I,fallbackSrc:j,alt:p.alt||e.title,imageClassName:at.sourceImage,loading:"lazy",decoding:"async"}),y&&n.jsx("div",{className:at.overflowOverlay,"aria-hidden":"true",children:n.jsxs("span",{className:at.overflowBadge,children:["+",l]})})]})}),!d&&n.jsxs("div",{className:at.captionWrapper,children:[S&&n.jsx("figcaption",{className:at.photoCaption,children:C}),h&&(a||r)&&n.jsx(he,{variant:"admin",size:"xs",onClick:H=>{H.stopPropagation(),a?a(e):r&&r(e)},title:"Edit photo details","aria-label":"Edit photo details",children:"✎ Edit"})]})]})},Zy="_wrapper_10c84_13",Qy="_editorial_10c84_25",e_="_editorialContent_10c84_65",t_="_editorialHeader_10c84_72",n_="_editorialTitle_10c84_78",s_="_editorialDesc_10c84_86",r_="_editorialAction_10c84_93",a_="_driveIcon_10c84_109",o_="_externalIcon_10c84_116",i_="_verifiedDot_10c84_130",Mt={wrapper:Zy,editorial:Qy,editorialContent:e_,editorialHeader:t_,editorialTitle:n_,editorialDesc:s_,editorialAction:r_,driveIcon:a_,externalIcon:o_,verifiedDot:i_},l_=({pointId:e,label:t,variant:s="compact",accentColor:r,className:a=""})=>{const{isDevMode:o,isDesktop:i}=Ne(),l=o&&i,[c,d]=u.useState(!1);u.useEffect(()=>{!l&&c&&d(!1)},[l,c]);const{folderUrl:f,folderTitle:m,description:h,hasFolder:p,updateFolder:x}=Hi(e),v=t||m||"Official Google Drive Folder",b=`source.${Qt(e)}.source`,y=u.useMemo(()=>({url:f,label:p?v:"",openInNewTab:!0}),[f,v,p]),g=u.useCallback((T,N,_)=>{_!=null&&_.url&&x(_.url,_.label)},[x]);if(!p&&!l)return null;const S=n.jsx("svg",{className:Mt.driveIcon,viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:n.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"})}),C=()=>{if(!p&&l)return n.jsx(or,{variant:"neutral",size:"sm",icon:S,label:"Attach Drive Folder",title:"No Drive folder configured. Use Edit to link an official folder."});if(s==="editorial"){const T=r?{"--accent":r}:void 0;return n.jsxs("a",{href:f,target:"_blank",rel:"noopener noreferrer",className:Mt.editorial,style:T,"aria-label":`Official Google Drive Folder: ${v}`,children:[n.jsxs("div",{className:Mt.editorialContent,children:[n.jsxs("div",{className:Mt.editorialHeader,children:[n.jsx("span",{className:Mt.verifiedDot,"aria-hidden":"true"}),S,n.jsx("span",{className:Mt.editorialTitle,children:v})]}),h&&n.jsx("span",{className:Mt.editorialDesc,children:h})]}),n.jsxs("span",{className:Mt.editorialAction,children:["Inspect MOV Archive ",n.jsx("span",{className:Mt.externalIcon,"aria-hidden":"true",children:"↗"})]})]})}return n.jsx(or,{variant:"link",size:"sm",href:f,icon:S,label:v,ariaLabel:`Official Google Drive Folder: ${v}`})};return n.jsxs("div",{className:`${Mt.wrapper} ${a}`.trim(),children:[n.jsx(Ln,{pointId:b,type:"link",defaultValue:y,currentValue:y,onEditText:()=>d(!0),onSave:g,children:C()}),n.jsx(Ui,{isOpen:c,pointId:e,initialTitle:p?m:"",initialUrl:f,onClose:()=>d(!1),onSuccess:(T,N)=>{x(T,N)}})]})},c_="_modalBody_f0gv9_1",d_="_photoPreviewBlock_f0gv9_8",u_="_previewThumbnail_f0gv9_17",h_="_previewMeta_f0gv9_26",m_="_previewLabel_f0gv9_33",f_="_previewOriginalName_f0gv9_41",p_="_formGroup_f0gv9_50",g_="_fieldLabel_f0gv9_56",v_="_inputField_f0gv9_63",x_="_fieldHint_f0gv9_83",b_="_actionRow_f0gv9_90",Ct={modalBody:c_,photoPreviewBlock:d_,previewThumbnail:u_,previewMeta:h_,previewLabel:m_,previewOriginalName:f_,formGroup:p_,fieldLabel:g_,inputField:v_,fieldHint:x_,actionRow:b_},y_=({isOpen:e,item:t,photoItem:s,onClose:r,onSave:a})=>{var g;const o=t??s??null,{isDevMode:i,isDesktop:l,showToast:c}=Ne(),[d,f]=u.useState(""),[m,h]=u.useState(!1),p=u.useRef(null);if(u.useEffect(()=>{e&&(!i||!l)&&r()},[e,i,l,r]),u.useEffect(()=>{var S,C;if(e&&o){const T=!!((S=o.photo)!=null&&S.src||o.imageSrc),N=o.title||((C=o.photo)==null?void 0:C.caption)||"";f(!T||(N==="Evidence photograph"||N==="Evidence documentation photo"||N==="Photographic proof for this strategic milestone."||N==="Photo Caption")?"":N),h(!1);const k=setTimeout(()=>{var w;(w=p.current)==null||w.focus()},50);return()=>clearTimeout(k)}},[e,o]),!e||!o)return null;const x=o,v=((g=o.photo)==null?void 0:g.src)||o.imageSrc||x.thumbnailUrl||"",b=x.originalFileName,y=async S=>{if(S&&S.preventDefault(),!(!d.trim()||m)){h(!0);try{await a(o.id,d.trim()),c("Photo title saved to draft successfully.","success"),r()}catch(C){console.error("Failed to save photo title:",C),c("Failed to save photo title.","error")}finally{h(!1)}}};return n.jsx(ut,{isOpen:e,onClose:r,onConfirm:!m&&d.trim()?()=>{y()}:void 0,title:"Edit Photo Title",maxWidth:"540px",children:n.jsxs("form",{onSubmit:y,className:Ct.modalBody,children:[v&&n.jsxs("div",{className:Ct.photoPreviewBlock,children:[n.jsx("img",{src:v,alt:o.title,className:Ct.previewThumbnail,referrerPolicy:"no-referrer"}),n.jsxs("div",{className:Ct.previewMeta,children:[n.jsx("span",{className:Ct.previewLabel,children:"Google Drive Asset"}),b&&n.jsx("span",{className:Ct.previewOriginalName,title:b,children:b})]})]}),n.jsxs("div",{className:Ct.formGroup,children:[n.jsx("label",{htmlFor:"edit-photo-title",className:Ct.fieldLabel,children:"Title / Caption"}),n.jsx("input",{ref:p,id:"edit-photo-title",type:"text",className:Ct.inputField,value:d,onChange:S=>f(S.target.value),placeholder:"e.g., Community Stakeholders Assembly",disabled:m,required:!0}),n.jsx("p",{className:Ct.fieldHint,children:"This title will be preserved across future Google Drive folder syncs."})]}),n.jsxs("div",{className:Ct.actionRow,children:[n.jsx(he,{variant:"secondary",size:"sm",type:"button",onClick:r,disabled:m,children:"Cancel"}),n.jsx(he,{variant:"primary",size:"sm",type:"submit",disabled:m||!d.trim(),children:m?"Saving...":"Save Title"})]})]})})},__="_container_1ejsb_12",w_="_footer_1ejsb_20",S_="_footerLeft_1ejsb_30",C_="_footerRight_1ejsb_37",k_="_syncButton_1ejsb_46",N_="_syncIcon_1ejsb_92",j_="_syncing_1ejsb_99",T_="_galleryCardContainer_1ejsb_113",I_="_galleryCardBody_1ejsb_121",A_="_sideEditWrapper_1ejsb_129",E_="_sideEditBtn_1ejsb_138",$_="_sideSyncBtn_1ejsb_139",L_="_highlightedGallery_1ejsb_146",M_="_collageContainer_1ejsb_154",D_="_topRow_1ejsb_165",R_="_topRowSingle_1ejsb_172",B_="_bottomRow_1ejsb_176",P_="_bottomRowDuo_1ejsb_183",Ue={container:__,footer:w_,footerLeft:S_,footerRight:C_,syncButton:k_,syncIcon:N_,syncing:j_,galleryCardContainer:T_,galleryCardBody:I_,sideEditWrapper:A_,sideEditBtn:E_,sideSyncBtn:$_,highlightedGallery:L_,collageContainer:M_,topRow:D_,topRowSingle:R_,bottomRow:B_,bottomRowDuo:P_},O_=({nodeId:e,sourceItems:t,accentColor:s,className:r="",editTriggerId:a})=>{const[o,i]=u.useState(!1),[l,c]=u.useState(0),[d,f]=u.useState(!1),[m,h]=u.useState(null),[p,x]=u.useState(null),[v,b]=u.useState("success"),[y,g]=u.useState(!1),{isDevMode:S,isDesktop:C}=Ne(),T=S&&C;u.useEffect(()=>{T||(d&&f(!1),m&&h(null))},[T,d,m]);const{folderUrl:N,folderTitle:_,hasFolder:k,updateFolder:w}=Hi(e),{syncedPhotos:$,syncState:I,isSyncing:j,syncPhotos:D,error:H}=By(e),L=u.useMemo(()=>ly(e),[e]),U=`source.${Qt(e)}.source`,G=N||(L==null?void 0:L.folderUrl)||"",z=_||(L==null?void 0:L.folderTitle)||"Official Google Drive Folder",q=k||!!(G&&G.trim().length>0),P=u.useMemo(()=>I==="synced_success"&&$.length>0?$:t,[I,$,t]),F=I==="synced_empty",R=!F&&P.length>0,W=u.useCallback(async()=>{try{const ee=await D();ee?ee.total===0?(x("Sync completed: 0 photos found in the Google Drive folder."),b("info")):ee.hasChanged?(x(`Synced ${ee.total} photos (+${ee.added} added, -${ee.removed} removed).`),b("success")):(x(`Gallery is up to date (${ee.total} photos verified).`),b("info")):(x(H||"Sync completed with no changes."),b(H?"error":"info"))}catch(ee){const V=ee instanceof Error?ee.message:"Failed to sync photos from Google Drive.";x(V),b("error")}},[D,H]),se=u.useCallback(async(ee,V,J,Y)=>{const te=V.trim();if(te)if($&&$.length>0){const oe=$.map(B=>{var E;return B.id===ee||B.driveFileId===ee?{...B,title:te,date:J||B.date,dateStamp:J||B.dateStamp,isCustomTitle:!0,photo:{...B.photo,src:((E=B.photo)==null?void 0:E.src)||B.fullImageUrl||B.thumbnailUrl||"",alt:te,caption:(Y==null?void 0:Y.trim())||te,showCaption:!0}}:B});await Es({pointId:e,folderUrl:G,folderTitle:z,syncedPhotos:oe,updatedBy:"Coordinator"}),x(`Updated photo: "${te}".`),b("success")}else{const oe=P.map((B,E)=>{var de,ae,fe,be,ve;const O=B.id===ee||B.driveFileId===ee,ie=O?te:B.title,ce=O&&J?J:B.date||B.dateStamp||"2026-10-09";return{id:B.id,pointId:e,driveFileId:B.driveFileId||B.id,originalFileName:B.originalFileName||`${B.id}.jpg`,title:ie,isCustomTitle:O?!0:B.isCustomTitle??!1,orderIndex:E,date:ce,dateStamp:ce,thumbnailUrl:((de=B.photo)==null?void 0:de.src)||B.imageSrc||"",fullImageUrl:((ae=B.photo)==null?void 0:ae.src)||B.imageSrc||"",imageSrc:((fe=B.photo)==null?void 0:fe.src)||B.imageSrc||"",photo:{src:((be=B.photo)==null?void 0:be.src)||B.imageSrc||"",alt:ie,caption:O?(Y==null?void 0:Y.trim())||ie:((ve=B.photo)==null?void 0:ve.caption)||ie,showCaption:!0}}});await Es({pointId:e,folderUrl:G,folderTitle:z,syncedPhotos:oe,updatedBy:"Coordinator"}),x(`Updated photo: "${te}".`),b("success")}},[$,P,e,G,z]),re=u.useCallback(ee=>{c(ee),i(!0)},[]),le=u.useCallback(()=>{i(!1)},[]),M=u.useCallback(ee=>{c(ee)},[]),K=P.length,{topRowItems:Q,bottomRowItems:X}=u.useMemo(()=>K===0?{topRowItems:[],bottomRowItems:[]}:K===1?{topRowItems:[{item:P[0],originalIndex:0,aspectRatio:"landscape"}],bottomRowItems:[]}:K===2?{topRowItems:[{item:P[0],originalIndex:0,aspectRatio:"landscape"},{item:P[1],originalIndex:1,aspectRatio:"landscape"}],bottomRowItems:[]}:K===3?{topRowItems:[{item:P[0],originalIndex:0,aspectRatio:"landscape"}],bottomRowItems:[{item:P[1],originalIndex:1,aspectRatio:"landscape"},{item:P[2],originalIndex:2,aspectRatio:"landscape"}]}:K===4?{topRowItems:[{item:P[0],originalIndex:0,aspectRatio:"landscape"},{item:P[1],originalIndex:1,aspectRatio:"landscape"}],bottomRowItems:[{item:P[2],originalIndex:2,aspectRatio:"landscape"},{item:P[3],originalIndex:3,aspectRatio:"landscape"}]}:{topRowItems:[{item:P[0],originalIndex:0,aspectRatio:"landscape"},{item:P[1],originalIndex:1,aspectRatio:"landscape"}],bottomRowItems:[{item:P[2],originalIndex:2,aspectRatio:"square"},{item:P[3],originalIndex:3,aspectRatio:"square"},{item:P[4],originalIndex:4,aspectRatio:"square",overlayCount:K-4}]},[P,K]);return n.jsxs("div",{className:`${Ue.container} ${r}`.trim(),children:[n.jsxs("div",{className:Ue.galleryCardContainer,children:[n.jsx("div",{className:`${Ue.galleryCardBody} ${y?Ue.highlightedGallery:""}`,children:R?n.jsxs("div",{className:Ue.collageContainer,children:[Q.length>0&&n.jsx("div",{className:`${Ue.topRow} ${Q.length===1?Ue.topRowSingle:""}`.trim(),children:Q.map(ee=>n.jsx(Tc,{item:ee.item,accentColor:s,aspectRatio:ee.aspectRatio,hideCaption:!0,onClick:()=>re(ee.originalIndex),onEditPhoto:V=>h(V)},ee.item.id))}),X.length>0&&n.jsx("div",{className:`${Ue.bottomRow} ${X.length===2?Ue.bottomRowDuo:""}`.trim(),children:X.map(ee=>n.jsx(Tc,{item:ee.item,accentColor:s,aspectRatio:ee.aspectRatio,hideCaption:!0,overlayCount:"overlayCount"in ee?ee.overlayCount:void 0,onClick:()=>re(ee.originalIndex),onEditPhoto:V=>h(V)},ee.item.id))})]}):F?n.jsx(jc,{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:G?"Open Google Drive to Upload ↗":void 0,onAction:G?()=>{typeof window<"u"&&window.open(G,"_blank","noopener,noreferrer")}:void 0}):n.jsx(jc,{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."})}),T&&n.jsxs("div",{className:Ue.sideEditWrapper,children:[n.jsx(he,{type:"button",variant:"admin",size:"xs","data-dev-edit-trigger":"true","data-canvas-edit-trigger":a,onClick:()=>f(!0),onMouseEnter:()=>g(!0),onMouseLeave:()=>g(!1),className:Ue.sideEditBtn,title:"Edit source photo repository","aria-label":"Edit source photo repository",children:"✎ Edit"}),n.jsxs(he,{type:"button",variant:"admin",size:"xs",onClick:W,onMouseEnter:()=>g(!0),onMouseLeave:()=>g(!1),disabled:j,className:Ue.sideSyncBtn,title:"Sync photos from Google Drive","aria-label":"Sync photos from Google Drive",children:[n.jsx("span",{className:`${Ue.syncIcon} ${j?Ue.spinning:""}`,"aria-hidden":"true",children:"↻"}),n.jsx("span",{children:j?"Syncing…":"Sync"})]})]})]}),o&&n.jsx(ku,{isOpen:o,items:P,currentIndex:l,driveFolderUrl:G,accentColor:s,onClose:le,onNavigate:M,onEditSource:()=>f(!0),onEditPhoto:ee=>h(ee)}),(q||T)&&n.jsxs("div",{className:Ue.footer,children:[n.jsx("div",{className:Ue.footerLeft,children:n.jsx(l_,{pointId:e,variant:"compact",accentColor:s})}),T&&q&&n.jsx("div",{className:Ue.footerRight,children:n.jsxs("button",{type:"button",className:`${Ue.syncButton} ${j?Ue.syncing:""}`,onClick:W,disabled:j,title:"Reconcile and sync photos from Google Drive","aria-label":"Sync photos from Google Drive",children:[n.jsx("span",{className:Ue.syncIcon,"aria-hidden":"true",children:"↻"}),n.jsx("span",{children:j?"Syncing...":"Sync Photos"})]})})]}),U&&n.jsx(Ui,{isOpen:d,pointId:e,initialTitle:z,initialUrl:G,onClose:()=>f(!1),onSuccess:(ee,V)=>{w(ee,V)}}),m&&n.jsx(y_,{isOpen:!!m,photoItem:m,onClose:()=>h(null),onSave:se}),p&&n.jsx(Ot,{message:p,type:v,onDismiss:()=>x(null)})]})},F_=Array.isArray(io)?io:io.nodes||[],zi=u.memo(({element:e,nodeId:t,accentColor:s,className:r})=>{const a=u.useMemo(()=>{const o=F_.find(i=>i.id===t);return(o==null?void 0:o.sourceItems)||[]},[t]);return n.jsx("div",{className:`${hr.galleryWrapper} ${r||""}`.trim(),children:n.jsx(O_,{nodeId:t,sourceItems:a,accentColor:s,editTriggerId:e.id})})});zi.displayName="CanvasGallery";const Eu={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)"},$u=["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)"],U_=[...$u,"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)"],Ic=["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)"],Ac=["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 ht(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 Os(e){const{count:t,accentColor:s,tierMode:r="bright"}=e;if(t<=0)return[];const a=[],o=new Set;if(s&&(a.push(s),o.add(ht(s))),r==="dark"){const c=$u.filter(m=>!o.has(ht(m))),d=Math.min(t,5);let f=0;for(;a.length<d&&f<c.length;){const m=c[f++];a.push(m),o.add(ht(m))}if(a.length<t){const m=Ic.filter(p=>!o.has(ht(p)));let h=0;for(;a.length<t&&h<m.length;){const p=m[h++];a.push(p),o.add(ht(p))}}if(a.length<t){const m=Ac.filter(p=>!o.has(ht(p)));let h=0;for(;a.length<t&&h<m.length;){const p=m[h++];a.push(p),o.add(ht(p))}}return a}const i=U_.filter(c=>!o.has(ht(c)));let l=0;for(;a.length<t&&l<i.length;){const c=i[l++];a.push(c),o.add(ht(c))}if(a.length<t){const c=Ac.filter(f=>!o.has(ht(f)));let d=0;for(;a.length<t&&d<c.length;){const f=c[d++];a.push(f),o.add(ht(f))}}if(a.length<t){const c=Ic.filter(f=>!o.has(ht(f)));let d=0;for(;a.length<t&&d<c.length;){const f=c[d++];a.push(f),o.add(ht(f))}}return a}const Jr={viewBoxWidth:800,viewBoxHeight:360,margins:{top:28,right:32,bottom:48,left:56},compactMargins:{top:16,right:16,bottom:36,left:44}};function G_(e={}){var d,f,m,h;const t=e.width??Jr.viewBoxWidth,s=e.height??Jr.viewBoxHeight,r=e.isCompact?Jr.compactMargins:Jr.margins;let a=((d=e.margins)==null?void 0:d.left)??r.left;typeof e.dynamicLeftMargin=="number"&&(a=Math.min(160,Math.max(r.left,e.dynamicLeftMargin)));const o={top:((f=e.margins)==null?void 0:f.top)??r.top,right:((m=e.margins)==null?void 0:m.right)??r.right,bottom:((h=e.margins)==null?void 0:h.bottom)??r.bottom,left:a},i=Math.max(0,t-o.left-o.right),l=Math.max(0,s-o.top-o.bottom),c=o.top+l;return{width:t,height:s,margin:o,innerWidth:i,innerHeight:l,baselineY:c}}function Lr(e={}){var o,i,l,c;const t=(o=e.margins)==null?void 0:o.top,s=(i=e.margins)==null?void 0:i.right,r=(l=e.margins)==null?void 0:l.bottom,a=(c=e.margins)==null?void 0:c.left;return u.useMemo(()=>G_(e),[e.width,e.height,t,s,r,a,e.dynamicLeftMargin,e.isCompact])}function Mr(e){const[t,s]=u.useState({visible:!1,x:0,y:0,value:null}),r=u.useCallback(o=>{let i=o.x,l=o.y;s({...o,x:i,y:l,visible:!0})},[e==null?void 0:e.clampX,e==null?void 0:e.clampY]),a=u.useCallback(()=>{s(o=>o.visible?{...o,visible:!1}:o)},[]);return{tooltipState:t,setTooltipState:s,showTooltip:r,hideTooltip:a}}const H_="_tooltipContainer_czh6l_1",z_="_tooltipCard_czh6l_12",q_="_title_czh6l_26",V_="_valueRow_czh6l_34",W_="_value_czh6l_34",K_="_seriesBadge_czh6l_49",Y_="_seriesDot_czh6l_58",Nn={tooltipContainer:H_,tooltipCard:z_,title:q_,valueRow:V_,value:W_,seriesBadge:K_,seriesDot:Y_},Fs=({visible:e,x:t,y:s,title:r,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 n.jsx("div",{className:Nn.tooltipContainer,style:{left:`${t}px`,top:`${s}px`},role:"tooltip","aria-hidden":!e,children:n.jsxs("div",{className:Nn.tooltipCard,children:[r&&n.jsx("div",{className:Nn.title,children:r}),n.jsx("div",{className:Nn.valueRow,children:n.jsx("span",{className:Nn.value,children:c})}),a&&n.jsxs("div",{className:Nn.seriesBadge,children:[l&&n.jsx("span",{className:Nn.seriesDot,style:{backgroundColor:l}}),n.jsx("span",{children:a})]})]})})},X_="_legend_ksjsx_1",J_="_legendItem_ksjsx_11",Z_="_dimmed_ksjsx_39",Q_="_active_ksjsx_43",e0="_swatch_ksjsx_49",Xs={legend:X_,legendItem:J_,dimmed:Z_,active:Q_,swatch:e0},xs=.15,Us=({items:e,activeIndex:t=null,onHover:s,className:r=""})=>!e||e.length===0?null:n.jsx("div",{className:`${Xs.legend} ${r}`.trim(),role:"list","aria-label":"Chart legend",onMouseLeave:()=>s==null?void 0:s(null),children:e.map((a,o)=>{const i=t!==null&&t===o,l=t!==null&&t!==o;return n.jsxs("button",{type:"button",role:"listitem",className:`${Xs.legendItem} ${i?Xs.active:""} ${l?Xs.dimmed:""}`.trim(),onMouseEnter:()=>s==null?void 0:s(o),onFocus:()=>s==null?void 0:s(o),onBlur:()=>s==null?void 0:s(null),"aria-pressed":i,children:[n.jsx("span",{className:Xs.swatch,style:{backgroundColor:a.color},"aria-hidden":"true"}),n.jsx("span",{children:a.name})]},a.id||o)})}),t0="_container_134xx_1",n0="_svgWrapper_134xx_10",s0="_chartSvg_134xx_17",r0="_gridLine_134xx_25",a0="_baseline_134xx_31",o0="_axisText_134xx_36",i0="_axisTextY_134xx_43",l0="_barRect_134xx_51",c0="_valueLabel_134xx_68",d0="_valueLabelInside_134xx_81",u0="_axisTextLeft_134xx_92",h0="_axisTitle_134xx_139",Re={container:t0,svgWrapper:n0,chartSvg:s0,gridLine:r0,baseline:a0,axisText:o0,axisTextY:i0,barRect:l0,valueLabel:c0,valueLabelInside:d0,axisTextLeft:u0,axisTitle:h0},Ec=24,$c=.15,Lu=({categories:e=[],series:t=[],unit:s,accentColor:r,orientation:a,barOrientation:o,stacked:i=!1,showValues:l=!1,xLabel:c,yLabel:d,onSelectDataPoint:f})=>{const m=u.useRef(null),p=(a||o||"vertical")==="horizontal",[x,v]=u.useState(null),{tooltipState:b,showTooltip:y,hideTooltip:g}=Mr(),S=u.useMemo(()=>{if(!p||e.length===0)return;const F=Math.max(...e.map(W=>String(W).length),4),R=d?24:0;return Math.min(180,Math.max(56,F*7+16+R))},[p,e,d]),{width:C,height:T,margin:N,innerWidth:_,innerHeight:k,baselineY:w}=Lr({dynamicLeftMargin:S,margins:{bottom:c?56:48,left:!p&&d?64:void 0}}),{maxValue:$,seriesList:I}=u.useMemo(()=>{const F=Os({count:t.length,accentColor:r,tierMode:"bright"}),R=t.map((re,le)=>({...re,resolvedColor:re.color||F[le]||"var(--folio-primary)"}));let W=0;if(i){const re=e.length;for(let le=0;le<re;le++){let M=0;for(const K of R){const Q=K.data[le];typeof Q=="number"&&Number.isFinite(Q)&&Q>0&&(M+=Q)}M>W&&(W=M)}}else for(const re of R)for(const le of re.data)typeof le=="number"&&Number.isFinite(le)&&le>W&&(W=le);return{maxValue:W>0?W*1.1:100,seriesList:R}},[t,e,r,i]),j=u.useMemo(()=>p?bc(e,[N.top,N.top+k],.25):bc(e,[N.left,N.left+_],.25),[e,p,N.left,N.top,_,k]),D=u.useMemo(()=>p?js([0,$],[N.left,N.left+_],!0):js([0,$],[w,N.top],!0),[$,p,N.left,N.top,_,w]),H=u.useMemo(()=>D.ticks(5),[D]),L=Math.max(I.length,1),U=j.bandwidth(),G=!i&&L>1?3:0,z=i?U:Math.max((U-(L-1)*G)/L,2),q=(F,R,W,se,re)=>{if(!m.current)return;const le=m.current.getBoundingClientRect(),M=F.clientX-le.left,K=F.clientY-le.top;v(W),y({x:M,y:K,title:R,seriesName:W,value:se,unit:s,color:re})},P=()=>{v(null),g()};return n.jsxs("div",{className:Re.container,ref:m,children:[n.jsx("div",{className:Re.svgWrapper,children:n.jsxs("svg",{viewBox:`0 0 ${C} ${T}`,className:Re.chartSvg,role:"graphics-document document","aria-label":"Bar Chart Visualizer",children:[p?H.map(F=>{const R=D(F);return n.jsxs("g",{children:[n.jsx("line",{x1:R,y1:N.top,x2:R,y2:w,className:Re.gridLine}),n.jsx("text",{x:R,y:w+18,className:Re.axisText,children:F.toLocaleString()})]},`grid-x-${F}`)}):H.map(F=>{const R=D(F);return n.jsxs("g",{children:[n.jsx("line",{x1:N.left,y1:R,x2:N.left+_,y2:R,className:Re.gridLine}),n.jsx("text",{x:N.left-10,y:R,className:Re.axisTextY,children:F.toLocaleString()})]},`grid-y-${F}`)}),p?n.jsx("line",{x1:N.left,y1:N.top,x2:N.left,y2:w,className:Re.baseline}):n.jsx("line",{x1:N.left,y1:w,x2:N.left+_,y2:w,className:Re.baseline}),c&&n.jsx("text",{x:N.left+_/2,y:T-8,textAnchor:"middle",className:Re.axisTitle,children:c}),d&&n.jsx("text",{x:-(N.top+k/2),y:16,transform:"rotate(-90)",textAnchor:"middle",className:Re.axisTitle,children:d}),e.map((F,R)=>{if(p){const M=j(F)??N.top;let K=N.left,Q=0;const X=String(F),ee=X.length>16?`${X.slice(0,14)}...`:X,V=i?I.map((J,Y)=>({idx:Y,val:J.data[R]})).filter(J=>typeof J.val=="number"&&Number.isFinite(J.val)&&J.val>0).map(J=>J.idx):[];return n.jsxs("g",{children:[n.jsx("text",{x:N.left-10,y:M+U/2,className:Re.axisTextLeft,tabIndex:0,onPointerEnter:J=>{X!==ee&&q(J,X,"",null,"")},onPointerLeave:P,children:ee}),I.map((J,Y)=>{const te=J.data[R]??null;if(te==null)return null;const B=x!==null&&x!==J.name?$c:1;let E,O,ie,ce;i?(ie=Math.max(te/$*_,0),E=K,O=M,ce=z,K+=ie,Q+=te):(ie=Math.max(D(te)-N.left,0),E=N.left,O=M+Y*(z+G),ce=z);let de="";if(i){const ae=V.length>0&&V[0]===Y,fe=V.length>0&&V[V.length-1]===Y;de=Sc(E,O,ie,ce,ae&&fe?{tl:3,tr:3,br:3,bl:3}:ae?{tl:3,bl:3,tr:0,br:0}:fe?{tr:3,br:3,tl:0,bl:0}:{tl:0,tr:0,br:0,bl:0})}return n.jsxs(u.Fragment,{children:[i?n.jsx("path",{d:de,fill:J.resolvedColor,style:{opacity:B},className:Re.barRect,tabIndex:0,onPointerEnter:ae=>q(ae,F,J.name,te,J.resolvedColor),onPointerMove:ae=>q(ae,F,J.name,te,J.resolvedColor),onPointerLeave:P,onClick:()=>f==null?void 0:f({category:F,seriesName:J.name,value:te}),onKeyDown:ae=>{(ae.key==="Enter"||ae.key===" ")&&(f==null||f({category:F,seriesName:J.name,value:te}))},"aria-label":`${F}, ${J.name}: ${te}`}):n.jsx("rect",{x:E,y:O,width:ie,height:ce,rx:3,ry:3,fill:J.resolvedColor,style:{opacity:B},className:Re.barRect,tabIndex:0,onPointerEnter:ae=>q(ae,F,J.name,te,J.resolvedColor),onPointerMove:ae=>q(ae,F,J.name,te,J.resolvedColor),onPointerLeave:P,onClick:()=>f==null?void 0:f({category:F,seriesName:J.name,value:te}),onKeyDown:ae=>{(ae.key==="Enter"||ae.key===" ")&&(f==null||f({category:F,seriesName:J.name,value:te}))},"aria-label":`${F}, ${J.name}: ${te}`}),l&&!i&&n.jsx("text",{x:E+ie+6,y:O+ce/2+4,textAnchor:"start",className:Re.valueLabel,children:te.toLocaleString()}),l&&i&&ie>=Ec&&n.jsx("text",{x:E+ie/2,y:O+ce/2+3,textAnchor:"middle",className:Re.valueLabelInside,children:te.toLocaleString()})]},`bar-frag-h-${F}-${J.name}-${Y}`)}),l&&i&&Q>0&&n.jsx("text",{x:K+6,y:M+U/2+4,textAnchor:"start",className:Re.valueLabel,children:Q.toLocaleString()})]},`cat-group-h-${F}`)}const W=j(F)??N.left;let se=w,re=0;const le=i?I.map((M,K)=>({idx:K,val:M.data[R]})).filter(M=>typeof M.val=="number"&&Number.isFinite(M.val)&&M.val>0).map(M=>M.idx):[];return n.jsxs("g",{children:[I.map((M,K)=>{const Q=M.data[R]??null;if(Q==null)return null;const ee=x!==null&&x!==M.name?$c:1;let V,J,Y,te;i?(te=Math.max(Q/$*k,0),J=se-te,V=W,Y=z,se-=te,re+=Q):(J=D(Q),te=Math.max(w-J,0),V=W+K*(z+G),Y=z);let oe="";if(i){const B=le.length>0&&le[0]===K,E=le.length>0&&le[le.length-1]===K;oe=Sc(V,J,Y,te,B&&E?{tl:3,tr:3,br:3,bl:3}:B?{bl:3,br:3,tl:0,tr:0}:E?{tl:3,tr:3,bl:0,br:0}:{tl:0,tr:0,br:0,bl:0})}return n.jsxs(u.Fragment,{children:[i?n.jsx("path",{d:oe,fill:M.resolvedColor,style:{opacity:ee},className:Re.barRect,tabIndex:0,onPointerEnter:B=>q(B,F,M.name,Q,M.resolvedColor),onPointerMove:B=>q(B,F,M.name,Q,M.resolvedColor),onPointerLeave:P,onClick:()=>f==null?void 0:f({category:F,seriesName:M.name,value:Q}),onKeyDown:B=>{(B.key==="Enter"||B.key===" ")&&(f==null||f({category:F,seriesName:M.name,value:Q}))},"aria-label":`${F}, ${M.name}: ${Q}`}):n.jsx("rect",{x:V,y:J,width:Y,height:te,rx:3,ry:3,fill:M.resolvedColor,style:{opacity:ee},className:Re.barRect,tabIndex:0,onPointerEnter:B=>q(B,F,M.name,Q,M.resolvedColor),onPointerMove:B=>q(B,F,M.name,Q,M.resolvedColor),onPointerLeave:P,onClick:()=>f==null?void 0:f({category:F,seriesName:M.name,value:Q}),onKeyDown:B=>{(B.key==="Enter"||B.key===" ")&&(f==null||f({category:F,seriesName:M.name,value:Q}))},"aria-label":`${F}, ${M.name}: ${Q}`}),l&&!i&&n.jsx("text",{x:V+Y/2,y:J-6,textAnchor:"middle",className:Re.valueLabel,children:Q.toLocaleString()}),l&&i&&te>=Ec&&n.jsx("text",{x:V+Y/2,y:J+te/2+4,textAnchor:"middle",className:Re.valueLabelInside,children:Q.toLocaleString()})]},`bar-frag-v-${F}-${M.name}-${K}`)}),l&&i&&re>0&&n.jsx("text",{x:W+U/2,y:se-6,textAnchor:"middle",className:Re.valueLabel,children:re.toLocaleString()}),n.jsx("text",{x:W+U/2,y:w+22,className:Re.axisText,children:F})]},`cat-group-v-${F}`)})]})}),n.jsx(Fs,{visible:b.visible,x:b.x,y:b.y,title:b.title,seriesName:b.seriesName,value:b.value,unit:s,color:b.color}),I.length>1&&n.jsx(Us,{items:I.map(F=>({id:F.name,name:F.name,color:F.resolvedColor})),activeIndex:x!==null?I.findIndex(F=>F.name===x):null,onHover:F=>{var R;return v(F!==null?((R=I[F])==null?void 0:R.name)??null:null)}})]})},m0="_container_1rexj_1",f0="_svgWrapper_1rexj_10",p0="_chartSvg_1rexj_17",g0="_gridLine_1rexj_25",v0="_baseline_1rexj_31",x0="_axisText_1rexj_36",b0="_axisTextY_1rexj_43",y0="_splinePath_1rexj_51",_0="_areaPath_1rexj_59",w0="_dashedBridge_1rexj_65",S0="_crosshairLine_1rexj_76",C0="_pointValueLabel_1rexj_83",k0="_dataNode_1rexj_98",N0="_dimmed_1rexj_118",j0="_axisTitle_1rexj_122",Qe={container:m0,svgWrapper:f0,chartSvg:p0,gridLine:g0,baseline:v0,axisText:x0,axisTextY:b0,splinePath:y0,areaPath:_0,dashedBridge:w0,crosshairLine:S0,pointValueLabel:C0,dataNode:k0,dimmed:N0,axisTitle:j0},Mu=({categories:e=[],series:t=[],unit:s,accentColor:r,curveInterpolation:a="smooth",showAreaFill:o=!1,markerSize:i="regular",autoScaleY:l=!1,startAtZero:c,showValues:d=!1,xLabel:f,yLabel:m,onSelectDataPoint:h})=>{const p=u.useRef(null),{tooltipState:x,showTooltip:v,hideTooltip:b}=Mr(),[y,g]=u.useState(null),[S,C]=u.useState(null),{width:T,height:N,margin:_,innerWidth:k,innerHeight:w,baselineY:$}=Lr({margins:{bottom:f?56:48,left:m?64:56}}),{seriesList:I,yDomainMin:j,yDomainMax:D}=u.useMemo(()=>{let R=1/0,W=-1/0,se=!1;for(const X of t)for(const ee of X.data)typeof ee=="number"&&Number.isFinite(ee)&&(se=!0,ee<R&&(R=ee),ee>W&&(W=ee));se||(R=0,W=100);const re=Os({count:t.length,accentColor:r,tierMode:"bright"}),le=t.map((X,ee)=>({...X,resolvedColor:X.color||re[ee]||"var(--folio-primary)"})),M=c!==void 0?c:!l;let K,Q;return M?(K=0,Q=W>0?W*1.1:100):R===W?(K=Math.max(0,R*.9),Q=W>0?W*1.1:100):(K=R>0?Math.max(0,R*.9):R*1.1,Q=W>0?W*1.1:W*.9),{seriesList:le,yDomainMin:K,yDomainMax:Q}},[t,r,l,c]),H=Math.max(e.length,1),L=u.useMemo(()=>{if(H===1)return[_.left+k/2];const R=k/(H-1);return e.map((W,se)=>_.left+se*R)},[H,k,_.left,e]),U=u.useMemo(()=>js([j,D],[$,_.top],!0),[j,D,$,_.top]),G=u.useMemo(()=>U.ticks(5),[U]),z=u.useMemo(()=>{switch(i){case"compact":return 3;case"prominent":return 7;case"regular":default:return 5}},[i]),q=u.useCallback((R,W,se,re)=>{if(!p.current)return;const le=p.current.getBoundingClientRect(),M=R.clientX-le.left,K=R.clientY-le.top;g(se),C(W.x),v({x:M,y:K,title:W.cat,seriesName:se,value:W.val,unit:s,color:re})},[v,s]),P=u.useCallback(()=>{b(),g(null),C(null)},[b]),F=u.useMemo(()=>{if(y===null)return null;const R=I.findIndex(W=>W.name===y);return R!==-1?R:null},[y,I]);return n.jsxs("div",{className:Qe.container,ref:p,children:[n.jsx("div",{className:Qe.svgWrapper,children:n.jsxs("svg",{viewBox:`0 0 ${T} ${N}`,className:Qe.chartSvg,role:"img","aria-label":"Line Chart Visualizer",onMouseLeave:P,children:[n.jsx("defs",{children:I.map((R,W)=>n.jsxs("linearGradient",{id:`area-grad-${W}`,x1:"0",y1:"0",x2:"0",y2:"1",children:[n.jsx("stop",{offset:"0%",stopColor:R.resolvedColor,stopOpacity:"0.15"}),n.jsx("stop",{offset:"100%",stopColor:R.resolvedColor,stopOpacity:"0.01"})]},`grad-${W}`))}),G.map(R=>{const W=U(R);return n.jsxs("g",{children:[n.jsx("line",{x1:_.left,y1:W,x2:_.left+k,y2:W,className:Qe.gridLine}),n.jsx("text",{x:_.left-10,y:W,className:Qe.axisTextY,children:R.toLocaleString()})]},`grid-${R}`)}),n.jsx("line",{x1:_.left,y1:$,x2:_.left+k,y2:$,className:Qe.baseline}),f&&n.jsx("text",{x:_.left+k/2,y:N-8,textAnchor:"middle",className:Qe.axisTitle,children:f}),m&&n.jsx("text",{x:-(_.top+w/2),y:16,transform:"rotate(-90)",textAnchor:"middle",className:Qe.axisTitle,children:m}),S!==null&&n.jsx("line",{x1:S,y1:_.top,x2:S,y2:$,className:Qe.crosshairLine}),e.map((R,W)=>n.jsx("text",{x:L[W],y:$+22,className:Qe.axisText,children:R},`x-label-${R}`)),I.map((R,W)=>{const se=[];if(R.data.forEach((X,ee)=>{typeof X=="number"&&Number.isFinite(X)&&se.push({x:L[ee],y:U(X),val:X,cat:e[ee],colIndex:ee})}),se.length===0)return null;const re=[],le=[];let M=[se[0]];for(let X=1;X<se.length;X++){const ee=se[X-1],V=se[X];V.colIndex===ee.colIndex+1?M.push(V):(re.push(M),le.push([ee,V]),M=[V])}re.push(M);const K=y!==null&&y!==R.name,Q=K?xs:1;return n.jsxs("g",{className:K?Qe.dimmed:void 0,style:{opacity:Q,transition:"opacity var(--duration-fast) var(--ease-out)"},children:[o&&re.map((X,ee)=>{if(X.length<2)return null;const J=`${a==="straight"?wc(X):ur(X)} L ${X[X.length-1].x} ${$} L ${X[0].x} ${$} Z`;return n.jsx("path",{d:J,fill:`url(#area-grad-${W})`,className:Qe.areaPath},`area-${W}-${ee}`)}),re.map((X,ee)=>{if(X.length<2)return null;const V=a==="straight"?wc(X):ur(X);return n.jsx("path",{d:V,stroke:R.resolvedColor,className:Qe.splinePath},`path-${W}-${ee}`)}),le.map(([X,ee],V)=>n.jsx("line",{x1:X.x,y1:X.y,x2:ee.x,y2:ee.y,stroke:R.resolvedColor,className:Qe.dashedBridge},`bridge-${W}-${V}`)),d&&se.map((X,ee)=>n.jsx("text",{x:X.x,y:X.y-(z+5),className:Qe.pointValueLabel,children:X.val.toLocaleString()},`val-label-${R.name}-${ee}`)),se.map((X,ee)=>n.jsx("circle",{cx:X.x,cy:X.y,r:z,fill:R.resolvedColor,className:Qe.dataNode,tabIndex:0,onPointerEnter:V=>q(V,X,R.name,R.resolvedColor),onPointerMove:V=>q(V,X,R.name,R.resolvedColor),onClick:()=>h==null?void 0:h({category:X.cat,seriesName:R.name,value:X.val}),onKeyDown:V=>{(V.key==="Enter"||V.key===" ")&&(h==null||h({category:X.cat,seriesName:R.name,value:X.val}))},"aria-label":`${X.cat}, ${R.name}: ${X.val.toLocaleString()}`},`point-${R.name}-${ee}`))]},`series-${R.name}-${W}`)})]})}),n.jsx(Fs,{visible:x.visible,x:x.x,y:x.y,title:x.title,seriesName:x.seriesName,value:x.value,unit:s,color:x.color}),I.length>1&&n.jsx(Us,{items:I.map(R=>({id:R.name,name:R.name,color:R.resolvedColor})),activeIndex:F,onHover:R=>{var W;R==null?g(null):g(((W=I[R])==null?void 0:W.name)||null)}})]})},T0="_container_nbga0_1",I0="_svgWrapper_nbga0_11",A0="_chartSvg_nbga0_22",E0="_slicesGroup_nbga0_31",$0="_segmentSlice_nbga0_35",L0="_labelsGroup_nbga0_52",M0="_sliceValueText_nbga0_56",D0="_centerCalloutGroup_nbga0_70",R0="_centerTotalText_nbga0_75",B0="_centerCategoryText_nbga0_86",P0="_centerMetricText_nbga0_95",it={container:T0,svgWrapper:I0,chartSvg:A0,slicesGroup:E0,segmentSlice:$0,labelsGroup:L0,sliceValueText:M0,centerCalloutGroup:D0,centerTotalText:R0,centerCategoryText:B0,centerMetricText:P0},O0=24,Du=({categories:e=[],data:t=[],accentColor:s,donutVariant:r="donut",groupOthers:a=!0,showValues:o=!1,onSelectDataPoint:i})=>{const l=u.useRef(null),c=r==="pie",{tooltipState:d,showTooltip:f,hideTooltip:m}=Mr(),[h,p]=u.useState(null),{width:x,height:v}=Lr(),b=x/2,y=v/2,g=120,S=c?0:78,C=(g+S)/2,T=g-S,N=2*Math.PI*C,{validTotal:_,segments:k}=u.useMemo(()=>{const j=[];let D=0;for(let R=0;R<e.length;R++){const W=e[R]||`Category ${R+1}`,se=t[R],re=typeof se=="number"&&Number.isFinite(se)&&se>0?se:0;j.push({category:W,value:re}),D+=re}const H=D>0?D:1;let L=[];if(a&&j.length>5){const R=[...j].sort((le,M)=>M.value-le.value),W=R.slice(0,5),se=R.slice(5),re=se.reduce((le,M)=>le+M.value,0);L=[...W],(re>0||se.length>0)&&L.push({category:"Others",value:re,isOther:!0})}else L=j;const U=L.filter(R=>!R.isOther).length,G=Os({count:U,accentColor:s,tierMode:"bright"});let z=0,q=-Math.PI/2,P=0;const F=L.map((R,W)=>{const se=R.value/H,re=se*2*Math.PI,le=q,M=q+re;q=M;const K=se*N,Q=N-K,X=-P*N;P+=se;const ee=Math.round(se*100),V=R.isOther?"var(--bg-surface-muted)":G[z++]||"var(--folio-primary)",J=le+re/2,Y=c?g*.65:C,te=b+Y*Math.cos(J),oe=y+Y*Math.sin(J),B=se*N;let E="";if(c)if(se>=.9999)E="";else{const O=b+g*Math.cos(le),ie=y+g*Math.sin(le),ce=b+g*Math.cos(M),de=y+g*Math.sin(M),ae=re>Math.PI?1:0;E=`M ${b} ${y} L ${O.toFixed(2)} ${ie.toFixed(2)} A ${g} ${g} 0 ${ae} 1 ${ce.toFixed(2)} ${de.toFixed(2)} Z`}return{id:`${R.category}-${W}`,category:R.category,value:R.value,percentage:ee,fraction:se,color:V,dashLength:K,dashSpace:Q,dashOffset:X,wedgePath:E,labelX:te,labelY:oe,arcLength:B,isOther:R.isOther}});return{validTotal:D,segments:F}},[e,t,a,s,N,b,y,c,g,C]),w=u.useCallback((j,D)=>{if(!l.current)return;const H=l.current.getBoundingClientRect(),L=k[D];L&&(p(D),f({x:j.clientX-H.left,y:j.clientY-H.top,title:L.category,seriesName:`${L.percentage}%`,value:L.value,color:L.color}))},[k,f]),$=u.useCallback(()=>{p(null),m()},[m]),I=h!==null?k[h]:null;return n.jsxs("div",{className:it.container,ref:l,children:[n.jsx("div",{className:it.svgWrapper,children:n.jsxs("svg",{viewBox:`0 0 ${x} ${v}`,className:it.chartSvg,role:"img","aria-label":"Donut Chart Visualizer",children:[!c&&n.jsx("circle",{cx:b,cy:y,r:C,stroke:"var(--bg-surface-muted)",strokeWidth:T,fill:"none",opacity:.35}),c?n.jsx("g",{className:it.slicesGroup,children:k.map((j,D)=>{const L=h!==null&&h!==D?xs:1;return j.fraction>=.9999?n.jsx("circle",{cx:b,cy:y,r:g,fill:j.color,opacity:L,className:it.segmentSlice,tabIndex:0,onPointerEnter:U=>w(U,D),onPointerMove:U=>w(U,D),onPointerLeave:$,onClick:()=>i==null?void 0:i({category:j.category,value:j.value}),onKeyDown:U=>{(U.key==="Enter"||U.key===" ")&&(i==null||i({category:j.category,value:j.value}))},"aria-label":`${j.category}: ${j.value.toLocaleString()} (${j.percentage}%)`},j.id):n.jsx("path",{d:j.wedgePath,fill:j.color,opacity:L,className:it.segmentSlice,tabIndex:0,onPointerEnter:U=>w(U,D),onPointerMove:U=>w(U,D),onPointerLeave:$,onClick:()=>i==null?void 0:i({category:j.category,value:j.value}),onKeyDown:U=>{(U.key==="Enter"||U.key===" ")&&(i==null||i({category:j.category,value:j.value}))},"aria-label":`${j.category}: ${j.value.toLocaleString()} (${j.percentage}%)`},j.id)})}):n.jsx("g",{transform:`rotate(-90 ${b} ${y})`,className:it.slicesGroup,children:k.map((j,D)=>{const H=h!==null&&h===D,U=h!==null&&h!==D?xs:1,G=H?T+6:T;return n.jsx("circle",{cx:b,cy:y,r:C,stroke:j.color,strokeWidth:G,strokeDasharray:`${j.dashLength.toFixed(2)} ${j.dashSpace.toFixed(2)}`,strokeDashoffset:j.dashOffset.toFixed(2),fill:"none",opacity:U,className:it.segmentSlice,tabIndex:0,onPointerEnter:z=>w(z,D),onPointerMove:z=>w(z,D),onPointerLeave:$,onClick:()=>i==null?void 0:i({category:j.category,value:j.value}),onKeyDown:z=>{(z.key==="Enter"||z.key===" ")&&(i==null||i({category:j.category,value:j.value}))},"aria-label":`${j.category}: ${j.value.toLocaleString()} (${j.percentage}%)`},j.id)})}),o&&n.jsx("g",{className:it.labelsGroup,pointerEvents:"none",children:k.map((j,D)=>{if(j.arcLength<O0)return null;const H=h!==null&&h!==D;return n.jsxs("text",{x:j.labelX,y:j.labelY,opacity:H?xs:1,className:it.sliceValueText,children:[j.percentage,"%"]},`label-${j.id}`)})}),!c&&n.jsx("g",{className:it.centerCalloutGroup,pointerEvents:"none",children:I?n.jsxs(n.Fragment,{children:[n.jsx("text",{x:b,y:y-8,textAnchor:"middle",className:it.centerCategoryText,children:I.category.length>14?`${I.category.slice(0,13)}…`:I.category}),n.jsxs("text",{x:b,y:y+16,textAnchor:"middle",className:it.centerMetricText,children:[I.value.toLocaleString()," (",I.percentage,"%)"]})]}):n.jsx("text",{x:b,y,textAnchor:"middle",dominantBaseline:"central",className:it.centerTotalText,children:_.toLocaleString()})})]})}),n.jsx(Fs,{visible:d.visible,x:d.x,y:d.y,title:d.title,seriesName:d.seriesName,value:d.value,color:d.color}),n.jsx(Us,{items:k.map(j=>({id:j.id,name:`${j.category} (${j.percentage}%)`,color:j.color})),activeIndex:h,onHover:j=>{p(j),j===null&&m()}})]})},F0="_container_vc9pg_1",U0="_topBar_vc9pg_10",G0="_correlationChip_vc9pg_19",H0="_chipDivider_vc9pg_33",z0="_svgWrapper_vc9pg_38",q0="_chartSvg_vc9pg_45",V0="_gridLine_vc9pg_53",W0="_axisLine_vc9pg_59",K0="_meanLine_vc9pg_64",Y0="_axisText_vc9pg_71",X0="_axisTextY_vc9pg_78",J0="_axisTitle_vc9pg_86",Z0="_trendLine_vc9pg_93",Q0="_confidenceBand_vc9pg_100",e1="_pointNode_vc9pg_105",Oe={container:F0,topBar:U0,correlationChip:G0,chipDivider:H0,svgWrapper:z0,chartSvg:q0,gridLine:V0,axisLine:W0,meanLine:K0,axisText:Y0,axisTextY:X0,axisTitle:J0,trendLine:Z0,confidenceBand:Q0,pointNode:e1},Ru=({points:e=[],xLabel:t,yLabel:s,unit:r,accentColor:a="var(--folio-primary)",curveInterpolation:o="none",loessBandwidth:i=.5,showAreaFill:l=!1,markerSize:c="regular",autoScaleY:d=!1,autoScaleX:f=!1,startAtZero:m,startAtZeroX:h,showCorrelationChip:p=!1,showReferenceGuide:x=!1,onSelectPoint:v})=>{const b=u.useRef(null),{tooltipState:y,showTooltip:g,hideTooltip:S}=Mr(),[C,T]=u.useState(null),[N,_]=u.useState(null),{width:k,height:w,margin:$,innerWidth:I,innerHeight:j,baselineY:D}=Lr({margins:{bottom:t?56:48,left:s?64:56}}),H=u.useMemo(()=>{switch(c){case"compact":return 3;case"prominent":return 7;case"regular":default:return 5}},[c]),L=u.useMemo(()=>e.filter(Y=>typeof Y.x=="number"&&Number.isFinite(Y.x)&&typeof Y.y=="number"&&Number.isFinite(Y.y)),[e]),{distinctGroups:U,groupColorMap:G,legendItems:z}=u.useMemo(()=>{const Y=L.map(O=>O.group).filter(Boolean),te=Array.from(new Set(Y));if(te.length===0)return{distinctGroups:[],groupColorMap:{},legendItems:[]};const oe=Os({count:te.length,accentColor:a,tierMode:"bright"}),B={},E=[];return te.forEach((O,ie)=>{const ce=oe[ie]||a;B[O]=ce,E.push({id:`group-${ie}-${O}`,name:O,color:ce})}),{distinctGroups:te,groupColorMap:B,legendItems:E}},[L,a]),q=C!==null?U[C]:null,{xScale:P,yScale:F,xTicks:R,yTicks:W,xDataRange:se}=u.useMemo(()=>{const Y=L.map(ve=>ve.x),te=L.map(ve=>ve.y),[oe,B]=_c(Y),[E,O]=_c(te),ie=h!==void 0?h:!f,ce=m!==void 0?m:!d;let de;if(ie)de=[0,B>0?B*1.1:100];else{const ve=B-oe||10,Pe=Math.max(0,oe-ve*.1),Ce=B+ve*.1;de=[Pe,Ce]}let ae;if(ce)ae=[0,O>0?O*1.15:100];else{const ve=O-E||10,Pe=Math.max(0,E-ve*.1),Ce=O+ve*.1;ae=[Pe,Ce]}const fe=js(de,[$.left,$.left+I],!0),be=js(ae,[D,$.top],!0);return{xScale:fe,yScale:be,xTicks:fe.ticks(6),yTicks:be.ticks(5),xDataRange:[oe,B]}},[L,I,D,$.left,$.top,f,d,m,h]),re=u.useMemo(()=>Lo(L),[L]),le=u.useMemo(()=>o!=="smooth"||L.length<2?[]:Tx(L,i),[o,L,i]),M=u.useMemo(()=>{if(le.length<2)return"";const Y=le.map(te=>({x:P(te.x),y:F(te.y)}));return ur(Y)},[le,P,F]),K=u.useMemo(()=>o!=="polynomial"||L.length<2?null:Ex(L,40),[o,L]),Q=u.useMemo(()=>{if(!K||K.points.length<2)return"";const Y=K.points.map(te=>({x:P(te.x),y:F(te.y)}));return ur(Y)},[K,P,F]),X=u.useMemo(()=>{if(!l)return"";let Y=[];if(o==="linear"?Y=jx(L,re.slope,re.intercept):o==="polynomial"&&K?Y=Cc(L,K.points,3):o==="smooth"&&le.length>0&&(Y=Cc(L,le,2)),Y.length<2)return"";const te=Y.map((B,E)=>`${E===0?"M":"L"} ${P(B.x).toFixed(2)} ${F(B.y1).toFixed(2)}`).join(" "),oe=[...Y].reverse().map(B=>`L ${P(B.x).toFixed(2)} ${F(B.y0).toFixed(2)}`).join(" ");return`${te} ${oe} Z`},[l,o,L,re,K,le,P,F]),ee=u.useMemo(()=>!x||L.length===0?null:Ix(L),[x,L]),V=(Y,te,oe)=>{if(!b.current)return;const B=b.current.getBoundingClientRect(),E=te.group&&G[te.group]||a;_(oe),g({x:Y.clientX-B.left,y:Y.clientY-B.top,title:te.label||"Data Point",seriesName:te.group||t||"Coordinate",value:`X: ${te.x.toLocaleString()} · Y: ${te.y.toLocaleString()}`,color:E,unit:r})},J=()=>{_(null),S()};return n.jsxs("div",{className:Oe.container,ref:b,children:[p&&re.n>=2&&n.jsx("div",{className:Oe.topBar,children:n.jsxs("div",{className:Oe.correlationChip,children:[n.jsxs("span",{children:["r = ",re.r>=0?`+${re.r.toFixed(2)}`:re.r.toFixed(2)]}),n.jsx("span",{className:Oe.chipDivider,children:"·"}),n.jsxs("span",{children:["R² = ",re.rSquared.toFixed(2)]})]})}),n.jsx("div",{className:Oe.svgWrapper,children:n.jsxs("svg",{viewBox:`0 0 ${k} ${w}`,className:Oe.chartSvg,role:"img","aria-label":"Scatter Plot Visualizer",children:[X&&n.jsx("path",{d:X,fill:a,className:Oe.confidenceBand}),W.map(Y=>{const te=F(Y);return n.jsxs("g",{children:[n.jsx("line",{x1:$.left,y1:te,x2:$.left+I,y2:te,className:Oe.gridLine}),n.jsx("text",{x:$.left-10,y:te,className:Oe.axisTextY,children:Y.toLocaleString()})]},`y-grid-${Y}`)}),R.map(Y=>{const te=P(Y);return n.jsx("line",{x1:te,y1:$.top,x2:te,y2:D,className:Oe.gridLine},`x-grid-${Y}`)}),n.jsx("line",{x1:$.left,y1:D,x2:$.left+I,y2:D,className:Oe.axisLine}),n.jsx("line",{x1:$.left,y1:$.top,x2:$.left,y2:D,className:Oe.axisLine}),R.map(Y=>{const te=P(Y);return n.jsx("text",{x:te,y:D+20,className:Oe.axisText,children:Y.toLocaleString()},`x-tick-${Y}`)}),ee&&n.jsxs("g",{"aria-label":"Mean quadrant crosshairs",children:[n.jsx("line",{x1:P(ee.meanX),y1:$.top,x2:P(ee.meanX),y2:D,className:Oe.meanLine}),n.jsx("line",{x1:$.left,y1:F(ee.meanY),x2:$.left+I,y2:F(ee.meanY),className:Oe.meanLine})]}),o==="linear"&&re.n>=2&&(()=>{const Y=P(se[0]),te=F(re.slope*se[0]+re.intercept),oe=P(se[1]),B=F(re.slope*se[1]+re.intercept);return n.jsx("line",{x1:Y,y1:te,x2:oe,y2:B,stroke:a,className:Oe.trendLine})})(),o==="smooth"&&M&&n.jsx("path",{d:M,stroke:a,className:Oe.trendLine}),o==="polynomial"&&Q&&n.jsx("path",{d:Q,stroke:a,className:Oe.trendLine}),t&&n.jsx("text",{x:$.left+I/2,y:w-8,textAnchor:"middle",className:Oe.axisTitle,children:t}),s&&n.jsx("text",{x:-($.top+j/2),y:16,transform:"rotate(-90)",textAnchor:"middle",className:Oe.axisTitle,children:s}),L.map((Y,te)=>{const oe=P(Y.x),B=F(Y.y),E=Y.group&&G[Y.group]||a,O=N===te,ie=q!==null&&Y.group!==q;let ce=.6;ie?ce=xs:O&&(ce=1);const de=O?8:H;return n.jsx("circle",{cx:oe,cy:B,r:de,fill:E,opacity:ce,className:Oe.pointNode,tabIndex:0,onPointerEnter:ae=>V(ae,Y,te),onPointerMove:ae=>V(ae,Y,te),onPointerLeave:J,onClick:()=>v==null?void 0:v(Y),onKeyDown:ae=>{(ae.key==="Enter"||ae.key===" ")&&(v==null||v(Y))},onFocus:()=>{_(te),g({x:oe,y:B,title:Y.label||"Data Point",seriesName:Y.group||t||"Coordinate",value:`X: ${Y.x.toLocaleString()} · Y: ${Y.y.toLocaleString()}`,color:E,unit:r})},onBlur:()=>{_(null),S()},"aria-label":`${Y.label||"Point"}: (${Y.x}, ${Y.y})`},`point-${te}-${Y.x}-${Y.y}`)})]})}),n.jsx(Fs,{visible:y.visible,x:y.x,y:y.y,title:y.title,seriesName:y.seriesName,value:y.value,unit:y.unit,color:y.color}),z.length>0&&n.jsx(Us,{items:z,activeIndex:C,onHover:T})]})},t1="_container_qwgca_1",n1="_organicStats_qwgca_10",s1="_statItem_qwgca_22",r1="_statLabel_qwgca_28",a1="_statValue_qwgca_37",o1="_statDivider_qwgca_42",i1="_svgWrapper_qwgca_48",l1="_chartSvg_qwgca_55",c1="_gridLine_qwgca_63",d1="_baseline_qwgca_69",u1="_axisText_qwgca_74",h1="_axisTextY_qwgca_81",m1="_barRect_qwgca_89",f1="_meanLine_qwgca_105",p1="_meanLabel_qwgca_111",g1="_trendCurve_qwgca_118",v1="_emptyState_qwgca_125",x1="_axisTitle_qwgca_135",_e={container:t1,organicStats:n1,statItem:s1,statLabel:r1,statValue:a1,statDivider:o1,svgWrapper:i1,chartSvg:l1,gridLine:c1,baseline:d1,axisText:u1,axisTextY:h1,barRect:m1,meanLine:f1,meanLabel:p1,trendCurve:g1,emptyState:v1,axisTitle:x1},Bu=({rawValues:e=[],series:t=[],unit:s="learners",accentColor:r="var(--folio-primary)",binStrategy:a="auto",binCount:o,bucketSize:i,histogramYMode:l="frequency",curveInterpolation:c="none",showSummaryStats:d=!1,showMedianMode:f=!1,showReferenceGuide:m=!1,sortField:h,sortDirection:p="asc",xLabel:x,yLabel:v,onSelectBin:b})=>{var J,Y,te;const y=u.useRef(null),{tooltipState:g,showTooltip:S,hideTooltip:C}=Mr(),[T,N]=u.useState(null),{width:_,height:k,margin:w,innerWidth:$,innerHeight:I,baselineY:j}=Lr({margins:{bottom:x?56:48,left:v?64:56}}),D=u.useMemo(()=>t&&t.length>0?t:e&&e.length>0?[{name:"Distribution",data:e}]:[],[t,e]),H=u.useMemo(()=>Os({count:D.length,accentColor:r,tierMode:"bright"}),[D.length,r]),{allNumbers:L,primaryData:U}=u.useMemo(()=>{const oe=[];let B=[];return D.forEach((E,O)=>{const ie=E.data.filter(ce=>typeof ce=="number"&&Number.isFinite(ce));oe.push(...ie),O===0&&(B=ie)}),{allNumbers:oe,primaryData:B}},[D]),G=u.useMemo(()=>gu(U),[U]),{processedSeries:z,templateBins:q,maxCountOrPct:P}=u.useMemo(()=>{if(L.length===0)return{processedSeries:[],templateBins:[],maxCountOrPct:10};const oe=Math.min(...L),B=Math.max(...L),E=Ii(U.length>0?U:L,{strategy:a,binCount:o,bucketSize:i,min:oe,max:B}),O=D.map((de,ae)=>{const fe=de.data.filter(Ce=>typeof Ce=="number"&&Number.isFinite(Ce)),be=fe.length,ve=E.map(Ce=>({x0:Ce.x0,x1:Ce.x1,count:0,percentage:0})),Pe=ve.length-1;for(const Ce of fe)for(let Me=0;Me<=Pe;Me++){const ot=ve[Me];if(Me===Pe?Ce>=ot.x0&&Ce<=ot.x1:Ce>=ot.x0&&Ce<ot.x1){ot.count++;break}}for(const Ce of ve)Ce.percentage=be>0?Ce.count/be*100:0;return{name:de.name,color:de.color||H[ae]||"var(--folio-primary)",data:fe,totalCount:be,bins:ve}});let ie=[...E];if(h==="frequency"&&O.length>0){const de=ie.map((ae,fe)=>{var be;return{bin:ae,count:((be=O[0].bins[fe])==null?void 0:be.count)??0,idx:fe}});de.sort((ae,fe)=>p==="desc"?fe.count-ae.count:ae.count-fe.count),ie=de.map(ae=>ae.bin);for(const ae of O)ae.bins=de.map(fe=>ae.bins[fe.idx])}else if(p==="desc"&&h!=="sheet"&&h!=="sheet_order"){ie.reverse();for(const de of O)de.bins.reverse()}let ce=0;for(const de of O)for(const ae of de.bins){const fe=l==="relative"?ae.percentage:ae.count;fe>ce&&(ce=fe)}return{processedSeries:O,templateBins:ie,maxCountOrPct:ce>0?ce*1.15:10}},[L,U,D,a,o,i,H,h,p,l]),F=u.useMemo(()=>js([0,P],[j,w.top],!0),[P,j,w.top]),R=u.useMemo(()=>F.ticks(5),[F]),W=Math.max(q.length,1),se=$/W,re=.75,le=Math.max(se-re*2,2),M=u.useMemo(()=>{if(!m||q.length===0||G.n===0)return null;const oe=q[0].x0,E=q[q.length-1].x1-oe;if(E<=0)return null;const O=(G.mean-oe)/E;return O<0||O>1?null:w.left+O*$},[m,q,G,w.left,$]),{curvePath:K,areaPath:Q}=u.useMemo(()=>{if(c!=="smooth"||z.length===0||q.length===0)return{curvePath:"",areaPath:""};const B=z[0].bins.map((de,ae)=>{const fe=w.left+ae*se+se/2,be=l==="relative"?de.percentage:de.count,ve=F(be);return{x:fe,y:ve}}),E=ur(B);if(!E||B.length===0)return{curvePath:"",areaPath:""};const O=B[0],ie=B[B.length-1],ce=`${E} L ${ie.x.toFixed(2)} ${j} L ${O.x.toFixed(2)} ${j} Z`;return{curvePath:E,areaPath:ce}},[c,z,q,w.left,se,l,F,j]),X=u.useCallback((oe,B,E,O)=>{if(!y.current)return;const ie=y.current.getBoundingClientRect(),ce=`${B.percentage.toFixed(1)}%`;S({x:oe.clientX-ie.left,y:oe.clientY-ie.top,title:`Range: [${B.x0} – ${B.x1}]`,seriesName:E,value:B.count,unit:`${s} (${ce})`,color:O})},[S,s]),ee=u.useCallback(()=>{C()},[C]);if(L.length===0)return n.jsx("div",{className:_e.emptyState,children:"No valid numerical data available for histogram distribution."});const V=z.length>1;return n.jsxs("div",{className:_e.container,ref:y,children:[(d||f)&&G.n>0&&n.jsxs("div",{className:_e.organicStats,role:"region","aria-label":"Distribution Summary Statistics",children:[d&&n.jsxs(n.Fragment,{children:[n.jsxs("span",{className:_e.statItem,children:[n.jsx("span",{className:_e.statLabel,children:"N"}),n.jsx("span",{className:_e.statValue,children:G.n.toLocaleString()})]}),n.jsx("span",{className:_e.statDivider,"aria-hidden":"true",children:"·"}),n.jsxs("span",{className:_e.statItem,children:[n.jsx("span",{className:_e.statLabel,children:"Mean (μ)"}),n.jsx("span",{className:_e.statValue,children:G.mean})]})]}),f&&n.jsxs(n.Fragment,{children:[d&&n.jsx("span",{className:_e.statDivider,"aria-hidden":"true",children:"·"}),n.jsxs("span",{className:_e.statItem,children:[n.jsx("span",{className:_e.statLabel,children:"Median"}),n.jsx("span",{className:_e.statValue,children:G.median})]}),G.mode!==void 0&&n.jsxs(n.Fragment,{children:[n.jsx("span",{className:_e.statDivider,"aria-hidden":"true",children:"·"}),n.jsxs("span",{className:_e.statItem,children:[n.jsx("span",{className:_e.statLabel,children:"Mode"}),n.jsx("span",{className:_e.statValue,children:G.mode})]})]})]}),d&&n.jsxs(n.Fragment,{children:[n.jsx("span",{className:_e.statDivider,"aria-hidden":"true",children:"·"}),n.jsxs("span",{className:_e.statItem,children:[n.jsx("span",{className:_e.statLabel,children:"Std Dev (σ)"}),n.jsxs("span",{className:_e.statValue,children:["±",G.stdDev]})]})]})]}),n.jsx("div",{className:_e.svgWrapper,children:n.jsxs("svg",{viewBox:`0 0 ${_} ${k}`,className:_e.chartSvg,role:"img","aria-label":"Histogram Frequency Distribution",children:[n.jsx("defs",{children:n.jsxs("linearGradient",{id:"hist-trend-curve-grad",x1:"0",y1:"0",x2:"0",y2:"1",children:[n.jsx("stop",{offset:"0%",stopColor:((J=z[0])==null?void 0:J.color)||r,stopOpacity:"0.25"}),n.jsx("stop",{offset:"100%",stopColor:((Y=z[0])==null?void 0:Y.color)||r,stopOpacity:"0.0"})]})}),R.map(oe=>{const B=F(oe);return n.jsxs("g",{children:[n.jsx("line",{x1:w.left,y1:B,x2:w.left+$,y2:B,className:_e.gridLine}),n.jsx("text",{x:w.left-10,y:B,className:_e.axisTextY,children:l==="relative"?`${oe.toFixed(0)}%`:oe.toLocaleString()})]},`y-grid-${oe}`)}),n.jsx("line",{x1:w.left,y1:j,x2:w.left+$,y2:j,className:_e.baseline}),x&&n.jsx("text",{x:w.left+$/2,y:k-8,textAnchor:"middle",className:_e.axisTitle,children:x}),v&&n.jsx("text",{x:-(w.top+I/2),y:16,transform:"rotate(-90)",textAnchor:"middle",className:_e.axisTitle,children:v}),z.map((oe,B)=>{const E=B>0,O=T===oe.name,de=T!==null&&!O?xs:E?.6:.85;return n.jsx("g",{children:oe.bins.map((ae,fe)=>{const be=w.left+fe*se+re,ve=l==="relative"?ae.percentage:ae.count,Pe=F(ve),Ce=Math.max(j-Pe,0);return n.jsx("rect",{x:be,y:Pe,width:le,height:Ce,rx:3,ry:3,fill:oe.color,stroke:E?oe.color:"none",strokeWidth:E?1:0,fillOpacity:de,className:_e.barRect,tabIndex:0,onPointerEnter:Me=>X(Me,ae,oe.name,oe.color),onPointerMove:Me=>X(Me,ae,oe.name,oe.color),onPointerLeave:ee,onClick:()=>b==null?void 0:b({x0:ae.x0,x1:ae.x1,count:ae.count}),onKeyDown:Me=>{(Me.key==="Enter"||Me.key===" ")&&(b==null||b({x0:ae.x0,x1:ae.x1,count:ae.count}))},"aria-label":`${oe.name} Range [${ae.x0} – ${ae.x1}]: ${ae.count} ${s} (${ae.percentage.toFixed(1)}%)`},`rect-${B}-${fe}-${ae.x0}-${ae.x1}`)})},`series-bins-${oe.name}-${B}`)}),c==="smooth"&&K&&n.jsxs("g",{className:_e.trendOverlay,children:[Q&&n.jsx("path",{d:Q,fill:"url(#hist-trend-curve-grad)"}),n.jsx("path",{d:K,className:_e.trendCurve,stroke:((te=z[0])==null?void 0:te.color)||r})]}),m&&M!==null&&n.jsxs("g",{className:_e.meanGuideGroup,children:[n.jsx("line",{x1:M,y1:w.top,x2:M,y2:j,className:_e.meanLine}),n.jsxs("text",{x:M+4,y:w.top+10,className:_e.meanLabel,children:["Mean: ",G.mean]})]}),q.map((oe,B)=>{const E=w.left+B*se+se/2;return n.jsxs("text",{x:E,y:j+20,className:_e.axisText,children:[oe.x0,"–",oe.x1]},`axis-label-${B}-${oe.x0}-${oe.x1}`)})]})}),V&&n.jsx(Us,{items:z.map(oe=>({id:oe.name,name:oe.name,color:oe.color})),activeIndex:T!==null?z.findIndex(oe=>oe.name===T):null,onHover:oe=>{var B;oe==null?N(null):N(((B=z[oe])==null?void 0:B.name)||null)}}),n.jsx(Fs,{visible:g.visible,x:g.x,y:g.y,title:g.title,seriesName:g.seriesName,value:g.value,unit:g.unit||s,color:g.color})]})},b1="_routerContainer_8p17x_1",y1="_emptyState_8p17x_9",_1="_emptyTitle_8p17x_25",w1="_emptySubtitle_8p17x_33",on={routerContainer:b1,emptyState:y1,emptyTitle:_1,emptySubtitle:w1},Pu=({dataset:e,overrideType:t,accentColor:s})=>{var c,d,f,m,h,p,x,v,b,y,g,S,C,T,N,_,k,w,$,I,j,D,H,L,U,G,z,q,P,F,R,W,se,re,le,M,K,Q,X,ee,V,J,Y,te,oe,B,E,O,ie,ce,de,ae,fe;const r=t||e.chartType||"bar",a=s||e.nodeId&&Eu[e.nodeId]||"var(--folio-primary)",o=e.categories||[],i=e.series||[],l=e.unit||((c=e.visualConfig)==null?void 0:c.unit);if(r==="bar")return n.jsx("div",{className:on.routerContainer,children:n.jsx(Lu,{categories:o,series:i,unit:l,accentColor:a,variant:((d=e.visualConfig)==null?void 0:d.barVariant)||"standard",targetValue:(f=e.visualConfig)==null?void 0:f.targetValue,targetLabel:(m=e.visualConfig)==null?void 0:m.targetLabel,orientation:((h=e.visualConfig)==null?void 0:h.barOrientation)||"vertical",stacked:((p=e.visualConfig)==null?void 0:p.stacked)||!1,showValues:((x=e.visualConfig)==null?void 0:x.showValues)||!1,xLabel:(v=e.visualConfig)==null?void 0:v.xLabel,yLabel:(b=e.visualConfig)==null?void 0:b.yLabel})});if(r==="line")return n.jsx("div",{className:on.routerContainer,children:n.jsx(Mu,{categories:o,series:i,unit:l,accentColor:a,curveInterpolation:((y=e.visualConfig)==null?void 0:y.curveInterpolation)==="linear"||((g=e.visualConfig)==null?void 0:g.curveInterpolation)==="polynomial"?"straight":(S=e.visualConfig)==null?void 0:S.curveInterpolation,showAreaFill:(C=e.visualConfig)==null?void 0:C.showAreaFill,markerSize:(T=e.visualConfig)==null?void 0:T.markerSize,autoScaleY:(N=e.visualConfig)==null?void 0:N.autoScaleY,startAtZero:(_=e.visualConfig)==null?void 0:_.startAtZero,showValues:(k=e.visualConfig)==null?void 0:k.showValues,xLabel:(w=e.visualConfig)==null?void 0:w.xLabel,yLabel:($=e.visualConfig)==null?void 0:$.yLabel})});if(r==="donut"){const be=i.length>0?i[0].data.map(ve=>typeof ve=="number"&&Number.isFinite(ve)?ve:0):[];return n.jsx("div",{className:on.routerContainer,children:n.jsx(Du,{categories:o,data:be,unit:l,accentColor:a,donutVariant:(I=e.visualConfig)==null?void 0:I.donutVariant,groupOthers:(j=e.visualConfig)==null?void 0:j.groupOthers,showValues:(D=e.visualConfig)==null?void 0:D.showValues,seriesName:(H=i[0])==null?void 0:H.name})})}if(r==="scatter"){let be=e.scatterPoints||[];if(be.length===0&&i.length>=2){const ve=o.length,Pe=[];for(let Ce=0;Ce<ve;Ce++){const Me=i[0].data[Ce],ot=i[1].data[Ce];typeof Me=="number"&&Number.isFinite(Me)&&typeof ot=="number"&&Number.isFinite(ot)&&Pe.push({x:Me,y:ot,label:o[Ce],group:i[0].name})}be=Pe}return n.jsx("div",{className:on.routerContainer,children:n.jsx(Ru,{points:be,xLabel:((L=e.visualConfig)==null?void 0:L.xLabel)||(be===e.scatterPoints||(U=i[0])==null?void 0:U.name),yLabel:((G=e.visualConfig)==null?void 0:G.yLabel)||(be===e.scatterPoints||(z=i[1])==null?void 0:z.name),unit:l,accentColor:a,curveInterpolation:(q=e.visualConfig)==null?void 0:q.curveInterpolation,loessBandwidth:(P=e.visualConfig)==null?void 0:P.loessBandwidth,showAreaFill:(F=e.visualConfig)==null?void 0:F.showAreaFill,markerSize:(R=e.visualConfig)==null?void 0:R.markerSize,autoScaleY:(W=e.visualConfig)==null?void 0:W.autoScaleY,autoScaleX:(se=e.visualConfig)==null?void 0:se.autoScaleX,startAtZero:(re=e.visualConfig)==null?void 0:re.startAtZero,startAtZeroX:(le=e.visualConfig)==null?void 0:le.startAtZeroX,showCorrelationChip:(M=e.visualConfig)==null?void 0:M.showCorrelationChip,showReferenceGuide:(K=e.visualConfig)==null?void 0:K.showReferenceGuide})})}if(r==="histogram"){const be=((Q=e.rawValues)==null?void 0:Q.filter(ve=>typeof ve=="number"&&Number.isFinite(ve)))||(i.length>0?i[0].data.filter(ve=>typeof ve=="number"&&Number.isFinite(ve)):[]);return n.jsx("div",{className:on.routerContainer,children:n.jsx(Bu,{rawValues:be,series:i,binStrategy:(X=e.visualConfig)==null?void 0:X.binStrategy,binCount:(ee=e.visualConfig)==null?void 0:ee.binCount,bucketSize:(V=e.visualConfig)==null?void 0:V.bucketSize,histogramYMode:(J=e.visualConfig)==null?void 0:J.histogramYMode,curveInterpolation:((Y=e.visualConfig)==null?void 0:Y.curveInterpolation)==="linear"||((te=e.visualConfig)==null?void 0:te.curveInterpolation)==="polynomial"?"straight":(oe=e.visualConfig)==null?void 0:oe.curveInterpolation,showSummaryStats:(B=e.visualConfig)==null?void 0:B.showSummaryStats,showMedianMode:(E=e.visualConfig)==null?void 0:E.showMedianMode,showReferenceGuide:(O=e.visualConfig)==null?void 0:O.showReferenceGuide,sortBy:(ie=e.visualConfig)==null?void 0:ie.sortBy,sortField:(ce=e.visualConfig)==null?void 0:ce.sortField,sortDirection:(de=e.visualConfig)==null?void 0:de.sortDirection,xLabel:(ae=e.visualConfig)==null?void 0:ae.xLabel,yLabel:(fe=e.visualConfig)==null?void 0:fe.yLabel,unit:l,accentColor:a})})}return n.jsxs("div",{className:on.emptyState,children:[n.jsx("div",{className:on.emptyTitle,children:"Data Distribution Pending"}),n.jsx("div",{className:on.emptySubtitle,children:"The designated visualizer for this indicator is being formatted."})]})},S1="_wireframeWrapper_uk8sj_8",C1="_wireframeSvg_uk8sj_23",k1="_axisLine_uk8sj_30",N1="_gridLine_uk8sj_37",j1="_ghostBar_uk8sj_44",T1="_ghostBarAccent_uk8sj_52",yt={wireframeWrapper:S1,wireframeSvg:C1,axisLine:k1,gridLine:N1,ghostBar:j1,ghostBarAccent:T1},qi=u.memo(({className:e})=>n.jsx("div",{className:`${yt.wireframeWrapper} ${e||""}`.trim(),"aria-hidden":"true",tabIndex:-1,children:n.jsxs("svg",{className:yt.wireframeSvg,viewBox:"0 0 540 220",preserveAspectRatio:"none",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[n.jsx("line",{x1:"45",y1:"40",x2:"515",y2:"40",className:yt.gridLine}),n.jsx("line",{x1:"45",y1:"90",x2:"515",y2:"90",className:yt.gridLine}),n.jsx("line",{x1:"45",y1:"140",x2:"515",y2:"140",className:yt.gridLine}),n.jsx("line",{x1:"45",y1:"20",x2:"45",y2:"190",className:yt.axisLine}),n.jsx("line",{x1:"45",y1:"190",x2:"515",y2:"190",className:yt.axisLine}),n.jsx("rect",{x:"75",y:"100",width:"48",height:"90",rx:"4",className:yt.ghostBar}),n.jsx("rect",{x:"165",y:"60",width:"48",height:"130",rx:"4",className:yt.ghostBarAccent}),n.jsx("rect",{x:"255",y:"120",width:"48",height:"70",rx:"4",className:yt.ghostBar}),n.jsx("rect",{x:"345",y:"45",width:"48",height:"145",rx:"4",className:yt.ghostBarAccent}),n.jsx("rect",{x:"435",y:"85",width:"48",height:"105",rx:"4",className:yt.ghostBar})]})}));qi.displayName="ChartGhostWireframe";const I1="_container_1md1z_11",A1="_publicNoticeWrapper_1md1z_28",E1="_logoWrapper_1md1z_47",$1="_kicker_1md1z_55",L1="_title_1md1z_64",M1="_description_1md1z_73",D1="_diagnosticPanel_1md1z_84",R1="_diagBadge_1md1z_103",B1="_diagBadgeUnlinked_1md1z_118",P1="_diagBadgeConnection_1md1z_124",O1="_diagBadgeDataFormat_1md1z_130",F1="_diagTitle_1md1z_136",U1="_diagHint_1md1z_145",G1="_actionRow_1md1z_153",lt={container:I1,publicNoticeWrapper:A1,logoWrapper:E1,kicker:$1,title:L1,description:M1,diagnosticPanel:D1,diagBadge:R1,diagBadgeUnlinked:B1,diagBadgeConnection:P1,diagBadgeDataFormat:O1,diagTitle:F1,diagHint:U1,actionRow:G1},Ou=({chartId:e,nodeTitle:t,category:s="unlinked",errorMessage:r,hasSheetUrl:a=!1,onEdit:o,className:i,headline:l,description:c})=>{const{isDevMode:d,isDesktop:f}=Ne(),m=d&&f,h=u.useMemo(()=>s&&s!=="none"?s:a?r?"connection_error":"data_format":"unlinked",[s,a,r]),p=u.useMemo(()=>{switch(h){case"connection_error":return{badgeClass:lt.diagBadgeConnection,badgeLabel:"Connection Issue",title:"Unable to Access Google Sheet",hint:r||'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:lt.diagBadgeDataFormat,badgeLabel:"Data Range Issue",title:"Empty or Unrecognized Data Range",hint:r||"The selected tab or range contains no valid rows or numeric data. Check the tab name and cell coordinates."};case"unlinked":default:return{badgeClass:lt.diagBadgeUnlinked,badgeLabel:"Unlinked Source",title:"No Google Sheet Linked",hint:"Link an official Google Sheet to automatically ingest and publish validated indicator metrics."}}},[h,r]);return n.jsxs("div",{className:`${lt.container} ${i||""}`.trim(),role:"region","aria-label":"Indicator Data Notice",tabIndex:-1,children:[n.jsx(qi,{}),m?n.jsxs("div",{className:lt.diagnosticPanel,children:[n.jsx("span",{className:`${lt.diagBadge} ${p.badgeClass}`,children:p.badgeLabel}),n.jsx("h4",{className:lt.diagTitle,children:p.title}),n.jsx("p",{className:lt.diagHint,children:p.hint}),o&&n.jsx("div",{className:lt.actionRow,children:n.jsx(he,{variant:"admin",size:"xs",onClick:o,"aria-label":e?`Edit chart ${e}`:"Edit chart",children:"✎ Edit"})})]}):n.jsxs("div",{className:lt.publicNoticeWrapper,children:[n.jsx("div",{className:lt.logoWrapper,children:n.jsx(pr,{sides:8,waviness:.15,radius:18,fill:"var(--folio-primary)"})}),n.jsx("div",{className:lt.kicker,children:t?`${t} Indicator`:"Official Indicator"}),n.jsx("h3",{className:lt.title,children:l||"Indicator Data Pending"}),n.jsx("p",{className:lt.description,children:c||"The designated coordinator is finalizing official validation and records encoding for this indicator. Data receipts will appear once published."})]})]})},H1="_backdrop_1k8iw_12",z1="_backdropOpen_1k8iw_27",q1="_drawer_1k8iw_32",V1="_positionRight_1k8iw_49",W1="_positionLeft_1k8iw_54",K1="_drawerOpen_1k8iw_59",Y1="_size_sm_1k8iw_64",X1="_size_md_1k8iw_68",J1="_size_lg_1k8iw_72",Z1="_size_xl_1k8iw_76",Q1="_size_full_1k8iw_80",ew="_companionViewport_1k8iw_94",tw="_companionLeft_1k8iw_108",nw="_companionRight_1k8iw_114",sw="_header_1k8iw_127",rw="_headerTitleWrapper_1k8iw_138",aw="_kicker_1k8iw_145",ow="_title_1k8iw_154",iw="_headerControls_1k8iw_167",lw="_closeButton_1k8iw_174",cw="_tabsContainer_1k8iw_209",dw="_tabList_1k8iw_216",uw="_tabButton_1k8iw_224",hw="_tabActive_1k8iw_263",mw="_tabCompleted_1k8iw_269",fw="_tabBadge_1k8iw_279",pw="_tabLabel_1k8iw_304",gw="_body_1k8iw_311",vw="_footer_1k8iw_322",xw="_footerLeft_1k8iw_334",bw="_footerRight_1k8iw_340",ke={backdrop:H1,backdropOpen:z1,drawer:q1,positionRight:V1,positionLeft:W1,drawerOpen:K1,size_sm:Y1,size_md:X1,size_lg:J1,size_xl:Z1,size_full:Q1,companionViewport:ew,companionLeft:tw,companionRight:nw,header:sw,headerTitleWrapper:rw,kicker:aw,title:ow,headerControls:iw,closeButton:lw,tabsContainer:cw,tabList:dw,tabButton:uw,tabActive:hw,tabCompleted:mw,tabBadge:fw,tabLabel:pw,body:gw,footer:vw,footerLeft:xw,footerRight:bw},Vi=({isOpen:e,onClose:t,title:s,kicker:r,headerActions:a,showCloseButton:o=!0,closeOnOutsideClick:i=!0,closeOnBackdropClick:l=!0,position:c="right",size:d="md",tabs:f,activeTab:m,onTabChange:h,tabsContent:p,footer:x,footerLeft:v,footerRight:b,children:y,className:g,bodyClassName:S,ariaLabel:C,ariaLabelledBy:T="canonical-drawer-title",ariaDescribedBy:N,onConfirm:_,enableCtrlEnter:k=!0,companionContent:w})=>{const[$,I]=u.useState(!1),j=u.useRef(null);if(u.useEffect(()=>{I(!0)},[]),u.useEffect(()=>{if(e)return ci(),()=>{di()}},[e]),u.useEffect(()=>{if(!e)return;const P=j.current;return P&&ui(P),()=>{P&&hi(P)}},[e]),u.useEffect(()=>{if(!e)return;const P=F=>{const R=j.current&&(j.current.contains(document.activeElement)||mi(j.current));if(F.key==="Escape"&&R){F.preventDefault(),t();return}if(k&&fi(F)&&R){if(F.preventDefault(),F.stopPropagation(),_){_();return}if(j.current){const W=pi(j.current);W&&gi(W)}return}};return window.addEventListener("keydown",P),()=>window.removeEventListener("keydown",P)},[e,t,k,_]),!$||!e&&typeof document<"u")return null;const D=i&&l,H=P=>{!D&&P.target===P.currentTarget&&P.preventDefault()},L=P=>{D&&P.target===P.currentTarget&&t()},U=!!(x||v||b),G=c==="left"?ke.positionLeft:ke.positionRight,z=ke[`size_${d}`]||ke.size_md,q=n.jsxs("div",{className:`${ke.backdrop} ${e?ke.backdropOpen:""}`,onMouseDown:H,onClick:L,role:"presentation",children:[w&&n.jsx("div",{className:`${ke.companionViewport} ${c==="left"?ke.companionRight:ke.companionLeft}`,onClick:P=>P.stopPropagation(),onMouseDown:P=>P.stopPropagation(),children:w}),n.jsxs("aside",{ref:j,className:`${ke.drawer} ${G} ${z} ${e?ke.drawerOpen:""} ${g||""}`,role:"dialog","aria-modal":"true","aria-label":C,"aria-labelledby":s?T:void 0,"aria-describedby":N,children:[(s||r||o||a)&&n.jsxs("div",{className:ke.header,children:[n.jsxs("div",{className:ke.headerTitleWrapper,children:[r&&n.jsx("span",{className:ke.kicker,children:r}),s&&n.jsx("h2",{id:T,className:ke.title,children:s})]}),n.jsxs("div",{className:ke.headerControls,children:[a,o&&n.jsx("button",{type:"button",className:ke.closeButton,onClick:t,"aria-label":"Close drawer",children:"✕"})]})]}),p?n.jsx("div",{className:ke.tabsContainer,children:p}):f&&f.length>0?n.jsx("nav",{className:ke.tabsContainer,role:"tablist","aria-label":"Drawer sections",children:n.jsx("div",{className:ke.tabList,children:f.map(P=>{const F=m===P.id;return n.jsxs("button",{type:"button",role:"tab",id:`drawer-tab-${P.id}`,"aria-selected":F,"aria-controls":`drawer-panel-${P.id}`,className:`${ke.tabButton} ${F?ke.tabActive:""} ${P.completed?ke.tabCompleted:""}`,onClick:()=>{!P.disabled&&h&&h(P.id)},disabled:P.disabled,children:[P.badge!==void 0&&P.badge!==null&&n.jsx("span",{className:ke.tabBadge,children:P.badge}),n.jsx("span",{className:ke.tabLabel,children:P.label})]},String(P.id))})})}):null,n.jsx("div",{className:`${ke.body} ${S||""}`,children:y}),U&&n.jsx("footer",{className:ke.footer,children:x||n.jsxs(n.Fragment,{children:[n.jsx("div",{className:ke.footerLeft,children:v}),n.jsx("div",{className:ke.footerRight,children:b})]})})]})]});return fr.createPortal(q,document.body)},yw="_accordionSection_1dyhk_6",_w="_summary_1dyhk_12",ww="_summaryLeft_1dyhk_35",Sw="_chevron_1dyhk_41",Cw="_title_1dyhk_57",kw="_badgeWrapper_1dyhk_76",Nw="_caption_1dyhk_81",jw="_content_1dyhk_89",ln={accordionSection:yw,summary:_w,summaryLeft:ww,chevron:Sw,title:Cw,badgeWrapper:kw,caption:Nw,content:jw},wt=({id:e,name:t,title:s,defaultOpen:r=!1,isOpen:a,onToggle:o,badge:i,caption:l,children:c,className:d=""})=>{const f=u.useId(),m=e||f,[h,p]=u.useState(r),x=typeof a=="boolean",v=x?a:h;u.useEffect(()=>{if(!t||x)return;const y=g=>{var C,T;const S=g;((C=S.detail)==null?void 0:C.name)===t&&((T=S.detail)==null?void 0:T.id)!==m&&p(!1)};return window.addEventListener("accordion-open",y),()=>{window.removeEventListener("accordion-open",y)}},[t,m,x]);const b=y=>{const g=y.currentTarget.open;x||p(g),t&&g&&window.dispatchEvent(new CustomEvent("accordion-open",{detail:{name:t,id:m}})),o==null||o(g)};return n.jsxs("details",{id:m,name:t,className:`${ln.accordionSection} ${d}`.trim(),open:v,onToggle:b,children:[n.jsxs("summary",{className:ln.summary,children:[n.jsxs("div",{className:ln.summaryLeft,children:[n.jsx("span",{className:ln.chevron,"aria-hidden":"true",children:n.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("polyline",{points:"9 18 15 12 9 6"})})}),n.jsx("span",{className:ln.title,children:s})]}),i&&n.jsx("div",{className:ln.badgeWrapper,children:i})]}),l&&n.jsx("p",{className:ln.caption,children:l}),n.jsx("div",{className:ln.content,children:c})]})},Tw="_tier_1t31h_1",Iw="_tierHeader_1t31h_8",Aw="_tierTitle_1t31h_14",Ew="_tierSubtitle_1t31h_23",$w="_tierContent_1t31h_30",Js={tier:Tw,tierHeader:Iw,tierTitle:Aw,tierSubtitle:Ew,tierContent:$w},Lw=({title:e,subtitle:t,children:s,className:r=""})=>n.jsxs("section",{className:`${Js.tier} ${r}`.trim(),"aria-label":e,children:[n.jsxs("div",{className:Js.tierHeader,children:[n.jsx("h3",{className:Js.tierTitle,children:e}),t&&n.jsx("p",{className:Js.tierSubtitle,children:t})]}),n.jsx("div",{className:Js.tierContent,children:s})]}),Mw=e=>n.jsx(he,{variant:"revolving-outline",...e}),Dw="_formGroup_kpi19_1",Rw="_labelRow_kpi19_8",Bw="_label_kpi19_8",Pw="_selectWrapper_kpi19_23",Ow="_hiddenSelect_kpi19_29",Fw="_trigger_kpi19_43",Uw="_triggerOpen_kpi19_70",Gw="_triggerValue_kpi19_75",Hw="_triggerLabel_kpi19_85",zw="_chevron_kpi19_90",qw="_chevronOpen_kpi19_96",Vw="_dropdown_kpi19_101",Ww="_option_kpi19_119",Kw="_optionSelected_kpi19_137",Yw="_checkIcon_kpi19_142",Xw="_optionText_kpi19_154",Jw="_optionLabel_kpi19_164",Zw="_colCode_kpi19_170",Qw="_hint_kpi19_179",Ge={formGroup:Dw,labelRow:Rw,label:Bw,selectWrapper:Pw,hiddenSelect:Ow,trigger:Fw,triggerOpen:Uw,triggerValue:Gw,triggerLabel:Hw,chevron:zw,chevronOpen:qw,dropdown:Vw,option:Ww,optionSelected:Kw,checkIcon:Yw,optionText:Xw,optionLabel:Jw,colCode:Zw,hint:Qw},Dn=({id:e,label:t,value:s,onChange:r,columns:a,hint:o,className:i=""})=>{const[l,c]=u.useState(!1),d=u.useRef(null),f=u.useRef(null),m=u.useId(),h=a.find(x=>x.index===s);u.useEffect(()=>{if(!l)return;const x=v=>{d.current&&!d.current.contains(v.target)&&c(!1)};return document.addEventListener("mousedown",x),document.addEventListener("touchstart",x),()=>{document.removeEventListener("mousedown",x),document.removeEventListener("touchstart",x)}},[l]);const p=x=>{if(x.key==="Escape"){c(!1);return}if(x.key==="Enter"||x.key===" "){x.preventDefault(),c(v=>!v);return}if(x.key==="ArrowDown"||x.key==="ArrowUp"){if(x.preventDefault(),!l){c(!0);return}const v=a.findIndex(y=>y.index===s),b=x.key==="ArrowDown"?Math.min(a.length-1,v+1):Math.max(0,v-1);a[b]&&r(a[b].index)}};return n.jsxs("div",{className:`${Ge.formGroup} ${i}`.trim(),ref:d,children:[n.jsx("div",{className:Ge.labelRow,children:n.jsx("label",{htmlFor:e,className:Ge.label,onClick:()=>c(x=>!x),children:t})}),n.jsxs("div",{className:Ge.selectWrapper,children:[n.jsx("select",{id:`${e}-native`,className:Ge.hiddenSelect,value:s,onChange:x=>r(Number(x.target.value)),tabIndex:-1,"aria-hidden":"true",children:a.map(x=>{const v=x.index>=0?` [${ct(x.index)}]`:"";return n.jsxs("option",{value:x.index,children:[x.label,v]},x.index)})}),n.jsxs("button",{type:"button",id:e,className:`${Ge.trigger} ${l?Ge.triggerOpen:""}`,"aria-haspopup":"listbox","aria-expanded":l,"aria-controls":m,onClick:()=>c(x=>!x),onKeyDown:p,children:[n.jsxs("div",{className:Ge.triggerValue,children:[n.jsx("span",{className:Ge.triggerLabel,children:(h==null?void 0:h.label)||"Select column..."}),h&&h.index>=0&&n.jsxs("span",{className:Ge.colCode,children:["[",ct(h.index),"]"]})]}),n.jsx("svg",{className:`${Ge.chevron} ${l?Ge.chevronOpen:""}`,width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true",children:n.jsx("path",{d:"M2.5 4.5L6 8L9.5 4.5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]}),l&&n.jsx("ul",{id:m,className:Ge.dropdown,role:"listbox",ref:f,"aria-label":t,children:a.map(x=>{const v=x.index===s;return n.jsxs("li",{role:"option","aria-selected":v,className:`${Ge.option} ${v?Ge.optionSelected:""}`,onClick:()=>{r(x.index),c(!1)},children:[n.jsx("span",{className:Ge.checkIcon,"aria-hidden":"true",children:v?"✓":""}),n.jsxs("span",{className:Ge.optionText,children:[n.jsx("span",{className:Ge.optionLabel,children:x.label}),x.index>=0&&n.jsxs("span",{className:Ge.colCode,children:["[",ct(x.index),"]"]})]})]},x.index)})})]}),o&&n.jsx("span",{className:Ge.hint,children:o})]})},eS="_badge_14e5p_1",tS="_text_14e5p_16",nS="_number_14e5p_22",lo={badge:eS,text:tS,number:nS},sS=({type:e,className:t=""})=>{const s=e==="number",r=s?"123":"TEXT",a=s?lo.number:lo.text;return n.jsx("span",{className:`${lo.badge} ${a} ${t}`.trim(),title:s?"Numeric metric column":"Categorical text dimension","aria-label":s?"Numeric data":"Text data",children:r})},rS="_container_a3fri_8",aS="_row_a3fri_16",oS="_rowDragging_a3fri_36",iS="_rowDragOver_a3fri_42",lS="_dragHandle_a3fri_47",cS="_content_a3fri_77",dS="_microControls_a3fri_89",uS="_microBtn_a3fri_98",Ut={container:rS,row:aS,rowDragging:oS,rowDragOver:iS,dragHandle:lS,content:cS,microControls:dS,microBtn:uS};function Fu({items:e,keyExtractor:t,onReorder:s,renderItem:r,showMicroArrows:a=!0,className:o="",ariaLabel:i="Draggable list"}){const[l,c]=u.useState(null),[d,f]=u.useState(null),m=u.useCallback((b,y)=>{c(y),b.dataTransfer.effectAllowed="move",b.dataTransfer.setData("text/plain",String(y))},[]),h=u.useCallback((b,y)=>{b.preventDefault(),b.dataTransfer.dropEffect="move",d!==y&&f(y)},[d]),p=u.useCallback((b,y)=>{if(b.preventDefault(),l===null||l===y){c(null),f(null);return}const g=[...e],[S]=g.splice(l,1);g.splice(y,0,S),s(g),c(null),f(null)},[l,e,s]),x=u.useCallback(()=>{c(null),f(null)},[]),v=u.useCallback((b,y)=>{const g=y==="up"?b-1:b+1;if(g<0||g>=e.length)return;const S=[...e],C=S[b];S[b]=S[g],S[g]=C,s(S)},[e,s]);return n.jsx("div",{className:`${Ut.container} ${o}`.trim(),role:"list","aria-label":i,children:e.map((b,y)=>{const g=t(b,y),S=l===y,C=d===y&&l!==y,T=y>0,N=y<e.length-1,_={index:y,isDragging:S,isDragOver:C,moveUp:()=>v(y,"up"),moveDown:()=>v(y,"down"),canMoveUp:T,canMoveDown:N};return n.jsxs("div",{className:`${Ut.row} ${S?Ut.rowDragging:""} ${C?Ut.rowDragOver:""}`,draggable:!0,onDragStart:k=>m(k,y),onDragOver:k=>h(k,y),onDrop:k=>p(k,y),onDragEnd:x,role:"listitem",tabIndex:0,children:[n.jsx("span",{className:Ut.dragHandle,title:"Drag to reorder","aria-label":"Drag handle",children:"⋮⋮"}),n.jsx("div",{className:Ut.content,children:r(b,_)}),a&&n.jsxs("div",{className:Ut.microControls,children:[n.jsx("button",{type:"button",className:Ut.microBtn,disabled:!T,onClick:k=>{k.stopPropagation(),v(y,"up")},"aria-label":"Move item up",title:"Move up",children:"↑"}),n.jsx("button",{type:"button",className:Ut.microBtn,disabled:!N,onClick:k=>{k.stopPropagation(),v(y,"down")},"aria-label":"Move item down",title:"Move down",children:"↓"})]})]},g)})})}const hS="_toolbar_sg8wo_1",mS="_titleRow_sg8wo_8",fS="_title_sg8wo_8",pS="_countBadge_sg8wo_21",gS="_actions_sg8wo_30",vS="_actionBtn_sg8wo_36",jn={toolbar:hS,titleRow:mS,title:fS,countBadge:pS,actions:gS,actionBtn:vS},xS=({title:e="Numbers to Show",selectedCount:t,totalCount:s,onSelectAll:r,onClear:a,className:o=""})=>n.jsxs("div",{className:`${jn.toolbar} ${o}`.trim(),children:[n.jsxs("div",{className:jn.titleRow,children:[n.jsx("span",{className:jn.title,children:e}),t!==void 0&&s!==void 0&&n.jsxs("span",{className:jn.countBadge,title:`${t} of ${s} series selected`,children:[t,"/",s]})]}),n.jsxs("div",{className:jn.actions,children:[n.jsx("button",{type:"button",className:jn.actionBtn,onClick:r,title:"Select all columns with numbers",children:"Select All Numbers"}),n.jsx("button",{type:"button",className:jn.actionBtn,onClick:a,title:"Deselect all series",children:"Clear All"})]})]}),bS="_container_15sk1_1",yS="_header_15sk1_8",_S="_label_15sk1_14",wS="_valueText_15sk1_22",SS="_trackWrapper_15sk1_29",CS="_rangeInput_15sk1_37",kS="_tiersRow_15sk1_113",NS="_tierBtn_15sk1_120",jS="_tierBtnActive_15sk1_149",TS="_tierNotch_15sk1_154",IS="_tierNotchActive_15sk1_161",kt={container:bS,header:yS,label:_S,valueText:wS,trackWrapper:SS,rangeInput:CS,tiersRow:kS,tierBtn:NS,tierBtnActive:jS,tierNotch:TS,tierNotchActive:IS},Uu=({id:e,label:t,value:s,min:r=.2,max:a=.8,step:o=.05,tiers:i=[],badgeFormatter:l,onChange:c,disabled:d=!1})=>{const f=i.reduce((h,p)=>h?Math.abs(p.value-s)<Math.abs(h.value-s)?p:h:p,null),m=l?l(s):`${Math.round(s*100)}%`;return n.jsxs("div",{className:kt.container,children:[n.jsxs("div",{className:kt.header,children:[n.jsx("label",{htmlFor:e,className:kt.label,children:t}),n.jsx("span",{className:kt.valueText,"aria-live":"polite",children:m})]}),n.jsx("div",{className:kt.trackWrapper,children:n.jsx("input",{id:e,type:"range",min:r,max:a,step:o,value:s,disabled:d,onChange:h=>c(parseFloat(h.target.value)),className:kt.rangeInput,"aria-valuemin":r,"aria-valuemax":a,"aria-valuenow":s,"aria-valuetext":m})}),i.length>0&&n.jsx("div",{className:kt.tiersRow,children:i.map(h=>{const p=f&&Math.abs(f.value-h.value)<.01;return n.jsxs("button",{type:"button",onClick:()=>c(h.value),disabled:d,className:`${kt.tierBtn} ${p?kt.tierBtnActive:""}`,title:`Snap to ${h.label} (${Math.round(h.value*100)}%)`,children:[n.jsx("span",{className:`${kt.tierNotch} ${p?kt.tierNotchActive:""}`}),n.jsx("span",{children:h.label})]},`tier-${h.value}`)})})]})},AS="_container_1whmk_1",ES="_label_1whmk_7",$S="_checkbox_1whmk_18",LS="_hint_1whmk_54",Zr={container:AS,label:ES,checkbox:$S,hint:LS},ia=({id:e="cfg-show-values",checked:t,onChange:s,label:r="Show values on bars",hint:a,className:o=""})=>n.jsxs("div",{className:`${Zr.container} ${o}`.trim(),children:[n.jsxs("label",{htmlFor:e,className:Zr.label,children:[n.jsx("input",{id:e,type:"checkbox",className:Zr.checkbox,checked:t,onChange:i=>s(i.target.checked)}),n.jsx("span",{children:r})]}),a&&n.jsx("span",{className:Zr.hint,children:a})]});function co(e){var t,s,r,a,o,i,l,c,d,f,m,h,p,x,v,b,y,g,S,C,T,N,_,k,w,$,I,j,D,H,L,U,G,z,q,P,F,R,W,se,re,le,M,K,Q,X,ee,V,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:((s=e==null?void 0:e.visualConfig)==null?void 0:s.barVariant)||"standard",targetValue:(r=e==null?void 0:e.visualConfig)==null?void 0:r.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)||((f=(d=e==null?void 0:e.visualConfig)==null?void 0:d.sortBy)!=null&&f.startsWith("category")?"category":"sheet_order"),sortDirection:((m=e==null?void 0:e.visualConfig)==null?void 0:m.sortDirection)||((p=(h=e==null?void 0:e.visualConfig)==null?void 0:h.sortBy)!=null&&p.includes("desc")?"desc":"asc"),orientation:((x=e==null?void 0:e.visualConfig)==null?void 0:x.orientation)||((v=e==null?void 0:e.visualConfig)==null?void 0:v.barOrientation)||"vertical",barOrientation:((b=e==null?void 0:e.visualConfig)==null?void 0:b.barOrientation)||((y=e==null?void 0:e.visualConfig)==null?void 0:y.orientation)||"vertical",stacked:((g=e==null?void 0:e.visualConfig)==null?void 0:g.stacked)||!1,showValues:((S=e==null?void 0:e.visualConfig)==null?void 0:S.showValues)||!1,lastModifiedTime:(C=e==null?void 0:e.visualConfig)==null?void 0:C.lastModifiedTime,excludeSummaryRows:((T=e==null?void 0:e.visualConfig)==null?void 0:T.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:((k=e==null?void 0:e.visualConfig)==null?void 0:k.showAreaFill)||!1,markerSize:((w=e==null?void 0:e.visualConfig)==null?void 0:w.markerSize)||"regular",autoScaleY:(($=e==null?void 0:e.visualConfig)==null?void 0:$.autoScaleY)||!1,startAtZero:((I=e==null?void 0:e.visualConfig)==null?void 0:I.startAtZero)??!((j=e==null?void 0:e.visualConfig)!=null&&j.autoScaleY),scatterXColIndex:(D=e==null?void 0:e.visualConfig)==null?void 0:D.scatterXColIndex,scatterYColIndex:(H=e==null?void 0:e.visualConfig)==null?void 0:H.scatterYColIndex,scatterLabelColIndex:(L=e==null?void 0:e.visualConfig)==null?void 0:L.scatterLabelColIndex,scatterGroupColIndex:(U=e==null?void 0:e.visualConfig)==null?void 0:U.scatterGroupColIndex,autoScaleX:((G=e==null?void 0:e.visualConfig)==null?void 0:G.autoScaleX)||!1,startAtZeroX:((z=e==null?void 0:e.visualConfig)==null?void 0:z.startAtZeroX)??!((q=e==null?void 0:e.visualConfig)!=null&&q.autoScaleX),loessBandwidth:((P=e==null?void 0:e.visualConfig)==null?void 0:P.loessBandwidth)??.5,showCorrelationChip:((F=e==null?void 0:e.visualConfig)==null?void 0:F.showCorrelationChip)||!1,donutVariant:((R=e==null?void 0:e.visualConfig)==null?void 0:R.donutVariant)||"donut",groupOthers:((W=e==null?void 0:e.visualConfig)==null?void 0:W.groupOthers)??!0,binStrategy:((se=e==null?void 0:e.visualConfig)==null?void 0:se.binStrategy)||"auto",customBinMode:((re=e==null?void 0:e.visualConfig)==null?void 0:re.bucketSize)!==void 0?"step":"count",binCount:((le=e==null?void 0:e.visualConfig)==null?void 0:le.binCount)||8,bucketSize:((M=e==null?void 0:e.visualConfig)==null?void 0:M.bucketSize)||5,histogramYMode:((K=e==null?void 0:e.visualConfig)==null?void 0:K.histogramYMode)||"frequency",showSummaryStats:((Q=e==null?void 0:e.visualConfig)==null?void 0:Q.showSummaryStats)||!1,showMedianMode:((X=e==null?void 0:e.visualConfig)==null?void 0:X.showMedianMode)||!1,showReferenceGuide:((ee=e==null?void 0:e.visualConfig)==null?void 0:ee.showReferenceGuide)||!1,xLabel:(((V=e==null?void 0:e.visualConfig)==null?void 0:V.xLabel)||"").trim(),yLabel:(((J=e==null?void 0:e.visualConfig)==null?void 0:J.yLabel)||"").trim()}}function MS(e){const[t,s]=u.useState(()=>(e==null?void 0:e.sheetUrl)||""),[r,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,f]=u.useState(()=>(e==null?void 0:e.defaultType)||"bar"),[m,h]=u.useState(()=>{var A;return(e==null?void 0:e.unitOverride)||((A=e==null?void 0:e.visualConfig)==null?void 0:A.unit)||""}),[p,x]=u.useState(()=>(e==null?void 0:e.titleOverride)||""),[v,b]=u.useState(()=>(e==null?void 0:e.subtitleOverride)||""),[y,g]=u.useState(()=>{var A;return((A=e==null?void 0:e.visualConfig)==null?void 0:A.xLabel)||""}),[S,C]=u.useState(()=>{var A;return((A=e==null?void 0:e.visualConfig)==null?void 0:A.yLabel)||""}),[T,N]=u.useState(()=>{var A;return((A=e==null?void 0:e.visualConfig)==null?void 0:A.excludeSummaryRows)??!0}),[_,k]=u.useState(()=>{var A;return((A=e==null?void 0:e.visualConfig)==null?void 0:A.transpose)??!1}),[w,$]=u.useState(()=>{var A;return((A=e==null?void 0:e.visualConfig)==null?void 0:A.barVariant)||"standard"}),[I,j]=u.useState(()=>{var A;return(A=e==null?void 0:e.visualConfig)==null?void 0:A.targetValue}),[D,H]=u.useState(()=>{var A;return((A=e==null?void 0:e.visualConfig)==null?void 0:A.targetLabel)||"Target"}),[L,U]=u.useState(()=>{var A;return((A=e==null?void 0:e.visualConfig)==null?void 0:A.categoryColIndex)??0}),[G,z]=u.useState(()=>{var A;return(A=e==null?void 0:e.visualConfig)==null?void 0:A.includedSeriesIndices}),[q,P]=u.useState(()=>{var A;return((A=e==null?void 0:e.visualConfig)==null?void 0:A.sortBy)||"none"}),[F,R]=u.useState(()=>{var A,Fe,xt;return((A=e==null?void 0:e.visualConfig)==null?void 0:A.sortField)||((xt=(Fe=e==null?void 0:e.visualConfig)==null?void 0:Fe.sortBy)!=null&&xt.startsWith("category")?"category":"sheet_order")}),[W,se]=u.useState(()=>{var A,Fe,xt;return((A=e==null?void 0:e.visualConfig)==null?void 0:A.sortDirection)||((xt=(Fe=e==null?void 0:e.visualConfig)==null?void 0:Fe.sortBy)!=null&&xt.includes("desc")?"desc":"asc")}),[re,le]=u.useState(()=>{var A,Fe;return((A=e==null?void 0:e.visualConfig)==null?void 0:A.orientation)||((Fe=e==null?void 0:e.visualConfig)==null?void 0:Fe.barOrientation)||"vertical"}),[M,K]=u.useState(()=>{var A;return((A=e==null?void 0:e.visualConfig)==null?void 0:A.stacked)||!1}),[Q,X]=u.useState(()=>{var A;return((A=e==null?void 0:e.visualConfig)==null?void 0:A.showValues)||!1}),[ee,V]=u.useState(()=>{var A;return(A=e==null?void 0:e.visualConfig)==null?void 0:A.lastModifiedTime}),[J,Y]=u.useState(()=>{var A;return((A=e==null?void 0:e.visualConfig)==null?void 0:A.curveInterpolation)||((e==null?void 0:e.defaultType)==="scatter"?"none":"smooth")}),[te,oe]=u.useState(()=>{var A;return((A=e==null?void 0:e.visualConfig)==null?void 0:A.showAreaFill)||!1}),[B,E]=u.useState(()=>{var A;return((A=e==null?void 0:e.visualConfig)==null?void 0:A.markerSize)||"regular"}),[O,ie]=u.useState(()=>{var A;return((A=e==null?void 0:e.visualConfig)==null?void 0:A.autoScaleY)||!1}),[ce,de]=u.useState(()=>{var A,Fe;return((A=e==null?void 0:e.visualConfig)==null?void 0:A.startAtZero)!==void 0?e.visualConfig.startAtZero:((Fe=e==null?void 0:e.visualConfig)==null?void 0:Fe.autoScaleY)!==void 0?!e.visualConfig.autoScaleY:!0}),[ae,fe]=u.useState(()=>{var A;return(A=e==null?void 0:e.visualConfig)==null?void 0:A.scatterXColIndex}),[be,ve]=u.useState(()=>{var A;return(A=e==null?void 0:e.visualConfig)==null?void 0:A.scatterYColIndex}),[Pe,Ce]=u.useState(()=>{var A;return(A=e==null?void 0:e.visualConfig)==null?void 0:A.scatterLabelColIndex}),[Me,ot]=u.useState(()=>{var A;return(A=e==null?void 0:e.visualConfig)==null?void 0:A.scatterGroupColIndex}),[tn,Dr]=u.useState(()=>{var A;return((A=e==null?void 0:e.visualConfig)==null?void 0:A.autoScaleX)||!1}),[vn,Rr]=u.useState(()=>{var A,Fe;return((A=e==null?void 0:e.visualConfig)==null?void 0:A.startAtZeroX)!==void 0?e.visualConfig.startAtZeroX:((Fe=e==null?void 0:e.visualConfig)==null?void 0:Fe.autoScaleX)!==void 0?!e.visualConfig.autoScaleX:!0}),[nn,Gs]=u.useState(()=>{var A;return((A=e==null?void 0:e.visualConfig)==null?void 0:A.loessBandwidth)??.5}),[Ft,zn]=u.useState(()=>{var A;return((A=e==null?void 0:e.visualConfig)==null?void 0:A.showCorrelationChip)||!1}),[xn,Br]=u.useState(()=>{var A;return((A=e==null?void 0:e.visualConfig)==null?void 0:A.donutVariant)||"donut"}),[bn,Pr]=u.useState(()=>{var A;return((A=e==null?void 0:e.visualConfig)==null?void 0:A.groupOthers)??!0}),[yn,Or]=u.useState(()=>{var A;return((A=e==null?void 0:e.visualConfig)==null?void 0:A.binStrategy)||"auto"}),[sn,qn]=u.useState(()=>{var A;return((A=e==null?void 0:e.visualConfig)==null?void 0:A.bucketSize)!==void 0?"step":"count"}),[_n,tl]=u.useState(()=>{var A;return((A=e==null?void 0:e.visualConfig)==null?void 0:A.binCount)||8}),[wn,nl]=u.useState(()=>{var A;return((A=e==null?void 0:e.visualConfig)==null?void 0:A.bucketSize)||5}),[Hs,sl]=u.useState(()=>{var A;return((A=e==null?void 0:e.visualConfig)==null?void 0:A.histogramYMode)||"frequency"}),[zs,rl]=u.useState(()=>{var A;return((A=e==null?void 0:e.visualConfig)==null?void 0:A.showSummaryStats)||!1}),[qs,al]=u.useState(()=>{var A;return((A=e==null?void 0:e.visualConfig)==null?void 0:A.showMedianMode)||!1}),[Vs,ol]=u.useState(()=>{var A;return((A=e==null?void 0:e.visualConfig)==null?void 0:A.showReferenceGuide)||!1}),[pe,Va]=u.useState(()=>co(e)),eh=u.useCallback(A=>{var xt,Vn,Wn,Fr,Ur,Gr,Hr,zr,il,ll,cl,dl,ul,hl,ml,fl,pl,gl,vl,xl,bl,yl,_l,wl,Sl,Cl,kl,Nl,jl,Tl,Il,Al,El,$l,Ll,Ml,Dl,Rl,Bl,Pl,Ol,Fl,Ul,Gl,Hl,zl,ql;const Fe=co(A);Va(Fe),s((A==null?void 0:A.sheetUrl)||""),a((A==null?void 0:A.tabName)||""),i((A==null?void 0:A.sheetGid)||""),c((A==null?void 0:A.range)||""),f((A==null?void 0:A.defaultType)||"bar"),h((A==null?void 0:A.unitOverride)||((xt=A==null?void 0:A.visualConfig)==null?void 0:xt.unit)||""),x((A==null?void 0:A.titleOverride)||""),b((A==null?void 0:A.subtitleOverride)||""),g(((Vn=A==null?void 0:A.visualConfig)==null?void 0:Vn.xLabel)||""),C(((Wn=A==null?void 0:A.visualConfig)==null?void 0:Wn.yLabel)||""),$(((Fr=A==null?void 0:A.visualConfig)==null?void 0:Fr.barVariant)||"standard"),j((Ur=A==null?void 0:A.visualConfig)==null?void 0:Ur.targetValue),H(((Gr=A==null?void 0:A.visualConfig)==null?void 0:Gr.targetLabel)||"Target"),U(((Hr=A==null?void 0:A.visualConfig)==null?void 0:Hr.categoryColIndex)??0),z((zr=A==null?void 0:A.visualConfig)==null?void 0:zr.includedSeriesIndices),P(((il=A==null?void 0:A.visualConfig)==null?void 0:il.sortBy)||"none"),R(((ll=A==null?void 0:A.visualConfig)==null?void 0:ll.sortField)||((dl=(cl=A==null?void 0:A.visualConfig)==null?void 0:cl.sortBy)!=null&&dl.startsWith("category")?"category":"sheet_order")),se(((ul=A==null?void 0:A.visualConfig)==null?void 0:ul.sortDirection)||((ml=(hl=A==null?void 0:A.visualConfig)==null?void 0:hl.sortBy)!=null&&ml.includes("desc")?"desc":"asc")),le(((fl=A==null?void 0:A.visualConfig)==null?void 0:fl.orientation)||((pl=A==null?void 0:A.visualConfig)==null?void 0:pl.barOrientation)||"vertical"),K(((gl=A==null?void 0:A.visualConfig)==null?void 0:gl.stacked)||!1),X(((vl=A==null?void 0:A.visualConfig)==null?void 0:vl.showValues)||!1),Y(((xl=A==null?void 0:A.visualConfig)==null?void 0:xl.curveInterpolation)||((A==null?void 0:A.defaultType)==="scatter"?"none":"smooth")),oe(((bl=A==null?void 0:A.visualConfig)==null?void 0:bl.showAreaFill)||!1),E(((yl=A==null?void 0:A.visualConfig)==null?void 0:yl.markerSize)||"regular"),ie(((_l=A==null?void 0:A.visualConfig)==null?void 0:_l.autoScaleY)||!1),de(((wl=A==null?void 0:A.visualConfig)==null?void 0:wl.startAtZero)??!((Sl=A==null?void 0:A.visualConfig)!=null&&Sl.autoScaleY)),fe((Cl=A==null?void 0:A.visualConfig)==null?void 0:Cl.scatterXColIndex),ve((kl=A==null?void 0:A.visualConfig)==null?void 0:kl.scatterYColIndex),Ce((Nl=A==null?void 0:A.visualConfig)==null?void 0:Nl.scatterLabelColIndex),ot((jl=A==null?void 0:A.visualConfig)==null?void 0:jl.scatterGroupColIndex),Dr(((Tl=A==null?void 0:A.visualConfig)==null?void 0:Tl.autoScaleX)||!1),Rr(((Il=A==null?void 0:A.visualConfig)==null?void 0:Il.startAtZeroX)??!((Al=A==null?void 0:A.visualConfig)!=null&&Al.autoScaleX)),Gs(((El=A==null?void 0:A.visualConfig)==null?void 0:El.loessBandwidth)??.5),zn((($l=A==null?void 0:A.visualConfig)==null?void 0:$l.showCorrelationChip)||!1),Br(((Ll=A==null?void 0:A.visualConfig)==null?void 0:Ll.donutVariant)||"donut"),Pr(((Ml=A==null?void 0:A.visualConfig)==null?void 0:Ml.groupOthers)??!0),Or(((Dl=A==null?void 0:A.visualConfig)==null?void 0:Dl.binStrategy)||"auto"),qn(((Rl=A==null?void 0:A.visualConfig)==null?void 0:Rl.bucketSize)!==void 0?"step":"count"),tl(((Bl=A==null?void 0:A.visualConfig)==null?void 0:Bl.binCount)||8),nl(((Pl=A==null?void 0:A.visualConfig)==null?void 0:Pl.bucketSize)||5),sl(((Ol=A==null?void 0:A.visualConfig)==null?void 0:Ol.histogramYMode)||"frequency"),rl(((Fl=A==null?void 0:A.visualConfig)==null?void 0:Fl.showSummaryStats)||!1),al(((Ul=A==null?void 0:A.visualConfig)==null?void 0:Ul.showMedianMode)||!1),ol(((Gl=A==null?void 0:A.visualConfig)==null?void 0:Gl.showReferenceGuide)||!1),V((Hl=A==null?void 0:A.visualConfig)==null?void 0:Hl.lastModifiedTime),N(((zl=A==null?void 0:A.visualConfig)==null?void 0:zl.excludeSummaryRows)??!0),k(((ql=A==null?void 0:A.visualConfig)==null?void 0:ql.transpose)??!1)},[]),th=u.useCallback(A=>{Va(co(A))},[]),nh=u.useMemo(()=>{const A=t.trim(),Fe=r.trim(),xt=o.trim(),Vn=l.trim(),Wn=m.trim(),Fr=p.trim(),Ur=v.trim(),Gr=y.trim(),Hr=S.trim(),zr=D.trim();return!pe.sheetUrl&&!A?!1:A!==pe.sheetUrl||Fe!==pe.tabName||xt!==pe.sheetGid||Vn!==pe.range||d!==pe.chartType||Wn!==pe.unit||Fr!==pe.titleOverride||Ur!==pe.subtitleOverride||Gr!==pe.xLabel||Hr!==pe.yLabel||w!==pe.barVariant||I!==pe.targetValue||zr!==pe.targetLabel||L!==pe.categoryColIndex||JSON.stringify(G)!==JSON.stringify(pe.includedSeriesIndices)||q!==pe.sortBy||F!==pe.sortField||W!==pe.sortDirection||re!==pe.barOrientation||M!==pe.stacked||Q!==pe.showValues||J!==pe.curveInterpolation||te!==pe.showAreaFill||B!==pe.markerSize||O!==pe.autoScaleY||ce!==pe.startAtZero||ae!==pe.scatterXColIndex||be!==pe.scatterYColIndex||Pe!==pe.scatterLabelColIndex||Me!==pe.scatterGroupColIndex||tn!==pe.autoScaleX||vn!==pe.startAtZeroX||nn!==pe.loessBandwidth||Ft!==pe.showCorrelationChip||xn!==pe.donutVariant||bn!==pe.groupOthers||yn!==pe.binStrategy||sn!==pe.customBinMode||_n!==pe.binCount||wn!==pe.bucketSize||Hs!==pe.histogramYMode||zs!==pe.showSummaryStats||qs!==pe.showMedianMode||Vs!==pe.showReferenceGuide||ee!==pe.lastModifiedTime||T!==pe.excludeSummaryRows||_!==pe.transpose},[t,r,o,l,d,m,p,v,y,S,w,I,D,L,G,q,F,W,re,M,Q,J,te,B,O,ce,ae,be,Pe,Me,tn,vn,nn,Ft,xn,bn,yn,sn,_n,wn,Hs,zs,qs,Vs,ee,T,_,pe]),sh=u.useCallback((A,Fe,xt,Vn,Wn)=>({chartId:A,nodeId:Fe,sheetUrl:t.trim(),tabName:r.trim()||void 0,sheetGid:o.trim()||void 0,range:l.trim(),defaultType:d,titleOverride:p.trim()||void 0,subtitleOverride:v.trim()||void 0,unitOverride:m.trim()||void 0,visualConfig:{unit:m.trim()||void 0,xLabel:y.trim()||void 0,yLabel:S.trim()||void 0,range:l.trim(),tabName:r.trim()||void 0,sheetGid:o.trim()||void 0,excludeSummaryRows:T,transpose:_,barVariant:d==="bar"?w:void 0,targetValue:d==="bar"&&w==="progress"?I:void 0,targetLabel:d==="bar"&&w==="progress"?D:void 0,categoryColIndex:L,includedSeriesIndices:G,sortBy:d==="donut"?void 0:q,sortField:d==="donut"?void 0:F,sortDirection:d==="donut"?void 0:W,orientation:d==="bar"?re:void 0,barOrientation:d==="bar"?re:void 0,stacked:d==="bar"?M:void 0,showValues:d==="bar"||d==="line"||d==="donut"?Q:void 0,curveInterpolation:d==="line"||d==="histogram"||d==="scatter"?J:void 0,showAreaFill:d==="line"||d==="scatter"?te:void 0,markerSize:d==="line"||d==="scatter"?B:void 0,autoScaleY:d==="line"||d==="bar"||d==="scatter"?O:void 0,startAtZero:d==="line"||d==="scatter"?ce:void 0,startAtZeroX:d==="scatter"?vn:void 0,loessBandwidth:d==="scatter"?nn:void 0,scatterXColIndex:d==="scatter"?xt??ae:void 0,scatterYColIndex:d==="scatter"?Vn??be:void 0,scatterLabelColIndex:d==="scatter"?Wn??Pe:void 0,scatterGroupColIndex:d==="scatter"?Me:void 0,autoScaleX:d==="scatter"?tn:void 0,showCorrelationChip:d==="scatter"?Ft:void 0,donutVariant:d==="donut"?xn:void 0,groupOthers:d==="donut"?bn:void 0,binStrategy:d==="histogram"?yn:void 0,binCount:d==="histogram"&&sn==="count"?typeof _n=="number"&&_n>=2?Math.min(50,_n):8:void 0,bucketSize:d==="histogram"&&sn==="step"?typeof wn=="number"&&wn>=1?wn:5:void 0,histogramYMode:d==="histogram"?Hs:void 0,showSummaryStats:d==="histogram"?zs:void 0,showMedianMode:d==="histogram"?qs:void 0,showReferenceGuide:d==="histogram"||d==="scatter"?Vs:void 0,lastModifiedTime:ee},updatedAt:new Date().toISOString(),updatedBy:"coordinator"}),[t,r,o,l,d,p,v,y,S,m,T,_,w,I,D,L,G,q,F,W,re,M,Q,J,te,B,O,ce,vn,nn,ae,be,Pe,Me,tn,Ft,xn,bn,yn,sn,_n,wn,Hs,zs,qs,Vs,ee]);return{sheetUrl:t,setSheetUrl:s,tabName:r,setTabName:a,sheetGid:o,setSheetGid:i,range:l,setRange:c,chartType:d,setChartType:f,unit:m,setUnit:h,titleOverride:p,setTitleOverride:x,subtitleOverride:v,setSubtitleOverride:b,xLabel:y,setXLabel:g,yLabel:S,setYLabel:C,excludeSummaryRows:T,setExcludeSummaryRows:N,transpose:_,setTranspose:k,barVariant:w,setBarVariant:$,targetValue:I,setTargetValue:j,targetLabel:D,setTargetLabel:H,categoryColIndex:L,setCategoryColIndex:U,includedSeriesIndices:G,setIncludedSeriesIndices:z,sortBy:q,setSortBy:P,sortField:F,setSortField:R,sortDirection:W,setSortDirection:se,barOrientation:re,setBarOrientation:le,stacked:M,setStacked:K,showValues:Q,setShowValues:X,lastModifiedTime:ee,setLastModifiedTime:V,curveInterpolation:J,setCurveInterpolation:Y,showAreaFill:te,setShowAreaFill:oe,markerSize:B,setMarkerSize:E,autoScaleY:O,setAutoScaleY:ie,startAtZero:ce,setStartAtZero:de,scatterXColIndex:ae,setScatterXColIndex:fe,scatterYColIndex:be,setScatterYColIndex:ve,scatterLabelColIndex:Pe,setScatterLabelColIndex:Ce,scatterGroupColIndex:Me,setScatterGroupColIndex:ot,autoScaleX:tn,setAutoScaleX:Dr,startAtZeroX:vn,setStartAtZeroX:Rr,loessBandwidth:nn,setLoessBandwidth:Gs,showCorrelationChip:Ft,setShowCorrelationChip:zn,donutVariant:xn,setDonutVariant:Br,groupOthers:bn,setGroupOthers:Pr,binStrategy:yn,setBinStrategy:Or,customBinMode:sn,setCustomBinMode:qn,binCount:_n,setBinCount:tl,bucketSize:wn,setBucketSize:nl,histogramYMode:Hs,setHistogramYMode:sl,showSummaryStats:zs,setShowSummaryStats:rl,showMedianMode:qs,setShowMedianMode:al,showReferenceGuide:Vs,setShowReferenceGuide:ol,savedSnapshot:pe,setSavedSnapshot:Va,hasUnsavedChanges:nh,resetForm:eh,markAsSaved:th,buildConfigPayload:sh}}function DS({sheetUrl:e,tabName:t,sheetGid:s,initialConfig:r,setTabName:a,setSheetGid:o,setLastModifiedTime:i,onAutoSelectTab:l}){var T;const[c,d]=u.useState(()=>r!=null&&r.sheetUrl?"public":"idle"),[f,m]=u.useState(()=>r!=null&&r.sheetUrl?"Public Access Verified":""),[h,p]=u.useState(()=>r!=null&&r.tabName?[{title:r.tabName,sheetId:Number(r.sheetGid)||0,index:0}]:[]),x=u.useRef(t);x.current=t;const v=u.useRef(s);v.current=s;const b=u.useRef(((T=r==null?void 0:r.sheetUrl)==null?void 0:T.trim())||null),y=u.useCallback(async N=>{const _=N.trim();if(!_){b.current=null,d("idle"),m(""),p([]);return}if(!Xt(_)){b.current=_,d("invalid"),m("Invalid Google Sheet link"),p([]);return}d("checking"),m("Verifying link access…");try{const[w,$]=await Promise.all([Lx(_),bu(_)]);b.current=_,w.accessible?(d("public"),m("Public Access Verified"),w.sheetGid&&!v.current&&o(w.sheetGid),w.modifiedTime&&i(w.modifiedTime)):(d("restricted"),m("Link Sharing Restricted"));const I=($&&$.length>0?$:w.tabs)||[];if(I.length>0){p(I);const j=x.current?I.find(D=>D.title===x.current):null;if(j)a(j.title),o(String(j.sheetId));else{const D=w.sheetGid||v.current,H=D?I.find(L=>String(L.sheetId)===D):null;if(H)a(H.title),o(String(H.sheetId)),l==null||l(H.title,String(H.sheetId));else{const L=I[0];a(L.title),o(String(L.sheetId)),l==null||l(L.title,String(L.sheetId))}}}else x.current||a("Sheet1")}catch{b.current=_,d("restricted"),m("Link Sharing Restricted")}},[a,o,i,l]);u.useEffect(()=>{const N=e.trim();if(!N){d("idle"),m(""),p([]),b.current=null;return}if(!Xt(N)){d("invalid"),m("Invalid Google Sheet link"),p([]);return}b.current&&b.current!==N&&(d("idle"),m(""),p([]))},[e]);const g=u.useCallback(N=>{const _=N.target.value;a(_);const k=h.find(w=>w.title===_);k&&o(String(k.sheetId))},[h,a,o]),S=u.useMemo(()=>{var k;return!Xt(e)?!1:!!(r!=null&&r.sheetUrl)&&e.trim()===((k=r==null?void 0:r.sheetUrl)==null?void 0:k.trim())?!0:c==="public"},[e,c,r]),C=u.useCallback((N,_,k)=>{d(N?"public":"idle"),m(N?"Public Access Verified":""),b.current=(N==null?void 0:N.trim())||null,p(_?[{title:_,sheetId:Number(k)||0,index:0}]:[])},[]);return{accessStatus:c,setAccessStatus:d,statusMessage:f,setStatusMessage:m,discoveredTabs:h,setDiscoveredTabs:p,isStep1Valid:S,executeVerification:y,handleTabChange:g,resetVerification:C}}function RS({sheetUrl:e,tabName:t,sheetGid:s,range:r,previewMatrix:a}){const[o,i]=u.useState([]),[l,c]=u.useState(!1),d=u.useCallback(async(b=e,y=t,g=s)=>{const S=b.trim();if(!S||!Xt(S)){i([]);return}c(!0);try{const C=await $i({sheetUrl:S,tabName:y?y.trim():void 0,sheetGid:g?g.trim():void 0,timeoutMs:8e3});i(C||[])}catch{i([])}finally{c(!1)}},[e,t,s]),f=u.useMemo(()=>o,[o]),m=u.useMemo(()=>gv(f),[f]),h=u.useMemo(()=>{if(o&&o.length>0){const b=Ar(r);if(!b)return o;const y=Math.max(0,b.startRow),g=typeof b.endRow=="number"?Math.min(o.length-1,b.endRow):o.length-1,S=Math.max(0,b.startCol),C=Math.max(S,b.endCol),T=[];for(let N=y;N<=g&&N<o.length;N++){const _=o[N]||[],k=[];for(let w=S;w<=C;w++)k.push(_[w]!==void 0?_[w]:null);T.push(k)}return T}return a&&a.length>0?a:[]},[o,a,r]),p=h.length>0?h:a||[],x=p[0]||[],v=u.useMemo(()=>x.map((b,y)=>({index:y,label:b!=null&&String(b).trim()!==""?String(b).trim():`Col ${y+1}`})),[x]);return{fetchedMatrix:o,fullMatrix:f,isSyncing:l,liveMatrix:h,activeMatrix:p,detectedColumns:v,detectedRange:m,executeSync:d}}const BS="_stepPanel_12c72_1",PS="_sectionGroup_12c72_20",OS="_formGroup_12c72_42",FS="_label_12c72_48",US="_labelTitle_12c72_58",GS="_verifiedCheck_12c72_64",HS="_labelRow_12c72_81",zS="_goToSourceBtn_12c72_88",qS="_input_12c72_122",VS="_inputSuccess_12c72_143",WS="_inputError_12c72_147",KS="_select_12c72_151",YS="_fieldWithActionRow_12c72_177",XS="_inlineActionBtn_12c72_191",JS="_rangeRow_12c72_288",ZS="_rangeDisplayWrapper_12c72_295",QS="_rangeBadge_12c72_300",eC="_rangeBadgeEmpty_12c72_314",tC="_selectRangeBtn_12c72_332",nC="_errorText_12c72_336",sC="_guidanceCard_12c72_344",rC="_guidanceHeader_12c72_354",aC="_guidanceTitleWrapper_12c72_360",oC="_guidanceIcon_12c72_366",iC="_guidanceTitle_12c72_360",lC="_guidanceText_12c72_377",cC="_guidanceSteps_12c72_385",dC="_guidanceStepItem_12c72_391",uC="_stepNum_12c72_400",hC="_guidanceActions_12c72_415",ye={stepPanel:BS,sectionGroup:PS,formGroup:OS,label:FS,labelTitle:US,verifiedCheck:GS,labelRow:HS,goToSourceBtn:zS,input:qS,inputSuccess:VS,inputError:WS,select:KS,fieldWithActionRow:YS,inlineActionBtn:XS,rangeRow:JS,rangeDisplayWrapper:ZS,rangeBadge:QS,rangeBadgeEmpty:eC,selectRangeBtn:tC,errorText:nC,guidanceCard:sC,guidanceHeader:rC,guidanceTitleWrapper:aC,guidanceIcon:oC,guidanceTitle:iC,guidanceText:lC,guidanceSteps:cC,guidanceStepItem:dC,stepNum:uC,guidanceActions:hC},mC=({sheetUrl:e,setSheetUrl:t,accessStatus:s,statusMessage:r,discoveredTabs:a,tabName:o,sheetGid:i,setTabName:l,executeVerification:c,handleTabChange:d,onResync:f,isSyncing:m=!1,range:h,isRangeValid:p,isSelectingRange:x,setIsSelectingRange:v,executeSync:b})=>{var S;const y=!!Xt(e.trim()),g=u.useMemo(()=>{if(a.length>0){const C=a.some(T=>T.title===o);return o&&!C?[{title:o,sheetId:"current"},...a]:a}return[{title:o||"Sheet1",sheetId:"default"}]},[a,o]);return n.jsxs("div",{className:ye.stepPanel,children:[n.jsx("div",{className:ye.sectionGroup,children:n.jsxs("div",{className:ye.formGroup,children:[n.jsxs("div",{className:ye.labelRow,children:[n.jsx("label",{className:ye.label,htmlFor:"cfg-sheet-url",children:n.jsxs("span",{className:ye.labelTitle,children:[n.jsx("span",{children:"1. Paste your Google Sheets Link"}),s==="public"&&n.jsx("span",{className:ye.verifiedCheck,"aria-label":"Verified",title:"Verified",children:"✓"})]})}),e&&n.jsx("a",{href:e,target:"_blank",rel:"noopener noreferrer",className:ye.goToSourceBtn,title:"Open spreadsheet in new tab",children:n.jsx("span",{children:"Open ↗"})})]}),n.jsxs("div",{className:ye.fieldWithActionRow,children:[n.jsx("input",{id:"cfg-sheet-url",type:"url",className:`${ye.input} ${s==="invalid"?ye.inputError:""} ${s==="public"?ye.inputSuccess:""}`,placeholder:"https://docs.google.com/spreadsheets/d/.../edit",value:e,onChange:C=>t(C.target.value),autoComplete:"off"}),n.jsx(he,{type:"button",variant:"primary",size:"sm",onClick:()=>c(e.trim()),disabled:!y||s==="checking",className:ye.inlineActionBtn,"aria-label":"Verify",children:"Verify"})]}),s==="restricted"&&n.jsxs("div",{className:ye.guidanceCard,role:"alert",children:[n.jsx("div",{className:ye.guidanceHeader,children:n.jsxs("div",{className:ye.guidanceTitleWrapper,children:[n.jsx("span",{className:ye.guidanceIcon,"aria-hidden":"true",children:n.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("rect",{x:"3",y:"11",width:"18",height:"11",rx:"2",ry:"2"}),n.jsx("path",{d:"M7 11V7a5 5 0 0 1 10 0v4"})]})}),n.jsx("span",{className:ye.guidanceTitle,children:"Enable Link Sharing"})]})}),n.jsx("p",{className:ye.guidanceText,children:"Google Sheets must be set to public view for live indicator charts to render."}),n.jsxs("div",{className:ye.guidanceSteps,children:[n.jsxs("div",{className:ye.guidanceStepItem,children:[n.jsx("span",{className:ye.stepNum,children:"1"}),n.jsxs("span",{children:["Click ",n.jsx("strong",{children:"Share"})," in Google Sheet"]})]}),n.jsxs("div",{className:ye.guidanceStepItem,children:[n.jsx("span",{className:ye.stepNum,children:"2"}),n.jsxs("span",{children:["Change access to ",n.jsx("strong",{children:"Anyone with the link"})]})]}),n.jsxs("div",{className:ye.guidanceStepItem,children:[n.jsx("span",{className:ye.stepNum,children:"3"}),n.jsxs("span",{children:["Keep role set to ",n.jsx("strong",{children:"Viewer"})]})]})]}),n.jsxs("div",{className:ye.guidanceActions,children:[e&&n.jsx(he,{as:"a",href:e,target:"_blank",rel:"noopener noreferrer",variant:"secondary",size:"sm",children:"Open Sheet ↗"}),n.jsx(he,{type:"button",variant:"secondary",size:"sm",onClick:()=>c(e),children:"Re-verify Link"})]})]})]})}),(e.trim()||s==="public")&&n.jsx("div",{className:ye.sectionGroup,children:n.jsxs("div",{className:ye.formGroup,children:[n.jsx("div",{className:ye.labelRow,children:n.jsx("label",{className:ye.label,htmlFor:"cfg-tab-name",children:n.jsx("span",{children:"2. Select a Tab"})})}),n.jsxs("div",{className:ye.fieldWithActionRow,children:[n.jsx("select",{id:"cfg-tab-name",className:ye.select,value:o||(((S=g[0])==null?void 0:S.title)??"Sheet1"),onChange:d,disabled:g.length===0,"aria-label":"Select Sheet Tab",children:g.map(C=>n.jsx("option",{value:C.title,children:C.title},String(C.sheetId??C.title)))}),n.jsx(he,{type:"button",variant:"primary",size:"sm",onClick:()=>b(e,o,i),disabled:s!=="public"||!o||m,className:ye.inlineActionBtn,"aria-label":"Refresh",children:"Refresh"})]})]})}),n.jsx("div",{className:ye.sectionGroup,children:n.jsxs("div",{className:ye.formGroup,children:[n.jsx("div",{className:ye.labelRow,children:n.jsx("label",{className:ye.label,children:n.jsxs("span",{children:["3. Select Range",n.jsx(Pn,{text:"The box of cells to use for this chart, like A1:D10.",label:"Data Range"})]})})}),n.jsxs("div",{className:ye.rangeRow,children:[n.jsx("div",{className:ye.rangeDisplayWrapper,children:n.jsx("span",{className:h?ye.rangeBadge:ye.rangeBadgeEmpty,children:h||"—"})}),n.jsx(he,{type:"button",variant:"primary",size:"sm",onClick:()=>v(C=>!C),className:ye.selectRangeBtn,"aria-label":x?"Finish range selection":"Select range on sheet",children:x?"Done":"Select"})]}),!p&&h&&n.jsx("p",{className:ye.errorText,children:"Invalid range"})]})})]})},fC="_container_1reoz_7",pC="_table_1reoz_20",gC="_headerCell_1reoz_30",vC="_cornerCell_1reoz_46",xC="_rowNumberCell_1reoz_58",bC="_dataCell_1reoz_75",yC="_dataCellSelecting_1reoz_91",_C="_nullCell_1reoz_99",wC="_cellSelected_1reoz_105",SC="_cellBorderTop_1reoz_109",CC="_cellBorderBottom_1reoz_113",kC="_cellBorderLeft_1reoz_117",NC="_cellBorderRight_1reoz_121",jC="_cellActiveDrag_1reoz_126",TC="_cellActiveDragBorderTop_1reoz_130",IC="_cellActiveDragBorderBottom_1reoz_134",AC="_cellActiveDragBorderLeft_1reoz_138",EC="_cellActiveDragBorderRight_1reoz_142",$C="_selectionHintBar_1reoz_147",LC="_selectionHintChip_1reoz_157",MC="_emptySheet_1reoz_172",DC="_bufferColumnHeader_1reoz_184",RC="_bufferColumnCell_1reoz_196",BC="_bufferRow_1reoz_205",PC="_bufferRowHeader_1reoz_209",OC="_bufferRowCell_1reoz_221",Ae={container:fC,table:pC,headerCell:gC,cornerCell:vC,rowNumberCell:xC,dataCell:bC,dataCellSelecting:yC,nullCell:_C,cellSelected:wC,cellBorderTop:SC,cellBorderBottom:CC,cellBorderLeft:kC,cellBorderRight:NC,cellActiveDrag:jC,cellActiveDragBorderTop:TC,cellActiveDragBorderBottom:IC,cellActiveDragBorderLeft:AC,cellActiveDragBorderRight:EC,selectionHintBar:$C,selectionHintChip:LC,emptySheet:MC,bufferColumnHeader:DC,bufferColumnCell:RC,bufferRow:BC,bufferRowHeader:PC,bufferRowCell:OC},Gu=({matrix:e,range:t,isSelecting:s=!1,onRangeSelect:r,className:a})=>{const[o,i]=u.useState(null),[l,c]=u.useState(null),[d,f]=u.useState(null),m=u.useMemo(()=>!e||e.length===0?0:Math.max(...e.map(S=>S?S.length:0),1),[e]),h=u.useMemo(()=>t?Ar(t):null,[t]),p=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]),x=u.useCallback(()=>{if(o&&l){const S=Math.min(o.r,l.r),C=Math.max(o.r,l.r),T=Math.min(o.c,l.c),N=Math.max(o.c,l.c),_=`${ct(T)}${S+1}`,k=`${ct(N)}${C+1}`,w=`${_}:${k}`;r==null||r(w),i(null),c(null),f(null)}},[o,l,r]);u.useEffect(()=>{if(o)return window.addEventListener("mouseup",x),()=>window.removeEventListener("mouseup",x)},[o,x]);const v=(S,C,T)=>{if(T.button!==0)return;if(T.preventDefault(),d&&!o){const k=Math.min(d.r,S),w=Math.max(d.r,S),$=Math.min(d.c,C),I=Math.max(d.c,C),j=`${ct($)}${k+1}:${ct(I)}${w+1}`;r==null||r(j),f(null);return}i({r:S,c:C}),c({r:S,c:C}),f({r:S,c:C});const N=`${ct(C)}${S+1}`,_=`${N}:${N}`;r==null||r(_)},b=(S,C)=>{o&&c({r:S,c:C})};if(!e||e.length===0)return n.jsx("div",{className:`${Ae.emptySheet} ${a||""}`,children:n.jsx("span",{children:"No sheet data loaded. Link a Google Sheet in the drawer."})});const y=Array.from({length:m},(S,C)=>ct(C)),g=o!==null;return n.jsxs("div",{className:`${Ae.container} ${a||""}`,tabIndex:-1,children:[s&&n.jsx("div",{className:Ae.selectionHintBar,children:n.jsx("div",{className:Ae.selectionHintChip,children:n.jsx("span",{children:"🎯 Click and drag across the sheet to highlight your cell range"})})}),n.jsxs("table",{className:Ae.table,"aria-label":"Full Google Sheet Spreadsheet Grid",children:[n.jsx("thead",{children:n.jsxs("tr",{children:[n.jsx("th",{className:Ae.cornerCell,"aria-label":"Row / Column Index"}),y.map((S,C)=>n.jsx("th",{className:Ae.headerCell,scope:"col",children:S},C)),n.jsx("th",{className:Ae.bufferColumnHeader,"aria-hidden":"true"})]})}),n.jsxs("tbody",{children:[e.map((S,C)=>n.jsxs("tr",{children:[n.jsx("th",{className:Ae.rowNumberCell,scope:"row",children:C+1}),y.map((T,N)=>{const _=S?S[N]:void 0;let k=!1,w=!1,$=!1,I=!1,j=!1;if(!g&&h){const{startCol:q,startRow:P,endCol:F,endRow:R}=h,W=typeof R=="number"?R:e.length-1,se=Math.min(P,W),re=Math.max(P,W),le=Math.min(q,F),M=Math.max(q,F);C>=se&&C<=re&&N>=le&&N<=M&&(k=!0,w=C===se,$=C===re,I=N===le,j=N===M)}let D=!1,H=!1,L=!1,U=!1,G=!1;if(p){const{minR:q,maxR:P,minC:F,maxC:R}=p;C>=q&&C<=P&&N>=F&&N<=R&&(D=!0,H=C===q,L=C===P,U=N===F,G=N===R)}const z=[Ae.dataCell,s?Ae.dataCellSelecting:"",k&&!D?Ae.cellSelected:"",k&&w&&!D?Ae.cellBorderTop:"",k&&$&&!D?Ae.cellBorderBottom:"",k&&I&&!D?Ae.cellBorderLeft:"",k&&j&&!D?Ae.cellBorderRight:"",D?Ae.cellActiveDrag:"",H?Ae.cellActiveDragBorderTop:"",L?Ae.cellActiveDragBorderBottom:"",U?Ae.cellActiveDragBorderLeft:"",G?Ae.cellActiveDragBorderRight:""].filter(Boolean).join(" ");return n.jsx("td",{className:z,onMouseDown:q=>v(C,N,q),onMouseEnter:()=>b(C,N),title:`Cell ${ct(N)}${C+1}`,children:_==null||_===""?n.jsx("span",{className:Ae.nullCell,children:"—"}):String(_)},N)}),n.jsx("td",{className:Ae.bufferColumnCell,"aria-hidden":"true"})]},C)),n.jsxs("tr",{className:Ae.bufferRow,children:[n.jsx("th",{className:Ae.bufferRowHeader,"aria-hidden":"true"}),n.jsx("td",{colSpan:y.length+1,className:Ae.bufferRowCell,"aria-hidden":"true"})]})]})]})]})},FC="_formGroup_1iatw_217",UC="_label_1iatw_223",GC="_input_1iatw_297",HC="_select_1iatw_298",zC="_checkboxLabel_1iatw_528",qC="_checkbox_1iatw_528",VC="_twoColRow_1iatw_548",WC="_titlesSection_1iatw_564",KC="_sectionBlock_1iatw_565",YC="_sectionHeader_1iatw_572",XC="_sectionEyebrow_1iatw_579",JC="_spinner_1iatw_616",ZC="_seriesSwatch_1iatw_696",QC="_draggableRowLabel_1iatw_704",ek="_draggableRowText_1iatw_718",tk="_draggableColLetter_1iatw_727",nk="_saveButton_1iatw_943",sk="_companionChartViewport_1iatw_1178",ne={formGroup:FC,label:UC,input:GC,select:HC,checkboxLabel:zC,checkbox:qC,twoColRow:VC,titlesSection:WC,sectionBlock:KC,sectionHeader:YC,sectionEyebrow:XC,spinner:JC,seriesSwatch:ZC,draggableRowLabel:QC,draggableRowText:ek,draggableColLetter:tk,saveButton:nk,companionChartViewport:sk},rk=({barOrientation:e,setBarOrientation:t,stacked:s,setStacked:r})=>n.jsxs("div",{className:ne.twoColRow,children:[n.jsxs("div",{className:ne.formGroup,children:[n.jsx("label",{className:ne.label,htmlFor:"cfg-orientation",children:n.jsx("span",{children:"Orientation"})}),n.jsxs("select",{id:"cfg-orientation",className:ne.select,value:e,onChange:a=>t(a.target.value),children:[n.jsx("option",{value:"vertical",children:"Vertical Columns"}),n.jsx("option",{value:"horizontal",children:"Horizontal Bars"})]})]}),n.jsxs("div",{className:ne.formGroup,children:[n.jsx("label",{className:ne.label,htmlFor:"cfg-series-mode",children:n.jsx("span",{children:"Grouping Mode"})}),n.jsxs("select",{id:"cfg-series-mode",className:ne.select,value:s?"stacked":"clustered",onChange:a=>r(a.target.value==="stacked"),children:[n.jsx("option",{value:"clustered",children:"Clustered (Side by Side)"}),n.jsx("option",{value:"stacked",children:"Stacked"})]})]})]}),ak=({curveInterpolation:e,setCurveInterpolation:t,markerSize:s,setMarkerSize:r,showAreaFill:a,setShowAreaFill:o,startAtZero:i,setStartAtZero:l,setAutoScaleY:c})=>n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:ne.twoColRow,children:[n.jsxs("div",{className:ne.formGroup,children:[n.jsx("label",{className:ne.label,htmlFor:"cfg-line-style",children:n.jsx("span",{children:"Line Interpolation"})}),n.jsxs("select",{id:"cfg-line-style",className:ne.select,value:e,onChange:d=>t(d.target.value),children:[n.jsx("option",{value:"smooth",children:"Smooth Curve"}),n.jsx("option",{value:"straight",children:"Straight Lines"})]})]}),n.jsxs("div",{className:ne.formGroup,children:[n.jsx("label",{className:ne.label,htmlFor:"cfg-marker-size",children:n.jsx("span",{children:"Point Marker Size"})}),n.jsxs("select",{id:"cfg-marker-size",className:ne.select,value:s,onChange:d=>r(d.target.value),children:[n.jsx("option",{value:"compact",children:"Small"}),n.jsx("option",{value:"regular",children:"Medium"}),n.jsx("option",{value:"prominent",children:"Large"})]})]})]}),n.jsx("div",{className:ne.formGroup,children:n.jsxs("label",{htmlFor:"cfg-line-area-fill",className:ne.checkboxLabel,children:[n.jsx("input",{id:"cfg-line-area-fill",type:"checkbox",className:ne.checkbox,checked:a,onChange:d=>o(d.target.checked)}),n.jsx("span",{children:"Shade area under line"})]})}),n.jsx("div",{className:ne.formGroup,children:n.jsxs("label",{htmlFor:"cfg-line-start-at-zero",className:ne.checkboxLabel,children:[n.jsx("input",{id:"cfg-line-start-at-zero",type:"checkbox",className:ne.checkbox,checked:i,onChange:d=>{const f=d.target.checked;l(f),c(!f)}}),n.jsx("span",{children:"Start vertical axis at zero"})]})})]}),ok=({donutVariant:e,setDonutVariant:t})=>n.jsxs("div",{className:ne.formGroup,children:[n.jsx("label",{className:ne.label,htmlFor:"cfg-donut-variant",children:n.jsx("span",{children:"Display Variant"})}),n.jsxs("select",{id:"cfg-donut-variant",className:ne.select,value:e,onChange:s=>t(s.target.value),children:[n.jsx("option",{value:"donut",children:"Donut Ring"}),n.jsx("option",{value:"pie",children:"Solid Pie"})]})]}),ik=({curveInterpolation:e,setCurveInterpolation:t,showReferenceGuide:s,setShowReferenceGuide:r,showSummaryStats:a,setShowSummaryStats:o,showMedianMode:i,setShowMedianMode:l})=>n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:ne.twoColRow,children:[n.jsx("div",{className:ne.formGroup,children:n.jsxs("label",{htmlFor:"cfg-histogram-curve",className:ne.checkboxLabel,children:[n.jsx("input",{id:"cfg-histogram-curve",type:"checkbox",className:ne.checkbox,checked:e==="smooth",onChange:c=>t(c.target.checked?"smooth":"none")}),n.jsx("span",{children:"Overlay Smooth Distribution Curve"})]})}),n.jsx("div",{className:ne.formGroup,children:n.jsxs("label",{htmlFor:"cfg-show-reference-guide",className:ne.checkboxLabel,children:[n.jsx("input",{id:"cfg-show-reference-guide",type:"checkbox",className:ne.checkbox,checked:s,onChange:c=>r(c.target.checked)}),n.jsx("span",{children:"Show Mean (Average) Reference Line"})]})})]}),n.jsxs("div",{className:ne.twoColRow,children:[n.jsx("div",{className:ne.formGroup,children:n.jsxs("label",{htmlFor:"cfg-show-summary-stats",className:ne.checkboxLabel,children:[n.jsx("input",{id:"cfg-show-summary-stats",type:"checkbox",className:ne.checkbox,checked:a,onChange:c=>o(c.target.checked)}),n.jsx("span",{children:"Show Summary Statistics Card"})]})}),n.jsx("div",{className:ne.formGroup,children:n.jsxs("label",{htmlFor:"cfg-show-median-mode",className:ne.checkboxLabel,children:[n.jsx("input",{id:"cfg-show-median-mode",type:"checkbox",className:ne.checkbox,checked:i,onChange:c=>l(c.target.checked)}),n.jsx("span",{children:"Include Median & Mode"})]})})]})]}),lk=({curveInterpolation:e,setCurveInterpolation:t,markerSize:s,setMarkerSize:r,loessBandwidth:a,setLoessBandwidth:o,showAreaFill:i,setShowAreaFill:l,showCorrelationChip:c,setShowCorrelationChip:d,showReferenceGuide:f,setShowReferenceGuide:m,startAtZero:h,setStartAtZero:p,setAutoScaleY:x,startAtZeroX:v,setStartAtZeroX:b,setAutoScaleX:y})=>n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:ne.twoColRow,children:[n.jsxs("div",{className:ne.formGroup,children:[n.jsx("label",{className:ne.label,htmlFor:"cfg-scatter-trendline",children:n.jsx("span",{children:"Trendline (Regression)"})}),n.jsxs("select",{id:"cfg-scatter-trendline",className:ne.select,value:e,onChange:g=>t(g.target.value),children:[n.jsx("option",{value:"none",children:"None (Points Only)"}),n.jsx("option",{value:"linear",children:"Linear Trendline"}),n.jsx("option",{value:"smooth",children:"Smooth LOESS Curve"}),n.jsx("option",{value:"polynomial",children:"Polynomial Curve"})]})]}),n.jsxs("div",{className:ne.formGroup,children:[n.jsx("label",{className:ne.label,htmlFor:"cfg-scatter-marker-size",children:n.jsx("span",{children:"Point Marker Size"})}),n.jsxs("select",{id:"cfg-scatter-marker-size",className:ne.select,value:s,onChange:g=>r(g.target.value),children:[n.jsx("option",{value:"compact",children:"Small"}),n.jsx("option",{value:"regular",children:"Medium"}),n.jsx("option",{value:"prominent",children:"Large"})]})]})]}),e==="smooth"&&n.jsx("div",{children:n.jsx(Uu,{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:g=>o(g)})}),n.jsxs("div",{className:ne.twoColRow,children:[(e==="linear"||e==="smooth"||e==="polynomial")&&n.jsx("div",{className:ne.formGroup,children:n.jsxs("label",{htmlFor:"cfg-scatter-confidence",className:ne.checkboxLabel,children:[n.jsx("input",{id:"cfg-scatter-confidence",type:"checkbox",className:ne.checkbox,checked:i,onChange:g=>l(g.target.checked)}),n.jsx("span",{children:"Show Confidence Band (Shaded)"})]})}),n.jsx("div",{className:ne.formGroup,children:n.jsxs("label",{htmlFor:"cfg-scatter-correlation",className:ne.checkboxLabel,children:[n.jsx("input",{id:"cfg-scatter-correlation",type:"checkbox",className:ne.checkbox,checked:c,onChange:g=>d(g.target.checked)}),n.jsx("span",{children:"Show Correlation (r) Badge"})]})})]}),n.jsx("div",{className:ne.formGroup,children:n.jsxs("label",{htmlFor:"cfg-scatter-crosshairs",className:ne.checkboxLabel,children:[n.jsx("input",{id:"cfg-scatter-crosshairs",type:"checkbox",className:ne.checkbox,checked:f,onChange:g=>m(g.target.checked)}),n.jsx("span",{children:"Show Mean Quadrant Crosshairs"})]})}),n.jsxs("div",{className:ne.twoColRow,children:[n.jsx("div",{className:ne.formGroup,children:n.jsxs("label",{htmlFor:"cfg-scatter-start-at-zero-y",className:ne.checkboxLabel,children:[n.jsx("input",{id:"cfg-scatter-start-at-zero-y",type:"checkbox",className:ne.checkbox,checked:h,onChange:g=>{const S=g.target.checked;p(S),x(!S)}}),n.jsx("span",{children:"Start Vertical (Y) Axis at Zero"})]})}),n.jsx("div",{className:ne.formGroup,children:n.jsxs("label",{htmlFor:"cfg-scatter-start-at-zero-x",className:ne.checkboxLabel,children:[n.jsx("input",{id:"cfg-scatter-start-at-zero-x",type:"checkbox",className:ne.checkbox,checked:v,onChange:g=>{const S=g.target.checked;b(S),y(!S)}}),n.jsx("span",{children:"Start Horizontal (X) Axis at Zero"})]})})]})]}),ck=({titleOverride:e,setTitleOverride:t,subtitleOverride:s,setSubtitleOverride:r,xLabel:a="",setXLabel:o,yLabel:i="",setYLabel:l,chartType:c})=>{const d=c!=="donut";return n.jsxs("div",{className:ne.titlesSection,children:[n.jsxs("div",{className:ne.formGroup,children:[n.jsx("label",{className:ne.label,htmlFor:"cfg-title",children:n.jsx("span",{children:"Chart Title"})}),n.jsx("input",{id:"cfg-title",type:"text",className:ne.input,placeholder:"Leave blank to use default sheet title",value:e,onChange:f=>t(f.target.value)})]}),n.jsxs("div",{className:ne.formGroup,children:[n.jsx("label",{className:ne.label,htmlFor:"cfg-subtitle",children:n.jsx("span",{children:"Subtitle / Description"})}),n.jsx("input",{id:"cfg-subtitle",type:"text",className:ne.input,placeholder:"Summary of metrics, timeline, or scope",value:s,onChange:f=>r(f.target.value)})]}),d&&o&&l&&n.jsxs("div",{className:ne.twoColRow,children:[n.jsxs("div",{className:ne.formGroup,children:[n.jsx("label",{className:ne.label,htmlFor:"cfg-xlabel",children:n.jsx("span",{children:"X-Axis Label (Horizontal)"})}),n.jsx("input",{id:"cfg-xlabel",type:"text",className:ne.input,placeholder:"e.g. Period, Category",value:a,onChange:f=>o(f.target.value)})]}),n.jsxs("div",{className:ne.formGroup,children:[n.jsx("label",{className:ne.label,htmlFor:"cfg-ylabel",children:n.jsx("span",{children:"Y-Axis Label (Vertical)"})}),n.jsx("input",{id:"cfg-ylabel",type:"text",className:ne.input,placeholder:"e.g. Enrolled Learners, %",value:i,onChange:f=>l(f.target.value)})]})]})]})},dk=({effectiveScatterX:e,setScatterXColIndex:t,effectiveScatterY:s,setScatterYColIndex:r,effectiveScatterLabel:a,setScatterLabelColIndex:o,scatterGroupColIndex:i,setScatterGroupColIndex:l,detectedColumns:c})=>n.jsxs(n.Fragment,{children:[n.jsxs(wt,{name:"chart-data",title:"Axes Mapping",defaultOpen:!0,children:[n.jsx(Dn,{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"}))}),n.jsx(Dn,{id:"cfg-scatter-y-col",label:"Y-Axis Metric (Vertical)",value:s,onChange:d=>r(d),columns:c.map(d=>({index:d.index,label:d.label,type:"number"}))})]}),n.jsxs(wt,{name:"chart-data",title:"Point Labels & Grouping",defaultOpen:!1,children:[n.jsx(Dn,{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"}))}),n.jsx(Dn,{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"}))]})]})]}),uk=({chartType:e,categoryColIndex:t,setCategoryColIndex:s,detectedColumns:r,includedSeriesIndices:a,setIncludedSeriesIndices:o,binStrategy:i,setBinStrategy:l,customBinMode:c,setCustomBinMode:d,bucketSize:f,setBucketSize:m,binCount:h,setBinCount:p,histogramYMode:x,setHistogramYMode:v,groupOthers:b,setGroupOthers:y,sortField:g,setSortField:S,accentColor:C,handleToggleSeries:T})=>{var N;return n.jsxs(n.Fragment,{children:[n.jsx(wt,{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:n.jsx(Dn,{id:"cfg-category-col",label:"Source Column",value:t,onChange:_=>{if(s(_),e==="donut"){const k=r.filter(w=>w.index!==_);a!=null&&a.includes(_)&&o(k.length>0?[k[0].index]:[])}else a!=null&&a.includes(_)&&o(a.filter(k=>k!==_))},columns:r.map(_=>({index:_.index,label:_.label,type:e==="histogram"?"number":"text"}))})}),e==="histogram"&&n.jsxs(wt,{name:"chart-data",title:"Binning & Distribution",defaultOpen:!1,children:[i==="custom"?n.jsxs("div",{className:ne.twoColRow,children:[n.jsxs("div",{className:ne.formGroup,children:[n.jsx("label",{className:ne.label,htmlFor:"cfg-bin-strategy",children:n.jsx("span",{children:"Grouping Method"})}),n.jsxs("select",{id:"cfg-bin-strategy",className:ne.select,value:i,onChange:_=>l(_.target.value),children:[n.jsx("option",{value:"auto",children:"Automatic Best Fit"}),n.jsx("option",{value:"custom",children:"Custom Ranges"})]})]}),n.jsxs("div",{className:ne.formGroup,children:[n.jsx("label",{className:ne.label,htmlFor:"cfg-custom-bin-mode",children:n.jsx("span",{children:"Custom Range By"})}),n.jsxs("select",{id:"cfg-custom-bin-mode",className:ne.select,value:c,onChange:_=>d(_.target.value),children:[n.jsx("option",{value:"step",children:"Range Size"}),n.jsx("option",{value:"count",children:"Number of Groups"})]})]})]}):n.jsxs("div",{className:ne.formGroup,children:[n.jsx("label",{className:ne.label,htmlFor:"cfg-bin-strategy",children:n.jsx("span",{children:"Grouping Method"})}),n.jsxs("select",{id:"cfg-bin-strategy",className:ne.select,value:i,onChange:_=>l(_.target.value),children:[n.jsx("option",{value:"auto",children:"Automatic Best Fit"}),n.jsx("option",{value:"custom",children:"Custom Ranges"})]})]}),i==="custom"&&n.jsxs("div",{className:ne.formGroup,children:[n.jsx("label",{className:ne.label,htmlFor:c==="step"?"cfg-bucket-size":"cfg-bin-count",children:n.jsx("span",{children:c==="step"?"Range Size":"Number of Groups"})}),c==="step"?n.jsx("input",{id:"cfg-bucket-size",type:"number",className:ne.input,min:1,step:1,value:f,onChange:_=>{const k=_.target.value;if(k==="")m("");else{const w=parseInt(k,10);m(isNaN(w)?"":w)}},onBlur:()=>{(f===""||f<1)&&m(1)}}):n.jsx("input",{id:"cfg-bin-count",type:"number",className:ne.input,min:2,max:50,step:1,value:h,onChange:_=>{const k=_.target.value;if(k==="")p("");else{const w=parseInt(k,10);p(isNaN(w)?"":w)}},onBlur:()=>{h===""||h<2?p(2):h>50&&p(50)}})]}),n.jsx("div",{className:ne.formGroup,children:n.jsxs("label",{htmlFor:"cfg-histogram-ymode",className:ne.checkboxLabel,children:[n.jsx("input",{id:"cfg-histogram-ymode",type:"checkbox",className:ne.checkbox,checked:x==="relative",onChange:_=>v(_.target.checked?"relative":"frequency")}),n.jsx("span",{children:"Show as Percentage instead of Count"})]})})]}),e==="donut"?n.jsxs(wt,{name:"chart-data",title:"Slice Values",defaultOpen:!1,children:[n.jsx(Dn,{id:"cfg-donut-metric-col",label:"Slice Values (Metric)",value:a&&a.length>0?a[0]:((N=r.find(_=>_.index!==t))==null?void 0:N.index)??1,onChange:_=>{o([_]);const k=r.find(w=>w.index===_);k&&g!=="sheet"&&g!=="category"&&S(k.label)},columns:r.filter(_=>_.index!==t).map(_=>({index:_.index,label:_.label,type:"number"}))}),n.jsx("div",{className:ne.formGroup,children:n.jsxs("label",{htmlFor:"cfg-group-others",className:ne.checkboxLabel,children:[n.jsx("input",{id:"cfg-group-others",type:"checkbox",className:ne.checkbox,checked:b,onChange:_=>y(_.target.checked)}),n.jsx("span",{children:"Group smaller slices into 'Other' (Top 5)"})]})})]}):r.filter(_=>_.index!==t).length>0&&(()=>{const _=r.filter(j=>j.index!==t),k=_.map(j=>j.index),w=a??k,$=[..._].sort((j,D)=>{const H=w.indexOf(j.index),L=w.indexOf(D.index);return H!==-1&&L!==-1?H-L:H!==-1?-1:L!==-1?1:j.index-D.index}),I=Os({count:_.length,accentColor:C,tierMode:"bright"});return n.jsx(wt,{name:"chart-data",title:e==="histogram"?"Subgroup Frequencies":"Metric Series (Y-Axis)",defaultOpen:!1,badge:n.jsxs("span",{className:ne.seriesCountBadge,children:[w.length," / ",_.length]}),children:n.jsx("div",{className:ne.formGroup,children:n.jsx(Fu,{items:$,keyExtractor:j=>j.index,showMicroArrows:!1,onReorder:j=>{const D=j.filter(H=>w.includes(H.index)).map(H=>H.index);o(D)},renderItem:(j,D)=>{const H=w.includes(j.index),L=I[D.index]||"var(--folio-primary)";return n.jsxs("label",{className:ne.draggableRowLabel,children:[n.jsx("input",{type:"checkbox",className:ne.checkbox,checked:H,onChange:()=>T(j.index)}),n.jsx("span",{className:ne.seriesSwatch,style:{backgroundColor:L}}),n.jsxs("span",{className:ne.draggableRowText,children:[j.label," ",n.jsxs("span",{className:ne.draggableColLetter,children:["[",ct(j.index),"]"]})]})]})}})})})})()]})},hk="_sortingGrid_4c2fd_1",mk="_formGroup_4c2fd_7",fk="_label_4c2fd_13",pk="_selectWrapper_4c2fd_20",gk="_select_4c2fd_20",Gt={sortingGrid:hk,formGroup:mk,label:fk,selectWrapper:pk,select:gk},Hu=({sortField:e,sortDirection:t,categoryLabel:s="Category Name",seriesOptions:r=[],onSortFieldChange:a,onSortDirectionChange:o,className:i=""})=>n.jsxs("div",{className:`${Gt.sortingGrid} ${i}`.trim(),children:[n.jsxs("div",{className:Gt.formGroup,children:[n.jsx("label",{htmlFor:"cfg-sort-field",className:Gt.label,children:"Sort By"}),n.jsx("div",{className:Gt.selectWrapper,children:n.jsxs("select",{id:"cfg-sort-field",className:Gt.select,value:e,onChange:l=>a(l.target.value),children:[n.jsx("option",{value:"sheet",children:"Original Sheet Order"}),n.jsx("option",{value:"category",children:s}),r.map(l=>n.jsx("option",{value:l.id,children:l.name},l.id))]})})]}),n.jsxs("div",{className:Gt.formGroup,children:[n.jsx("label",{htmlFor:"cfg-sort-dir",className:Gt.label,children:"Sort Order"}),n.jsx("div",{className:Gt.selectWrapper,children:n.jsxs("select",{id:"cfg-sort-dir",className:Gt.select,value:t,onChange:l=>o(l.target.value),children:[n.jsx("option",{value:"asc",children:"Lowest to Highest"}),n.jsx("option",{value:"desc",children:"Highest to Lowest"})]})})]})]}),vk=({chartType:e,sortBy:t,setSortBy:s,sortField:r,setSortField:a,sortDirection:o,setSortDirection:i,categoryColIndex:l,detectedColumns:c})=>{const d=e==="donut"?n.jsxs("div",{className:ne.formGroup,children:[n.jsx("label",{className:ne.label,htmlFor:"cfg-donut-sort",children:n.jsx("span",{children:"Slice Order"})}),n.jsxs("div",{className:ne.twoColRow,children:[n.jsxs("select",{id:"cfg-donut-sort",className:ne.select,value:t==="none"?"sheet":"value",onChange:f=>{f.target.value==="sheet"?(s("none"),a("sheet")):(s(o==="desc"?"desc":"asc"),a("value"))},children:[n.jsx("option",{value:"value",children:"Largest Slices First (Clockwise)"}),n.jsx("option",{value:"sheet",children:"Original Sheet Order"})]}),n.jsxs("select",{id:"cfg-donut-sort-dir",className:ne.select,value:o,onChange:f=>{const m=f.target.value;i(m),t!=="none"&&s(m==="desc"?"desc":"asc")},disabled:t==="none",children:[n.jsx("option",{value:"desc",children:"Highest to Lowest"}),n.jsx("option",{value:"asc",children:"Lowest to Highest"})]})]})]}):e==="scatter"?n.jsxs("div",{className:ne.formGroup,children:[n.jsx("label",{className:ne.label,htmlFor:"cfg-scatter-sort",children:n.jsx("span",{children:"Sort Points By"})}),n.jsxs("div",{className:ne.twoColRow,children:[n.jsxs("select",{id:"cfg-scatter-sort",className:ne.select,value:r,onChange:f=>{const m=f.target.value;a(m),s(m==="sheet"?"none":o==="desc"?"desc":"asc")},children:[n.jsx("option",{value:"sheet",children:"Original Sheet Order"}),n.jsx("option",{value:"x",children:"Horizontal Axis (X)"}),n.jsx("option",{value:"y",children:"Vertical Axis (Y)"})]}),n.jsxs("select",{id:"cfg-scatter-sort-dir",className:ne.select,value:o,onChange:f=>{const m=f.target.value;i(m),r!=="sheet"&&s(m==="desc"?"desc":"asc")},disabled:r==="sheet",children:[n.jsx("option",{value:"asc",children:"Lowest to Highest"}),n.jsx("option",{value:"desc",children:"Highest to Lowest"})]})]})]}):n.jsx(Hu,{sortField:r,sortDirection:o,categoryLabel:e==="histogram"?"Range Interval":"Category Name",seriesOptions:e==="histogram"?[{id:"frequency",name:"Group Count"}]:c.filter(f=>f.index!==l).map(f=>({id:f.label,name:`${f.label} [${ct(f.index)}]`})),onSortFieldChange:f=>{a(f),s(f==="category"?o==="desc"?"category-desc":"category-asc":f==="sheet_order"||f==="sheet"?"none":o==="desc"?"desc":"asc")},onSortDirectionChange:f=>{i(f),s(r==="category"?f==="desc"?"category-desc":"category-asc":r==="sheet_order"||r==="sheet"?"none":f==="desc"?"desc":"asc")}});return n.jsxs("div",{className:ne.sectionBlock,children:[n.jsx("div",{className:ne.sectionHeader,children:n.jsx("span",{className:ne.sectionEyebrow,children:"Data Order & Direction"})}),d]})},xk="_stepPanel_1v17w_1",bk="_formGroup_1v17w_20",yk="_label_1v17w_26",_k="_select_1v17w_36",wk="_subTabGroup_1v17w_59",Sk="_subTabButton_1v17w_70",Ck="_subTabActive_1v17w_86",kk="_subTabPanel_1v17w_98",Nk="_subTabPanelHidden_1v17w_105",jk="_checkboxLabel_1v17w_109",Tk="_checkbox_1v17w_109",et={stepPanel:xk,formGroup:bk,label:yk,select:_k,subTabGroup:wk,subTabButton:Sk,subTabActive:Ck,subTabPanel:kk,subTabPanelHidden:Nk,checkboxLabel:jk,checkbox:Tk},Ik=({form:e,detectedColumns:t,accentColor:s,setupSubTab:r,setSetupSubTab:a,handleSubTabKeyDown:o,handleToggleSeries:i})=>{const{transpose:l,setTranspose:c,chartType:d,setChartType:f,barOrientation:m,setBarOrientation:h,stacked:p,setStacked:x,curveInterpolation:v,setCurveInterpolation:b,markerSize:y,setMarkerSize:g,showAreaFill:S,setShowAreaFill:C,startAtZero:T,setStartAtZero:N,setAutoScaleY:_,startAtZeroX:k,setStartAtZeroX:w,setAutoScaleX:$,donutVariant:I,setDonutVariant:j,showReferenceGuide:D,setShowReferenceGuide:H,showSummaryStats:L,setShowSummaryStats:U,showMedianMode:G,setShowMedianMode:z,loessBandwidth:q,setLoessBandwidth:P,showCorrelationChip:F,setShowCorrelationChip:R,titleOverride:W,setTitleOverride:se,subtitleOverride:re,setSubtitleOverride:le,xLabel:M,setXLabel:K,yLabel:Q,setYLabel:X,scatterXColIndex:ee,setScatterXColIndex:V,scatterYColIndex:J,setScatterYColIndex:Y,scatterLabelColIndex:te,setScatterLabelColIndex:oe,scatterGroupColIndex:B,setScatterGroupColIndex:E,categoryColIndex:O,setCategoryColIndex:ie,includedSeriesIndices:ce,setIncludedSeriesIndices:de,binStrategy:ae,setBinStrategy:fe,customBinMode:be,setCustomBinMode:ve,bucketSize:Pe,setBucketSize:Ce,binCount:Me,setBinCount:ot,histogramYMode:tn,setHistogramYMode:Dr,groupOthers:vn,setGroupOthers:Rr,sortField:nn,setSortField:Gs,showValues:Ft,setShowValues:zn,sortBy:xn,setSortBy:Br,sortDirection:bn,setSortDirection:Pr}=e,yn=typeof ee=="number"?ee:t.length>1?1:0,Or=typeof J=="number"?J:t.length>2?2:t.length>1?1:0,sn=typeof te=="number"?te:0;return n.jsxs("div",{className:et.stepPanel,children:[n.jsxs("div",{className:et.formGroup,children:[n.jsx("label",{className:et.label,htmlFor:"cfg-chart-type",children:n.jsx("span",{children:"Chart Type"})}),n.jsxs("select",{id:"cfg-chart-type",className:et.select,value:d,onChange:qn=>f(qn.target.value),children:[n.jsx("option",{value:"bar",children:"Bar Chart"}),n.jsx("option",{value:"line",children:"Line Chart"}),n.jsx("option",{value:"donut",children:"Donut Chart"}),n.jsx("option",{value:"scatter",children:"Scatter Plot"}),n.jsx("option",{value:"histogram",children:"Histogram"})]})]}),n.jsxs("div",{className:et.subTabGroup,role:"tablist","aria-label":"Chart Setup Sections",onKeyDown:o,children:[n.jsx("button",{id:"setup-tab-data",role:"tab",type:"button","aria-selected":r==="data","aria-controls":"setup-panel-data",tabIndex:r==="data"?0:-1,className:`${et.subTabButton} ${r==="data"?et.subTabActive:""}`,onClick:()=>a("data"),children:"Data"}),n.jsx("button",{id:"setup-tab-style",role:"tab",type:"button","aria-selected":r==="style","aria-controls":"setup-panel-style",tabIndex:r==="style"?0:-1,className:`${et.subTabButton} ${r==="style"?et.subTabActive:""}`,onClick:()=>a("style"),children:"Appearance"})]}),n.jsxs("div",{id:"setup-panel-data",role:"tabpanel","aria-labelledby":"setup-tab-data",className:`${et.subTabPanel} ${r!=="data"?et.subTabPanelHidden:""}`,hidden:r!=="data",children:[n.jsx(wt,{name:"chart-data",title:"Table Orientation",defaultOpen:!1,children:n.jsx("div",{className:et.formGroup,children:n.jsxs("label",{className:et.checkboxLabel,children:[n.jsx("input",{type:"checkbox",className:et.checkbox,checked:l,onChange:qn=>c(qn.target.checked)}),n.jsx("span",{children:"Transpose data: Swap rows and columns"})]})})}),d==="scatter"?n.jsx(dk,{effectiveScatterX:yn,setScatterXColIndex:V,effectiveScatterY:Or,setScatterYColIndex:Y,effectiveScatterLabel:sn,setScatterLabelColIndex:oe,scatterGroupColIndex:B,setScatterGroupColIndex:E,detectedColumns:t}):n.jsx(uk,{chartType:d,categoryColIndex:O,setCategoryColIndex:ie,detectedColumns:t,includedSeriesIndices:ce,setIncludedSeriesIndices:de,binStrategy:ae,setBinStrategy:fe,customBinMode:be,setCustomBinMode:ve,bucketSize:Pe,setBucketSize:Ce,binCount:Me,setBinCount:ot,histogramYMode:tn,setHistogramYMode:Dr,groupOthers:vn,setGroupOthers:Rr,sortField:nn,setSortField:Gs,accentColor:s,handleToggleSeries:i})]}),n.jsxs("div",{id:"setup-panel-style",role:"tabpanel","aria-labelledby":"setup-tab-style",className:`${et.subTabPanel} ${r!=="style"?et.subTabPanelHidden:""}`,hidden:r!=="style",children:[n.jsx(wt,{name:"chart-appearance",title:"Titles & Axis Labels",defaultOpen:!0,children:n.jsx(ck,{titleOverride:W,setTitleOverride:se,subtitleOverride:re,setSubtitleOverride:le,xLabel:M,setXLabel:K,yLabel:Q,setYLabel:X,chartType:d})}),n.jsxs(wt,{name:"chart-appearance",title:"Geometry & Visual Style",defaultOpen:!1,children:[d==="bar"&&n.jsx(rk,{barOrientation:m,setBarOrientation:h,stacked:p,setStacked:x}),d==="line"&&n.jsx(ak,{curveInterpolation:v,setCurveInterpolation:b,markerSize:y,setMarkerSize:g,showAreaFill:S,setShowAreaFill:C,startAtZero:T,setStartAtZero:N,setAutoScaleY:_}),d==="donut"&&n.jsx(ok,{donutVariant:I,setDonutVariant:j}),d==="histogram"&&n.jsx(ik,{curveInterpolation:v,setCurveInterpolation:b,showReferenceGuide:D,setShowReferenceGuide:H,showSummaryStats:L,setShowSummaryStats:U,showMedianMode:G,setShowMedianMode:z}),d==="scatter"&&n.jsx(lk,{curveInterpolation:v,setCurveInterpolation:b,markerSize:y,setMarkerSize:g,loessBandwidth:q,setLoessBandwidth:P,showAreaFill:S,setShowAreaFill:C,showCorrelationChip:F,setShowCorrelationChip:R,showReferenceGuide:D,setShowReferenceGuide:H,startAtZero:T,setStartAtZero:N,setAutoScaleY:_,startAtZeroX:k,setStartAtZeroX:w,setAutoScaleX:$})]}),(d==="bar"||d==="line"||d==="donut")&&n.jsxs(wt,{name:"chart-appearance",title:"Data Labels",defaultOpen:!1,children:[d==="bar"&&n.jsx(ia,{id:"cfg-show-values-bar-app",checked:Ft,onChange:zn,label:"Show numbers on bars"}),d==="line"&&n.jsx(ia,{id:"cfg-show-values-line-app",checked:Ft,onChange:zn,label:"Show numbers on points"}),d==="donut"&&n.jsx(ia,{id:"cfg-show-values-donut-app",checked:Ft,onChange:zn,label:"Show percentages or values on slices"})]}),n.jsx(wt,{name:"chart-appearance",title:"Order & Direction",defaultOpen:!1,children:n.jsx(vk,{chartType:d,sortBy:xn,setSortBy:Br,sortField:nn,setSortField:Gs,sortDirection:bn,setSortDirection:Pr,categoryColIndex:O,detectedColumns:t})})]})]})},Wi=({isOpen:e,onClose:t,chartId:s,nodeId:r,initialConfig:a,previewMatrix:o,onDeployed:i,mode:l="edit"})=>{const[c,d]=u.useState(1),[f,m]=u.useState("data"),[h,p]=u.useState(!1),[x,v]=u.useState(!1),[b,y]=u.useState(!1),[g,S]=u.useState(null),{showToast:C}=Ne(),T=u.useRef(!1),N=u.useRef(null),_=MS(a);Fa(e&&_.hasUnsavedChanges,`chart-config-${s}`);const k=DS({sheetUrl:_.sheetUrl,tabName:_.tabName,sheetGid:_.sheetGid,initialConfig:a,setTabName:_.setTabName,setSheetGid:_.setSheetGid,setLastModifiedTime:_.setLastModifiedTime,onAutoSelectTab:(V,J)=>{_.setSavedSnapshot(Y=>Y.sheetUrl===_.sheetUrl.trim()&&!Y.tabName?{...Y,tabName:V,sheetGid:J}:Y)}}),w=RS({sheetUrl:_.sheetUrl,tabName:_.tabName,sheetGid:_.sheetGid,range:_.range,previewMatrix:o||(a==null?void 0:a.cachedDataset)||void 0});u.useEffect(()=>{e&&(!T.current||N.current!==s)&&(d(1),m("data"),_.resetForm(a),k.resetVerification(a==null?void 0:a.sheetUrl,a==null?void 0:a.tabName,a==null?void 0:a.sheetGid)),T.current=e,N.current=s},[e,s,a,_,k]);const $=u.useRef(_.tabName),I=u.useRef(!1);u.useEffect(()=>{_.tabName!==$.current&&($.current=_.tabName,I.current=!1)},[_.tabName]),u.useEffect(()=>{if(!w.detectedRange)return;const V=!!(a!=null&&a.range&&a.range.trim()!==""&&a.range.trim()!=="A1:D6"&&(!a.tabName||a.tabName===_.tabName));I.current||(!V||l==="add"||_.tabName!==(a==null?void 0:a.tabName))&&_.setRange(w.detectedRange)},[w.detectedRange,a,_,l]);const j=V=>{var te,oe,B,E;const J=["data","style"],Y=J.indexOf(f);if(V.key==="ArrowRight"){V.preventDefault();const O=J[(Y+1)%J.length];m(O),(te=document.getElementById(`setup-tab-${O}`))==null||te.focus()}else if(V.key==="ArrowLeft"){V.preventDefault();const O=J[(Y-1+J.length)%J.length];m(O),(oe=document.getElementById(`setup-tab-${O}`))==null||oe.focus()}else V.key==="Home"?(V.preventDefault(),m("data"),(B=document.getElementById("setup-tab-data"))==null||B.focus()):V.key==="End"&&(V.preventDefault(),m("style"),(E=document.getElementById("setup-tab-style"))==null||E.focus())},D=u.useMemo(()=>!w.liveMatrix||w.liveMatrix.length===0?w.liveMatrix:_.transpose?yu(w.liveMatrix):w.liveMatrix,[w.liveMatrix,_.transpose]),H=u.useMemo(()=>((D.length>0?D:o||[])[0]||[]).map((Y,te)=>({index:te,label:Y!=null&&String(Y).trim()!==""?String(Y).trim():`Col ${te+1}`})),[D,o]),L=u.useCallback(V=>{const J=H.filter(te=>te.index!==_.categoryColIndex).map(te=>te.index),Y=_.includedSeriesIndices??J;Y.includes(V)?Y.length>1&&_.setIncludedSeriesIndices(Y.filter(te=>te!==V)):_.setIncludedSeriesIndices([...Y,V])},[H,_]),G=!!u.useMemo(()=>Ar(_.range),[_.range]),z=u.useCallback(V=>V===1?!0:V===2?k.isStep1Valid&&G:!1,[k.isStep1Valid,G]),q=Eu[r]||"var(--folio-primary)",P=typeof _.scatterXColIndex=="number"?_.scatterXColIndex:H.length>1?1:0,F=typeof _.scatterYColIndex=="number"?_.scatterYColIndex:H.length>2?2:H.length>1?1:0,R=typeof _.scatterLabelColIndex=="number"?_.scatterLabelColIndex:0,W=u.useMemo(()=>{if(!w.liveMatrix||w.liveMatrix.length===0)return null;try{const V=w.liveMatrix.map(Y=>Y.map(te=>te==null?"":String(te))),J=_.buildConfigPayload(s,r,P,F,R);return ns({chartId:s,title:_.titleOverride.trim()||"",subtitle:_.subtitleOverride.trim()||void 0,unit:_.unit.trim()||void 0,chartType:_.chartType,nodeId:r,visualConfig:J.visualConfig,rawMatrix:V})}catch{return null}},[w.liveMatrix,_,s,r,P,F,R]),se=u.useCallback(async()=>{if(!_.sheetUrl.trim()){S({message:"Please enter a Google Sheet URL first.",type:"error"});return}try{await k.executeVerification(_.sheetUrl),w.executeSync(),I.current=!1,S({message:"Google Sheet source and tabs resynced.",type:"info"})}catch{S({message:"Failed to resync Google Sheet source.",type:"error"})}},[_.sheetUrl,k,w]),re=u.useCallback(async()=>{if(!_.sheetUrl.trim()){S({message:"Google Sheet URL is required.",type:"error"});return}if(!G){S({message:"Please provide a valid cell range such as A1:D6.",type:"error"});return}p(!0);const J={..._.buildConfigPayload(s,r,P,F,R),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 Y=await As(J);Y.savedToCloud?(jt(J),_.markAsSaved(J),S({message:"Chart configuration saved.",type:"success"}),i==null||i(J)):Y.savedLocally?(jt(J),_.markAsSaved(J),i==null||i(J),S({message:ss(Y,"save"),type:Y.error?"error":"info"})):S({message:ss(Y,"save"),type:"error"})}catch(Y){S({message:ss(Y,"save"),type:"error"})}finally{p(!1)}},[_,s,r,G,P,F,R,w.liveMatrix,w.fetchedMatrix,a==null?void 0:a.cachedDataset,i]),le=u.useCallback(async()=>{if(!_.sheetUrl.trim()){S({message:"Google Sheet URL is required.",type:"error"});return}if(!G){S({message:"Please provide a valid cell range such as A5:D12.",type:"error"});return}v(!0);const J={..._.buildConfigPayload(s,r,P,F,R),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 Y=await As(J);if(Y.savedToCloud){jt(J),_.markAsSaved(J);const te=l==="add"?"Chart added to canvas and saved to draft.":"Chart saved to draft successfully.";S({message:te,type:"success"}),C(te,"success"),i==null||i(J),t()}else Y.savedLocally&&(jt(J),_.markAsSaved(J),i==null||i(J),t()),S({message:ss(Y,"deploy"),type:"error"})}catch(Y){S({message:ss(Y,"deploy"),type:"error"})}finally{v(!1)}},[_,s,r,G,P,F,R,w.liveMatrix,w.fetchedMatrix,a==null?void 0:a.cachedDataset,l,i,t,C]),M=u.useMemo(()=>({..._.buildConfigPayload(s,r,P,F,R),cachedDataset:w.liveMatrix&&w.liveMatrix.length>0?w.liveMatrix:a==null?void 0:a.cachedDataset}),[_,s,r,P,F,R,w.liveMatrix,a==null?void 0:a.cachedDataset]),K=u.useMemo(()=>[{id:1,label:"Source & Range",badge:k.isStep1Valid&&G&&c!==1?"✓":"1",completed:k.isStep1Valid&&G},{id:2,label:"Chart Setup",badge:"2",disabled:!z(2)}],[c,k.isStep1Valid,G,z]),Q=u.useMemo(()=>{if(c===1){const V=w.fullMatrix&&w.fullMatrix.length>0?w.fullMatrix:D;return n.jsx(Gu,{matrix:V,range:_.range,isSelecting:b,onRangeSelect:J=>{I.current=!0,_.setRange(J)}})}return c===2?n.jsx("div",{className:ne.companionChartViewport,children:n.jsx("div",{children:n.jsx(Ki,{chartId:s,dataset:W,config:M,nodeId:r,accentColor:q,editTriggerId:s,hideEditButton:!0,status:w.isSyncing?"syncing":W?"success":"pending_data"})})}):null},[c,w.fullMatrix,D,_.range,_.setRange,b,s,W,M,r,q,w.isSyncing]),X=n.jsx(n.Fragment,{children:c===1?n.jsx(he,{variant:"secondary",size:"sm",type:"button",onClick:t,children:"Cancel"}):n.jsx(he,{variant:"secondary",size:"sm",type:"button",onClick:()=>d(1),children:"← Back"})}),ee=n.jsxs(n.Fragment,{children:[c===1&&n.jsxs(n.Fragment,{children:[_.hasUnsavedChanges&&n.jsx(he,{variant:"secondary",size:"sm",type:"button",className:ne.saveButton,onClick:re,disabled:h||!k.isStep1Valid||!G,children:h?n.jsxs(n.Fragment,{children:[n.jsx("span",{className:ne.spinner,"aria-hidden":"true"}),n.jsx("span",{children:"Saving..."})]}):"Save"}),n.jsx(he,{variant:"primary",size:"sm",type:"button",disabled:!k.isStep1Valid||!G,onClick:()=>d(2),children:"Next: Chart Setup →"})]}),c===2&&n.jsxs(n.Fragment,{children:[_.hasUnsavedChanges&&n.jsx(he,{variant:"secondary",size:"sm",type:"button",className:ne.saveButton,onClick:re,disabled:h,children:h?n.jsxs(n.Fragment,{children:[n.jsx("span",{className:ne.spinner,"aria-hidden":"true"}),n.jsx("span",{children:"Saving..."})]}):"Save Draft"}),n.jsx(he,{variant:"primary",size:"sm",type:"button",disabled:x||!k.isStep1Valid||!G,onClick:le,children:x?n.jsxs(n.Fragment,{children:[n.jsx("span",{className:ne.spinner,"aria-hidden":"true"}),n.jsx("span",{children:"Deploying…"})]}):l==="add"?"Add to Canvas & Save ":"Save in Draft"})]})]});return n.jsxs(n.Fragment,{children:[n.jsxs(Vi,{isOpen:e,onClose:t,title:"Chart Setup",tabs:K,activeTab:c,onTabChange:V=>{z(V)&&d(V)},footerLeft:X,footerRight:ee,closeOnOutsideClick:!1,companionContent:Q,children:[c===1&&n.jsx(mC,{sheetUrl:_.sheetUrl,setSheetUrl:_.setSheetUrl,accessStatus:k.accessStatus,statusMessage:k.statusMessage,discoveredTabs:k.discoveredTabs,tabName:_.tabName,sheetGid:_.sheetGid,setTabName:_.setTabName,executeVerification:k.executeVerification,handleTabChange:k.handleTabChange,onResync:se,isSyncing:w.isSyncing,range:_.range,isRangeValid:G,isSelectingRange:b,setIsSelectingRange:y,executeSync:w.executeSync}),c===2&&n.jsx(Ik,{form:_,detectedColumns:H,accentColor:q,setupSubTab:f,setSetupSubTab:m,handleSubTabKeyDown:j,handleToggleSeries:L})]}),g&&n.jsx(Ot,{message:g.message,type:g.type,durationMs:g.type==="error"?5500:3500,onDismiss:()=>S(null)})]})},Ak="_modalCard_hh7jb_8",Ek="_header_hh7jb_28",$k="_headerInfo_hh7jb_37",Lk="_title_hh7jb_44",Mk="_subtitleRow_hh7jb_54",Dk="_asOfCaption_hh7jb_61",Rk="_headerActions_hh7jb_71",Bk="_closeButton_hh7jb_78",Pk="_tableWrapper_hh7jb_107",Ok="_table_hh7jb_107",Fk="_headerCell_hh7jb_128",Uk="_indexColHeader_hh7jb_144",Gk="_indexCell_hh7jb_153",Hk="_categoryCell_hh7jb_167",zk="_dataCell_hh7jb_178",qk="_numCell_hh7jb_187",Vk="_headerNumCell_hh7jb_194",Wk="_tableRow_hh7jb_198",Kk="_nullCell_hh7jb_204",Yk="_emptyState_hh7jb_209",ge={modalCard:Ak,header:Ek,headerInfo:$k,title:Lk,subtitleRow:Mk,asOfCaption:Dk,headerActions:Rk,closeButton:Bk,tableWrapper:Pk,table:Ok,headerCell:Fk,indexColHeader:Uk,indexCell:Gk,categoryCell:Hk,dataCell:zk,numCell:qk,headerNumCell:Vk,tableRow:Wk,nullCell:Kk,emptyState:Yk},zu=({isOpen:e,onClose:t,dataset:s,title:r,asOfDate:a,onDownloadCsv:o})=>{if(!e)return null;const i=s.chartType==="scatter"&&s.scatterPoints&&s.scatterPoints.length>0,l=s.chartType==="histogram"&&s.bins&&s.bins.length>0,c=!!(s.categories&&s.categories.length>0&&s.series&&s.series.length>0),d=()=>{var f,m;if(i&&s.scatterPoints){const h=((f=s.visualConfig)==null?void 0:f.xLabel)||"X",p=((m=s.visualConfig)==null?void 0:m.yLabel)||"Y",x=s.scatterPoints.some(S=>!!S.group),v=x?4:3,b=x?34:40,y=(100-b)/(v-1),g=208+(v-1)*130;return n.jsxs("table",{className:ge.table,style:{minWidth:`${g}px`},"aria-label":`Tabular data for ${r}`,children:[n.jsxs("colgroup",{children:[n.jsx("col",{style:{width:"48px"}}),n.jsx("col",{style:{width:`${b}%`}}),n.jsx("col",{style:{width:`${y}%`}}),n.jsx("col",{style:{width:`${y}%`}}),x&&n.jsx("col",{style:{width:`${y}%`}})]}),n.jsx("thead",{children:n.jsxs("tr",{children:[n.jsx("th",{className:`${ge.headerCell} ${ge.indexColHeader}`,scope:"col",children:"#"}),n.jsx("th",{className:ge.headerCell,scope:"col",children:"Label"}),n.jsx("th",{className:`${ge.headerCell} ${ge.headerNumCell}`,scope:"col",children:h}),n.jsx("th",{className:`${ge.headerCell} ${ge.headerNumCell}`,scope:"col",children:p}),x&&n.jsx("th",{className:ge.headerCell,scope:"col",children:"Group"})]})}),n.jsx("tbody",{children:s.scatterPoints.map((S,C)=>n.jsxs("tr",{className:ge.tableRow,children:[n.jsx("td",{className:ge.indexCell,children:C+1}),n.jsx("td",{className:ge.categoryCell,title:S.label||"",children:S.label||"—"}),n.jsx("td",{className:`${ge.dataCell} ${ge.numCell}`,children:Number.isFinite(S.x)?S.x:"—"}),n.jsx("td",{className:`${ge.dataCell} ${ge.numCell}`,children:Number.isFinite(S.y)?S.y:"—"}),x&&n.jsx("td",{className:ge.dataCell,children:S.group||"—"})]},C))})]})}if(l&&s.bins)return n.jsxs("table",{className:ge.table,style:{minWidth:"398px"},"aria-label":`Tabular data for ${r}`,children:[n.jsxs("colgroup",{children:[n.jsx("col",{style:{width:"48px"}}),n.jsx("col",{style:{width:"55%"}}),n.jsx("col",{style:{width:"45%"}})]}),n.jsx("thead",{children:n.jsxs("tr",{children:[n.jsx("th",{className:`${ge.headerCell} ${ge.indexColHeader}`,scope:"col",children:"#"}),n.jsx("th",{className:ge.headerCell,scope:"col",children:"Range (Bins)"}),n.jsx("th",{className:`${ge.headerCell} ${ge.headerNumCell}`,scope:"col",children:"Frequency Count"})]})}),n.jsx("tbody",{children:s.bins.map((p,x)=>n.jsxs("tr",{className:ge.tableRow,children:[n.jsx("td",{className:ge.indexCell,children:x+1}),n.jsx("td",{className:ge.categoryCell,children:`${p.x0} – ${p.x1}`}),n.jsx("td",{className:`${ge.dataCell} ${ge.numCell}`,children:p.count})]},x))})]});if(c&&s.categories&&s.series){const h=s.categories,p=s.series,x=p.length,v=x<=2?34:x<=4?26:20,b=(100-v)/x,y=208+x*130;return n.jsxs("table",{className:ge.table,style:{minWidth:`${y}px`},"aria-label":`Tabular data for ${r}`,children:[n.jsxs("colgroup",{children:[n.jsx("col",{style:{width:"48px"}}),n.jsx("col",{style:{width:`${v}%`}}),p.map((g,S)=>n.jsx("col",{style:{width:`${b}%`}},S))]}),n.jsx("thead",{children:n.jsxs("tr",{children:[n.jsx("th",{className:`${ge.headerCell} ${ge.indexColHeader}`,scope:"col",children:"#"}),n.jsx("th",{className:ge.headerCell,scope:"col",children:"Category"}),p.map((g,S)=>n.jsx("th",{className:`${ge.headerCell} ${ge.headerNumCell}`,scope:"col",title:g.name||`Series ${S+1}`,children:g.name||`Series ${S+1}`},S))]})}),n.jsx("tbody",{children:h.map((g,S)=>n.jsxs("tr",{className:ge.tableRow,children:[n.jsx("td",{className:ge.indexCell,children:S+1}),n.jsx("td",{className:ge.categoryCell,title:g||"",children:g||"—"}),p.map((C,T)=>{const N=C.data[S],_=N!=null&&Number.isFinite(N);return n.jsx("td",{className:`${ge.dataCell} ${ge.numCell}`,children:_?n.jsx("span",{children:N}):n.jsx("span",{className:ge.nullCell,children:"—"})},T)})]},S))})]})}return n.jsx("div",{className:ge.emptyState,children:n.jsx("p",{children:"No tabular data available for this chart visualization."})})};return n.jsxs(ut,{isOpen:e,onClose:t,cardClassName:ge.modalCard,showCloseButton:!1,ariaLabel:`Data table for ${r}`,children:[n.jsxs("header",{className:ge.header,children:[n.jsxs("div",{className:ge.headerInfo,children:[n.jsx("h3",{className:ge.title,children:r}),n.jsx("div",{className:ge.subtitleRow,children:a&&n.jsxs("span",{className:ge.asOfCaption,children:["As of ",a]})})]}),n.jsxs("div",{className:ge.headerActions,children:[o&&n.jsx(he,{variant:"secondary",size:"xs",onClick:o,"aria-label":`Download CSV data for ${r}`,children:n.jsx("span",{children:"Download Data (CSV)"})}),n.jsx("button",{type:"button",className:ge.closeButton,onClick:t,"aria-label":"Close data table modal",children:"✕"})]})]}),n.jsx("div",{className:ge.tableWrapper,tabIndex:-1,children:d()})]})},Xk="_cardOuterWrapper_85koo_8",Jk="_card_85koo_8",Zk="_sideEditWrapper_85koo_37",Qk="_sideEditBtn_85koo_46",eN="_sideSyncBtn_85koo_47",tN="_syncIcon_85koo_54",nN="_spinning_85koo_59",sN="_highlightedCard_85koo_72",rN="_title_85koo_78",aN="_subtitle_85koo_90",oN="_contentWrapper_85koo_108",iN="_footer_85koo_122",lN="_asOfCaption_85koo_132",cN="_footerActions_85koo_141",dN="_viewTableAction_85koo_149",uN="_downloadAction_85koo_150",Ye={cardOuterWrapper:Xk,card:Jk,sideEditWrapper:Zk,sideEditBtn:Qk,sideSyncBtn:eN,syncIcon:tN,spinning:nN,highlightedCard:sN,title:rN,subtitle:aN,contentWrapper:oN,footer:iN,asOfCaption:lN,footerActions:cN,viewTableAction:dN,downloadAction:uN},Ki=({chartId:e,dataset:t,config:s,nodeId:r="access",nodeTitle:a,accentColor:o,status:i,errorMessage:l,onConfigUpdated:c,onSync:d,isSyncing:f=!1,className:m,editTriggerId:h,hideEditButton:p=!1})=>{var F,R,W;const{isDevMode:x,isDesktop:v}=Ne(),b=x&&v&&!p,[y,g]=u.useState(!1),[S,C]=u.useState(!1),[T,N]=u.useState(!1),_=f||i==="syncing"||T,[k,w]=u.useState(null),$=u.useCallback(async()=>{if(!_){if(!(s!=null&&s.sheetUrl)){w({message:"No Google Sheet linked yet. Opening drawer to configure...",type:"info"}),g(!0);return}N(!0);try{if(d)await d(),w({message:"Chart synced successfully from Google Sheet.",type:"success"});else{const se=await $i({sheetUrl:s.sheetUrl,tabName:s.tabName,sheetGid:s.sheetGid,range:s.range,timeoutMs:8e3});if(se&&se.length>0){const re={...s,cachedDataset:se,updatedAt:new Date().toISOString()};await As(re),Ua(e,re),c==null||c(re),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 re=se instanceof Error?se.message:"Failed to sync chart from Google Sheet.";w({message:re,type:"error"})}finally{N(!1)}}},[_,s,d,e,c]),I=(s==null?void 0:s.titleOverride)||(t==null?void 0:t.title)||"",j=(s==null?void 0:s.subtitleOverride)||(t==null?void 0:t.subtitle),H=Mo((F=s==null?void 0:s.visualConfig)==null?void 0:F.lastModifiedTime)||Mo((R=t==null?void 0:t.visualConfig)==null?void 0:R.lastModifiedTime)||(t==null?void 0:t.asOfDate)||"Current SY",L=(s==null?void 0:s.unitOverride)||(t==null?void 0:t.unit)||((W=t==null?void 0:t.visualConfig)==null?void 0:W.unit),U=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]),G=u.useMemo(()=>U?"none":i==="error"||l?"connection_error":s!=null&&s.sheetUrl?"data_format":"unlinked",[U,i,l,s==null?void 0:s.sheetUrl]),z=u.useCallback(()=>{var X,ee,V;let se=t==null?void 0:t.sanitizedCsvContent;if(!se&&(t!=null&&t.categories)&&(t!=null&&t.series)&&(se=ou(t.categories,t.series,I,L)),!se)return;const re=(s==null?void 0:s.tabName)||((X=s==null?void 0:s.visualConfig)==null?void 0:X.tabName)||((ee=t==null?void 0:t.visualConfig)==null?void 0:ee.tabName)||(s!=null&&s.range?(V=Ar(s.range))==null?void 0:V.sheetName:void 0),le=xv({title:I,sheetName:re,chartId:e}),M=new Blob([se],{type:"text/csv;charset=utf-8;"}),K=URL.createObjectURL(M),Q=document.createElement("a");Q.setAttribute("href",K),Q.setAttribute("download",le),document.body.appendChild(Q),Q.click(),document.body.removeChild(Q),URL.revokeObjectURL(K)},[t,I,L,e,s]),[q,P]=u.useState(!1);return n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:Ye.cardOuterWrapper,children:[n.jsxs("article",{className:`${Ye.card} ${q?Ye.highlightedCard:""} ${m||""}`,"aria-labelledby":`chart-title-${e}`,tabIndex:-1,children:[n.jsxs("header",{className:Ye.header,children:[I&&n.jsx("h3",{id:`chart-title-${e}`,className:Ye.title,children:I}),j&&n.jsx("p",{className:Ye.subtitle,children:j})]}),n.jsx("div",{className:Ye.contentWrapper,children:U&&t?n.jsx(Pu,{dataset:t,accentColor:o}):n.jsx(Ou,{chartId:e,nodeTitle:a,category:G,errorMessage:l,hasSheetUrl:!!(s!=null&&s.sheetUrl),onEdit:()=>g(!0)})}),U&&n.jsxs("footer",{className:Ye.footer,children:[n.jsxs("span",{className:Ye.asOfCaption,children:["As of ",H]}),n.jsxs("div",{className:Ye.footerActions,children:[n.jsx(he,{variant:"secondary",size:"xs",className:Ye.viewTableAction,onClick:()=>C(!0),"aria-label":`View data table for ${I}`,children:n.jsx("span",{children:"View Table"})}),n.jsx(he,{variant:"secondary",size:"xs",className:Ye.downloadAction,onClick:z,"aria-label":`Download CSV data for ${I}`,children:n.jsx("span",{children:"Download Data (CSV)"})})]})]})]}),b&&n.jsxs("div",{className:Ye.sideEditWrapper,children:[n.jsx(he,{type:"button",variant:"admin",size:"xs","data-dev-edit-trigger":"true","data-canvas-edit-trigger":h,onClick:()=>g(!0),onMouseEnter:()=>P(!0),onMouseLeave:()=>P(!1),"aria-label":`Edit chart ${e}`,title:`Edit chart ${e}`,className:Ye.sideEditBtn,children:"✎ Edit"}),n.jsxs(he,{type:"button",variant:"admin",size:"xs",onClick:$,onMouseEnter:()=>P(!0),onMouseLeave:()=>P(!1),disabled:_,className:Ye.sideSyncBtn,title:"Sync chart data from Google Sheet","aria-label":`Sync chart data for ${e}`,children:[n.jsx("span",{className:`${Ye.syncIcon} ${_?Ye.spinning:""}`,"aria-hidden":"true",children:"↻"}),n.jsx("span",{children:_?"Syncing…":"Sync"})]})]})]}),b&&n.jsx(Wi,{isOpen:y,onClose:()=>g(!1),chartId:e,nodeId:r,initialConfig:s||void 0,onDeployed:se=>{c==null||c(se)}}),U&&t&&n.jsx(zu,{isOpen:S,onClose:()=>C(!1),dataset:t,title:I,asOfDate:H,onDownloadCsv:z}),k&&n.jsx(Ot,{message:k.message,type:k.type,durationMs:k.type==="error"?5500:3500,onDismiss:()=>w(null)})]})},Yi=u.memo(({element:e,nodeId:t,nodeTitle:s,accentColor:r,isDevMode:a,className:o})=>{const{isDevMode:i}=Ne(),l=a??i,{dataset:c,config:d,reload:f,status:m,errorMessage:h,syncLiveSheet:p}=Hx({chartId:e.chartId,nodeId:t,isDevMode:l});return n.jsx("div",{className:`${ze.chartContainer} ${o||""}`.trim(),children:n.jsx(Ki,{chartId:e.chartId,dataset:c,config:d,status:m,errorMessage:h,nodeId:t,nodeTitle:s,accentColor:r,editTriggerId:e.id,onConfigUpdated:()=>{f()},onSync:p,isSyncing:m==="syncing"})})});Yi.displayName="CanvasChart";const hN="_addBarGutter_1q43h_15",mN="_hoverGuideLine_1q43h_25",fN="_addBarActive_1q43h_37",pN="_addPillButton_1q43h_48",gN="_plusIcon_1q43h_115",vN="_paletteMenu_1q43h_125",xN="_dropdownMenu_1q43h_153",bN="_dropupMenu_1q43h_158",yN="_paletteOptionWrapper_1q43h_164",_N="_paletteOption_1q43h_164",wN="_paletteIcon_1q43h_209",SN="_chevronIcon_1q43h_224",CN="_paletteOptionActive_1q43h_241",kN="_subMenu_1q43h_255",NN="_dropupSubMenu_1q43h_298",jN="_subOption_1q43h_311",TN="_subOptionIcon_1q43h_346",IN="_addBarSuppressed_1q43h_362",AN="_starterContainer_1q43h_373",EN="_starterButton_1q43h_384",$N="_itemControlsWrapper_1q43h_427",LN="_itemControlsFloatingBar_1q43h_431",MN="_sectionFloatingBar_1q43h_458",DN="_suppressHover_1q43h_474",RN="_dragHandle_1q43h_479",BN="_dropTargetHighlight_1q43h_501",PN="_isDragging_1q43h_506",ON="_controlButton_1q43h_510",FN="_editButton_1q43h_548",UN="_deleteButton_1q43h_572",GN="_editIcon_1q43h_582",HN="_deleteIcon_1q43h_583",zN="_modalBody_1q43h_593",qN="_modalMessage_1q43h_600",VN="_modalWarning_1q43h_608",WN="_modalActions_1q43h_619",KN="_modalDeleteButton_1q43h_627",xe={addBarGutter:hN,hoverGuideLine:mN,addBarActive:fN,addPillButton:pN,plusIcon:gN,paletteMenu:vN,dropdownMenu:xN,dropupMenu:bN,paletteOptionWrapper:yN,paletteOption:_N,paletteIcon:wN,chevronIcon:SN,paletteOptionActive:CN,subMenu:kN,dropupSubMenu:NN,subOption:jN,subOptionIcon:TN,addBarSuppressed:IN,starterContainer:AN,starterButton:EN,itemControlsWrapper:$N,itemControlsFloatingBar:LN,sectionFloatingBar:MN,suppressHover:DN,dragHandle:RN,dropTargetHighlight:BN,isDragging:PN,controlButton:ON,editButton:FN,deleteButton:UN,editIcon:GN,deleteIcon:HN,modalBody:zN,modalMessage:qN,modalWarning:VN,modalActions:WN,modalDeleteButton:KN},Lc=({className:e})=>n.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:[n.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),n.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),YN=({className:e})=>n.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:[n.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),n.jsx("path",{d:"M3 9h18"}),n.jsx("path",{d:"M7 15h10"})]}),XN=({className:e})=>n.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:[n.jsx("path",{d:"M4 5h16"}),n.jsx("path",{d:"M9 12h11"}),n.jsx("path",{d:"M9 18h8"}),n.jsx("polyline",{points:"4 9 4 15 7 15"})]}),JN=({className:e})=>n.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:[n.jsx("polyline",{points:"4 7 4 4 20 4 20 7"}),n.jsx("line",{x1:"9",y1:"20",x2:"15",y2:"20"}),n.jsx("line",{x1:"12",y1:"4",x2:"12",y2:"20"})]}),qu=({className:e})=>n.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:[n.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),n.jsx("circle",{cx:"8.5",cy:"8.5",r:"1.5"}),n.jsx("polyline",{points:"21 15 16 10 5 21"})]}),ZN=({className:e})=>n.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:[n.jsx("rect",{x:"3",y:"3",width:"7",height:"7",rx:"1.5"}),n.jsx("rect",{x:"14",y:"3",width:"7",height:"7",rx:"1.5"}),n.jsx("rect",{x:"3",y:"14",width:"7",height:"7",rx:"1.5"}),n.jsx("rect",{x:"14",y:"14",width:"7",height:"7",rx:"1.5"})]}),QN=({className:e})=>n.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:n.jsx("polyline",{points:"9 18 15 12 9 6"})}),ej=({className:e})=>n.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:[n.jsx("line",{x1:"18",y1:"20",x2:"18",y2:"10"}),n.jsx("line",{x1:"12",y1:"20",x2:"12",y2:"4"}),n.jsx("line",{x1:"6",y1:"20",x2:"6",y2:"14"})]}),tj=[{type:"section",label:"Section",IconComponent:YN},{type:"subsection",label:"Subsection",IconComponent:XN},{type:"text",label:"Text",IconComponent:JN},{type:"photo",label:"Photo",IconComponent:qu},{type:"chart",label:"Chart",IconComponent:ej}],qt=u.memo(({onAddElement:e,isInitialStarter:t=!1,accentColor:s,className:r,label:a="Click to add the first Section",barId:o,activeBarId:i,onToggleActive:l})=>{const{isDevMode:c,isDesktop:d}=Ne(),[f,m]=u.useState(!1),[h,p]=u.useState(!1),[x,v]=u.useState(!1),[b,y]=u.useState(!1),g=u.useRef(null),S=u.useRef(null),C=u.useRef(null),T=o&&i!==void 0?i===o:f,N=!!(i&&o&&i!==o),_=u.useCallback(()=>{C.current&&(clearTimeout(C.current),C.current=null)},[]),k=u.useCallback(()=>{_(),v(!0)},[_]),w=u.useCallback(()=>{_(),b||(C.current=setTimeout(()=>{v(!1)},350))},[_,b]),$=u.useCallback(H=>{H.stopPropagation(),_(),y(L=>!L),v(L=>!L)},[_]),I=u.useCallback(()=>{b||(_(),v(!1))},[b,_]),j=u.useCallback(()=>{_(),m(!1),v(!1),y(!1),o&&l&&l(o,!1)},[o,l,_]),D=u.useCallback(()=>{var H;if(T)j();else{_();const L=(H=S.current)==null?void 0:H.getBoundingClientRect(),U=L?window.innerHeight-L.bottom:300;p(U<240),m(!0),v(!1),y(!1),o&&l&&l(o,!0)}},[T,j,o,l,_]);return u.useEffect(()=>()=>{_()},[_]),u.useEffect(()=>{if(!T)return;const H=U=>{const G=U.target;g.current&&!g.current.contains(G)&&S.current&&!S.current.contains(G)&&j()},L=U=>{var G;U.key==="Escape"&&(j(),(G=S.current)==null||G.focus())};return document.addEventListener("mousedown",H),document.addEventListener("keydown",L),()=>{document.removeEventListener("mousedown",H),document.removeEventListener("keydown",L)}},[T,j]),!c||!d?null:t?n.jsx("div",{className:`${xe.starterContainer} ${r||""}`.trim(),children:n.jsxs("button",{type:"button",className:xe.starterButton,onClick:()=>e("section"),children:[n.jsx("span",{className:xe.plusIcon,children:n.jsx(Lc,{})}),n.jsx("span",{children:a})]})}):n.jsxs("div",{className:`${xe.addBarGutter} ${T?xe.addBarActive:""} ${N?xe.addBarSuppressed:""} ${r||""}`.trim(),role:"region","aria-label":"Insert element",children:[n.jsx("div",{className:xe.hoverGuideLine,"aria-hidden":"true"}),n.jsxs("button",{ref:S,type:"button",className:xe.addPillButton,onClick:D,"aria-expanded":T,"aria-haspopup":"menu",children:[n.jsx("span",{className:xe.plusIcon,children:n.jsx(Lc,{})}),n.jsx("span",{children:"Add Element"})]}),T&&n.jsx("div",{ref:g,role:"menu","aria-label":"Add Element Palette",className:`${xe.paletteMenu} ${h?xe.dropupMenu:xe.dropdownMenu}`,children:tj.map(H=>{const L=H.IconComponent;return H.type==="photo"?n.jsxs("div",{className:xe.paletteOptionWrapper,onMouseEnter:k,onMouseLeave:w,children:[n.jsxs("button",{role:"menuitem",type:"button",className:`${xe.paletteOption} ${x?xe.paletteOptionActive:""}`.trim(),onClick:$,"aria-haspopup":"menu","aria-expanded":x,children:[n.jsx("span",{className:xe.paletteIcon,"aria-hidden":"true",children:n.jsx(L,{})}),n.jsx("span",{children:H.label}),n.jsx("span",{className:xe.chevronIcon,"aria-hidden":"true",children:n.jsx(QN,{})})]}),x&&n.jsxs("div",{role:"menu","aria-label":"Photo Element Options",className:`${xe.subMenu} ${h?xe.dropupSubMenu:""}`,onMouseEnter:k,onMouseLeave:w,children:[n.jsxs("button",{role:"menuitem",type:"button",className:xe.subOption,onClick:()=>{e("photo"),j()},children:[n.jsx("span",{className:xe.subOptionIcon,"aria-hidden":"true",children:n.jsx(qu,{})}),n.jsx("span",{children:"Single Photo"})]}),n.jsxs("button",{role:"menuitem",type:"button",className:xe.subOption,onClick:()=>{e("gallery"),j()},children:[n.jsx("span",{className:xe.subOptionIcon,"aria-hidden":"true",children:n.jsx(ZN,{})}),n.jsx("span",{children:"Photo Gallery"})]})]})]},H.type):n.jsxs("button",{role:"menuitem",type:"button",className:xe.paletteOption,onMouseEnter:I,onClick:()=>{e(H.type),j()},children:[n.jsx("span",{className:xe.paletteIcon,"aria-hidden":"true",children:n.jsx(L,{})}),n.jsx("span",{children:H.label})]},H.type)})})]})});qt.displayName="CanvasAddBar";function nj(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 Xi=u.memo(({isOpen:e,itemType:t,hasChildren:s=!1,onClose:r,onConfirm:a})=>{const{title:o,noun:i}=nj(t);return n.jsx(ut,{isOpen:e,onClose:r,onConfirm:a,role:"alertdialog",ariaLabel:o,title:o,maxWidth:440,children:n.jsxs("div",{className:xe.modalBody,children:[n.jsxs("p",{className:xe.modalMessage,children:["Are you sure you want to delete this ",i,"?"]}),s&&n.jsxs("p",{className:xe.modalWarning,children:["Warning: Everything inside this ",i," will also be deleted."]}),n.jsxs("div",{className:xe.modalActions,children:[n.jsx(he,{variant:"ghost",size:"sm",onClick:r,children:"Cancel"}),n.jsx(he,{variant:"admin",size:"sm",onClick:a,className:xe.modalDeleteButton,children:"Delete"})]})]})})});Xi.displayName="CanvasDeleteConfirmModal";const cs=u.memo(({itemId:e,itemType:t,canMoveUp:s,canMoveDown:r,onMoveUp:a,onMoveDown:o,onDelete:i,onEdit:l,children:c,className:d,suppressHover:f=!1,sourceParentId:m,sourceIndex:h,hasChildren:p=!1,onDropItem:x})=>{const{isDevMode:v,isDesktop:b}=Ne(),y=u.useRef(null),[g,S]=u.useState(!1),[C,T]=u.useState(!1),[N,_]=u.useState(!1),k=u.useCallback(()=>{S(!1),i()},[i]);if(!v||!b)return n.jsx(n.Fragment,{children:c});const w=z=>{z.stopPropagation(),T(!0),z.dataTransfer.setData("application/json",JSON.stringify({itemId:e,itemType:t,sourceParentId:m,sourceIndex:h})),z.dataTransfer.effectAllowed="move"},$=()=>{T(!1),_(!1)},I=z=>{x&&(z.preventDefault(),z.stopPropagation(),z.dataTransfer.dropEffect="move",N||_(!0))},j=z=>{z.stopPropagation(),_(!1)},D=z=>{if(x){z.preventDefault(),z.stopPropagation(),_(!1);try{const q=z.dataTransfer.getData("application/json");if(q){const P=JSON.parse(q);P.itemId&&P.itemId!==e&&x(P.itemId,m||e,h)}}catch{}}},H=z=>{z.stopPropagation(),S(!0)},L=z=>{z.stopPropagation(),l&&l()},U=t==="section"?`${xe.itemControlsFloatingBar} ${xe.sectionFloatingBar}`:xe.itemControlsFloatingBar,G=f||g;return n.jsxs(n.Fragment,{children:[n.jsxs("div",{ref:y,className:`${xe.itemControlsWrapper} ${G?xe.suppressHover:""} ${N?xe.dropTargetHighlight:""} ${C?xe.isDragging:""} ${d||""}`.trim(),"data-canvas-item-id":e,"data-canvas-item-type":t,onDragOver:I,onDragLeave:j,onDrop:D,children:[n.jsxs("div",{className:U,role:"toolbar","aria-label":"Item authoring controls",children:[n.jsx("span",{className:xe.dragHandle,title:"Drag to reorder","aria-label":"Drag to reorder",draggable:!0,onDragStart:w,onDragEnd:$,role:"button",tabIndex:0,children:"⋮⋮"}),n.jsx("button",{type:"button",className:xe.controlButton,onClick:z=>{z.stopPropagation(),a()},disabled:!s,title:s?"Move Up":"First element in canvas — cannot move up further","aria-label":"Move Up",children:"↑"}),n.jsx("button",{type:"button",className:xe.controlButton,onClick:z=>{z.stopPropagation(),o()},disabled:!r,title:r?"Move Down":"Last element in canvas — cannot move down further","aria-label":"Move Down",children:"↓"}),n.jsx("button",{type:"button",className:`${xe.controlButton} ${xe.editButton}`,onClick:L,title:"Edit","aria-label":"Edit",children:n.jsxs("svg",{className:xe.editIcon,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[n.jsx("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),n.jsx("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]})}),n.jsx("button",{type:"button",className:`${xe.controlButton} ${xe.deleteButton}`,onClick:H,title:"Delete","aria-label":"Delete",children:n.jsxs("svg",{className:xe.deleteIcon,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[n.jsx("polyline",{points:"3 6 5 6 21 6"}),n.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"}),n.jsx("line",{x1:"10",y1:"11",x2:"10",y2:"17"}),n.jsx("line",{x1:"14",y1:"11",x2:"14",y2:"17"})]})})]}),c]}),g&&n.jsx(Xi,{isOpen:g,itemType:t,hasChildren:p,onClose:()=>S(!1),onConfirm:k})]})});cs.displayName="CanvasItemControls";function sj(e){let t=1;const s={};for(const r of e)r.isNumbered?(s[r.id]=String(t).padStart(2,"0"),t++):s[r.id]=null;return s}function rj(e,t){const{isDevMode:s}=Ne(),[r,a]=u.useState(0);return u.useEffect(()=>qo(o=>{const i=o==null?void 0:o.key;(!i||i==="*"||typeof i=="string"&&i.includes(".isNumbered"))&&a(l=>l+1)},s),[s]),u.useMemo(()=>{const o=t.map(i=>{const c=`${i.titlePointId||`node.${e}.section.${i.id}.title`}.isNumbered`,d=hn(c,"",s),f=i.isNumbered!==void 0?i.isNumbered:i.number!==void 0&&i.number!==null,m=d!==""?d==="true":f;return{id:i.id,isNumbered:m}});return sj(o)},[e,t,r,s])}function Mc(e,t,s,r,a,o){switch(e.type){case"text":return n.jsx(Bi,{element:e,nodeId:t,accentColor:r,onEdit:o?()=>o(e):void 0});case"photo":return n.jsx(Gi,{element:e,nodeId:t,accentColor:r,onEdit:a?()=>a(e):void 0});case"gallery":return n.jsx(zi,{element:e,nodeId:t,accentColor:r});case"chart":return n.jsx(Yi,{element:e,nodeId:t,nodeTitle:s,accentColor:r});default:return null}}const Ji=u.memo(({nodeId:e,nodeTitle:t,accentColor:s,className:r})=>{const{isDevMode:a,isDesktop:o}=Ne(),i=a&&o,{document:l,addElement:c,restoreSection:d,restoreSubsection:f,restoreElement:m,moveItem:h,relocateItem:p,removeItem:x,updateItem:v,saveError:b,clearSaveError:y}=Mi(e),g=rj(e,l.sections),[S,C]=u.useState(null),[T,N]=u.useState(!1),[_,k]=u.useState(null),[w,$]=u.useState(null),[I,j]=u.useState(null),D=u.useCallback((M,K)=>{k(K?M:null)},[]),H=u.useCallback((M,K)=>{C({type:"section",section:M,index:K}),x(M.id),N(!0)},[x]),L=u.useCallback((M,K,Q)=>{C({type:"subsection",subsection:K,sectionId:M,index:Q}),x(K.id,M),N(!0)},[x]),U=u.useCallback((M,K,Q,X)=>{C({type:"leaf",leaf:K,sectionId:M,subsectionId:X,index:Q}),x(K.id,X||M),N(!0)},[x]),G=u.useCallback(()=>{S&&(S.type==="section"&&S.section?d(S.section,S.index):S.type==="subsection"&&S.subsection&&S.sectionId?f(S.sectionId,S.subsection,S.index):S.type==="leaf"&&S.leaf&&S.sectionId&&m(S.sectionId,S.leaf,S.index,S.subsectionId),C(null),N(!1))},[S,d,f,m]),z=u.useCallback((M,K,Q,X)=>{if(M==="chart"){const ee="chart-"+e+"-"+Dt("chart");j({isOpen:!0,mode:"add",chartId:ee,targetSectionId:K,targetIndex:Q,targetSubsectionId:X});return}$({isOpen:!0,mode:"add",elementType:M,targetSectionId:K,targetIndex:Q,targetSubsectionId:X})},[e]),q=u.useCallback(M=>{const K=M.titlePointId||`node.${e}.section.${M.id}.title`;$({isOpen:!0,mode:"edit",elementType:"section",itemId:M.id,pointId:K,initialData:{title:M.title,isNumbered:M.isNumbered!==!1}})},[e]),P=u.useCallback(M=>{const K=M.titlePointId||`node.${e}.subsection.${M.id}.title`;$({isOpen:!0,mode:"edit",elementType:"subsection",itemId:M.id,pointId:K,initialData:{title:M.title}})},[e]),F=u.useCallback(M=>{$({isOpen:!0,mode:"edit",elementType:"photo",itemId:M.id,pointId:M.pointId,initialData:{src:M.src,alt:M.alt,caption:M.caption,driveUrl:M.driveUrl}})},[]),R=u.useCallback(M=>{if(M.type==="chart"){j({isOpen:!0,mode:"edit",chartId:M.chartId});return}if(M.type==="photo"){F(M);return}let K={},Q;M.type==="text"?(Q=M.pointId,K={content:M.content,as:M.as||"p"}):M.type==="gallery"&&(Q=M.pointId||M.titlePointId,K={title:M.title||"",driveUrl:M.driveUrl||""}),$({isOpen:!0,mode:"edit",elementType:M.type,itemId:M.id,pointId:Q,initialData:K})},[F]),W=u.useCallback((M,K,Q,X,ee)=>{var J,Y,te,oe,B,E,O,ie,ce;if(M==="section"){const de=Dt("section"),ae=`node.${e}.section.${de}.title`,fe=K.isNumbered!==!1,be={id:de,type:"section",title:((J=K.title)==null?void 0:J.trim())||"Section",titlePointId:ae,isNumbered:fe,elements:[]};if(Q){const ve=l.sections.findIndex(Pe=>Pe.id===Q);if(ve!==-1){d(be,ve+1);return}}d(be,X);return}if(M==="subsection"){const de=Dt("subsection"),ae=`node.${e}.subsection.${de}.title`,fe={id:de,type:"subsection",title:((Y=K.title)==null?void 0:Y.trim())||"Subsection",titlePointId:ae,elements:[]};if(Q)f(Q,fe,X);else if(l.sections.length>0){const be=typeof X=="number"&&X===0?l.sections[0]:l.sections[Math.min((X??1)-1,l.sections.length-1)];f(be.id,fe)}else{const be=Dt("section"),ve={id:be,type:"section",title:"Section 1",titlePointId:`node.${e}.section.${be}.title`,isNumbered:!0,elements:[fe]};d(ve,0)}return}let V;if(M==="text"){const de=Dt("text"),ae=`node.${e}.text.${de}`;V={id:de,type:"text",pointId:ae,content:((te=K.content)==null?void 0:te.trim())||"",as:K.as||"p"}}else if(M==="photo"){const de=Dt("photo"),ae=`node.${e}.photo.${de}`;V={id:de,type:"photo",pointId:ae,src:((oe=K.src)==null?void 0:oe.trim())||void 0,alt:((B=K.alt)==null?void 0:B.trim())||void 0,caption:((E=K.caption)==null?void 0:E.trim())||void 0,driveUrl:((O=K.driveUrl)==null?void 0:O.trim())||void 0}}else{const de=Dt("gallery"),ae=`node.${e}.gallery.${de}.title`;V={id:de,type:"gallery",pointId:`node.${e}.gallery.${de}`,title:((ie=K.title)==null?void 0:ie.trim())||void 0,titlePointId:ae,driveUrl:((ce=K.driveUrl)==null?void 0:ce.trim())||void 0}}if(Q)c(Q,V,X,ee);else if(l.sections.length===0){const de=yo(0,e);de.elements.push(V),d(de,0)}else{const de=typeof X=="number"&&X===0?l.sections[0]:l.sections[Math.min((X??1)-1,l.sections.length-1)],ae=typeof X=="number"&&X===0?0:void 0;c(de.id,V,ae)}},[e,l.sections,d,f,c]),se=u.useCallback(M=>{var Y,te,oe,B,E,O,ie,ce,de;if(!w)return;const{mode:K,elementType:Q,itemId:X,targetSectionId:ee,targetIndex:V,targetSubsectionId:J}=w;if(K==="add"){W(Q,M,ee,V,J),$(null);return}Q==="section"&&X?v(X,{title:(Y=M.title)==null?void 0:Y.trim(),isNumbered:M.isNumbered!==!1}):Q==="subsection"&&X?v(X,{title:(te=M.title)==null?void 0:te.trim()}):Q==="text"&&X?v(X,{content:(oe=M.content)==null?void 0:oe.trim(),as:M.as||"p"}):Q==="photo"&&X?v(X,{src:((B=M.src)==null?void 0:B.trim())||void 0,alt:((E=M.alt)==null?void 0:E.trim())||void 0,caption:((O=M.caption)==null?void 0:O.trim())||void 0,driveUrl:((ie=M.driveUrl)==null?void 0:ie.trim())||void 0}):Q==="gallery"&&X&&v(X,{title:((ce=M.title)==null?void 0:ce.trim())||void 0,driveUrl:((de=M.driveUrl)==null?void 0:de.trim())||void 0}),$(null)},[w,v,W]),re=u.useCallback(()=>{$(null)},[]),le=u.useCallback((M,K,Q)=>{p(M,K,Q)},[p]);return l.sections.length===0&&!i?null:n.jsxs("div",{className:r,style:{opacity:1,transition:"opacity var(--duration-normal) var(--ease-out)"},children:[l.sections.length===0?n.jsx(qt,{isInitialStarter:!0,barId:"starter-bar",activeBarId:_,onToggleActive:D,onAddElement:()=>z("section"),label:"Click to add the first Section",accentColor:s}):n.jsxs(n.Fragment,{children:[i&&n.jsx(qt,{barId:"top-bar",activeBarId:_,onToggleActive:D,onAddElement:M=>z(M,void 0,0),accentColor:s}),l.sections.map((M,K)=>{const Q=K>0,X=K<l.sections.length-1,ee=g[M.id];return n.jsx(u.Fragment,{children:n.jsx(cs,{itemId:M.id,itemType:"section",canMoveUp:Q,canMoveDown:X,onMoveUp:()=>h(M.id,"up"),onMoveDown:()=>h(M.id,"down"),onDelete:()=>H(M,K),onEdit:()=>q(M),suppressHover:!!_,sourceParentId:e,sourceIndex:K,hasChildren:M.elements.length>0,onDropItem:le,children:n.jsxs(Di,{section:M,nodeId:e,nodeTitle:t,accentColor:s,computedNumber:ee,onEdit:()=>q(M),children:[i&&(M.elements||[]).length===0&&n.jsx(qt,{barId:`sec-top-${M.id}`,activeBarId:_,onToggleActive:D,onAddElement:V=>z(V,M.id,0),accentColor:s}),(M.elements||[]).filter(V=>!!(V&&V.id&&V.type)).map((V,J,Y)=>{const te=!(K===0&&J===0),oe=!(K===l.sections.length-1&&J===Y.length-1);if(V.type==="subsection"){const B=(V.elements||[]).filter(E=>!!(E&&E.id&&E.type));return n.jsxs(u.Fragment,{children:[n.jsx(cs,{itemId:V.id,itemType:"subsection",canMoveUp:te,canMoveDown:oe,onMoveUp:()=>h(V.id,"up",M.id),onMoveDown:()=>h(V.id,"down",M.id),onDelete:()=>L(M.id,V,J),onEdit:()=>P(V),suppressHover:!!_,sourceParentId:M.id,sourceIndex:J,hasChildren:B.length>0,onDropItem:le,children:n.jsxs(Ri,{subsection:V,nodeId:e,accentColor:s,onEdit:()=>P(V),children:[i&&B.length===0&&n.jsx(qt,{barId:`sub-top-${V.id}`,activeBarId:_,onToggleActive:D,onAddElement:E=>z(E,M.id,0,V.id),accentColor:s}),B.map((E,O)=>{const ie=!(K===0&&J===0&&O===0),ce=!(K===l.sections.length-1&&J===Y.length-1&&O===B.length-1);return n.jsxs(u.Fragment,{children:[n.jsx(cs,{itemId:E.id,itemType:E.type,canMoveUp:ie,canMoveDown:ce,onMoveUp:()=>h(E.id,"up",V.id),onMoveDown:()=>h(E.id,"down",V.id),onDelete:()=>U(M.id,E,O,V.id),onEdit:()=>R(E),suppressHover:!!_,sourceParentId:V.id,sourceIndex:O,onDropItem:le,children:Mc(E,e,t,s,F,R)}),i&&n.jsx(qt,{barId:`leaf-${E.id}`,activeBarId:_,onToggleActive:D,onAddElement:de=>z(de,M.id,O+1,V.id),accentColor:s})]},E.id)})]})}),i&&n.jsx(qt,{barId:`sub-${V.id}`,activeBarId:_,onToggleActive:D,onAddElement:E=>z(E,M.id,J+1),accentColor:s})]},V.id)}return n.jsxs(u.Fragment,{children:[n.jsx(cs,{itemId:V.id,itemType:V.type,canMoveUp:te,canMoveDown:oe,onMoveUp:()=>h(V.id,"up",M.id),onMoveDown:()=>h(V.id,"down",M.id),onDelete:()=>U(M.id,V,J),onEdit:()=>R(V),suppressHover:!!_,sourceParentId:M.id,sourceIndex:J,onDropItem:le,children:Mc(V,e,t,s,F,R)}),i&&n.jsx(qt,{barId:`direct-leaf-${V.id}`,activeBarId:_,onToggleActive:D,onAddElement:B=>z(B,M.id,J+1),accentColor:s})]},V.id)})]})})},M.id)})]}),T&&n.jsx(Ot,{message:"Item deleted",type:"info",durationMs:5e3,actionLabel:"Undo",onAction:G,onDismiss:()=>{N(!1),C(null)}}),b&&n.jsx(Ot,{message:b,type:"error",durationMs:4e3,onDismiss:y}),n.jsx(An,{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:()=>$(null),onSubmit:se,onResetToDefault:re}),I&&n.jsx(Wi,{isOpen:I.isOpen,mode:I.mode,chartId:I.chartId,nodeId:e,onClose:()=>j(null),onDeployed:M=>{if(I.mode==="add"){const K={id:Dt("chart"),type:"chart",chartId:I.chartId,title:M.titleOverride||"Indicator Chart",subtitle:M.subtitleOverride};if(I.targetSectionId)c(I.targetSectionId,K,I.targetIndex,I.targetSubsectionId);else if(l.sections.length===0){const Q=yo(0,e);Q.elements.push(K),d(Q,0)}else{const Q=typeof I.targetIndex=="number"&&I.targetIndex===0?l.sections[0]:l.sections[Math.min((I.targetIndex??1)-1,l.sections.length-1)],X=typeof I.targetIndex=="number"&&I.targetIndex===0?0:void 0;c(Q.id,K,X)}}j(null)}})]})});Ji.displayName="DocumentCanvas";const aj="_notFoundWrapper_4997g_12",oj="_errorCode_4997g_26",ij="_title_4997g_35",lj="_description_4997g_45",cj="_returnButton_4997g_54",dj="_returnIcon_4997g_79",Zn={notFoundWrapper:aj,errorCode:oj,title:ij,description:lj,returnButton:cj,returnIcon:dj},uj=({onReturn:e,title:t="Pathway Uncharted in Registry",description:s="The requested resource or document view could not be located in this registry.",errorCode:r="[HTTP 404 · ROUTE UNRESOLVED]",returnLabel:a="Return to Overview",className:o})=>n.jsxs("main",{className:`${Zn.notFoundWrapper} ${o||""}`.trim(),role:"main",children:[n.jsx(gt,{pointId:"notFound.errorCode",defaultText:r,as:"div",className:Zn.errorCode}),n.jsx(gt,{pointId:"notFound.title",defaultText:t,as:"h1",className:Zn.title}),n.jsx(gt,{pointId:"notFound.description",defaultText:s,as:"p",className:Zn.description}),e&&n.jsxs("button",{type:"button",className:Zn.returnButton,onClick:e,children:[n.jsx("svg",{className:Zn.returnIcon,viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:n.jsx("path",{d:"M10 13L5 8l5-5"})}),n.jsx(gt,{pointId:"notFound.returnButton",defaultText:a,as:"span",inline:!0})]})]}),hj=["access","equity","quality","resiliency","governance"],Bo={access:1,equity:2,quality:3,resiliency:4,governance:5},mj={1:"access",2:"equity",3:"quality",4:"resiliency",5:"governance"};function ds(e="/",t="",s,r){let a=e.trim().replace(/\/+$/,"")+"/";const o=t.replace(/^#\/?/,"").trim(),i=r??me.getEngineConfig().basePath;if(i){const m=i.trim().replace(/^\/+/,"").replace(/\/+$/,"");m&&a.startsWith("/"+m+"/")&&(a=a.slice(m.length+1))}const l=a.match(/^\/(node|page)\/([a-zA-Z0-9_-]+)\/?$/);if(l){const m=l[2].toLowerCase();if(s?s.includes(m):!0){const p=m;let x=Bo[p]??null;if(x===null){const v=me.getEngineConfig().nodes;if(v&&v.length>0){const b=v.findIndex(y=>y.id.toLowerCase()===m);b!==-1&&(x=b+1)}}return{type:"node",nodeId:p,pageId:p,targetStage:x,rawHash:t,pathname:"/node/"+p+"/"}}return{type:"not-found",nodeId:null,pageId:null,targetStage:null,rawHash:t,pathname:a}}if(o.startsWith("node/")||o.startsWith("page/")){const m=o.startsWith("node/")?"node/":"page/",h=o.slice(m.length).replace(/\/$/,"").toLowerCase();if(s?s.includes(h):!0){const x=h;return{type:"node",nodeId:x,pageId:x,targetStage:Bo[x]??null,rawHash:t,pathname:"/node/"+x+"/"}}return{type:"not-found",nodeId:null,pageId:null,targetStage:null,rawHash:t,pathname:a}}const c=o.match(/^stage-(\d+)$/);return c?{type:"home",nodeId:null,pageId:null,targetStage:parseInt(c[1],10),rawHash:t,pathname:"/"}:(a==="/"||a==="/index.html/")&&(!o||o==="home"||o==="main-content"||o==="roadmap"||o==="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:a}}function fj(e,t){return ds(typeof window<"u"?window.location.pathname:"/",e,t)}function Zi(e,t){const s=t??me.getEngineConfig().basePath,[r,a]=u.useState(()=>ds(typeof window<"u"?window.location.pathname:"/",typeof window<"u"?window.location.hash:"",e,s));u.useEffect(()=>{if(typeof window<"u"){const c=window.location.hash.replace(/^#\/?/,"").trim();if(c.startsWith("node/")||c.startsWith("page/")){const d=c.startsWith("node/")?"node/":"page/",f=c.slice(d.length).replace(/\/$/,"").toLowerCase();if(e?e.includes(f):!0){const h=s?"/"+s.replace(/^\/+|\/+$/g,""):"";window.history.replaceState(null,"",h+"/node/"+f+"/")}}}const l=()=>{a(ds(window.location.pathname,window.location.hash,e,s))};return window.addEventListener("popstate",l),window.addEventListener("hashchange",l),()=>{window.removeEventListener("popstate",l),window.removeEventListener("hashchange",l)}},[e,s]);const o=u.useCallback(l=>{ma();const d=(s?"/"+s.replace(/^\/+|\/+$/g,""):"")+"/node/"+l+"/";typeof window<"u"&&(window.location.pathname!==d&&window.history.pushState(null,"",d),window.scrollTo({top:0,left:0,behavior:"instant"}),a(ds(window.location.pathname,window.location.hash,e,s)))},[e,s]),i=u.useCallback(l=>{ma();const c=s?"/"+s.replace(/^\/+|\/+$/g,""):"",d=l&&l>=1?c+"/#stage-"+l:c||"/";typeof window<"u"&&(window.history.pushState(null,"",d),l||window.scrollTo({top:0,left:0,behavior:"instant"}),a(ds(window.location.pathname,window.location.hash,e,s)))},[e,s]);return{route:r.type,nodeId:r.nodeId,pageId:r.pageId,targetStage:r.targetStage,rawHash:r.rawHash,pathname:r.pathname,navigateToNode:o,navigateToPage:o,navigateToHome:i}}const pj=Zi,gj=35,vj=45,xj=180;function bj({enabled:e,activeStage:t,scrollZone:s,onNextStage:r,onPrevStage:a,onScrollToTop:o,onScrollToFooter:i,onDirectStage:l,cooldownMs:c=200}){const d=u.useRef(!1),f=u.useRef(null),m=u.useRef(0),h=u.useRef(null),p=u.useRef(0),x=u.useRef(0),v=u.useRef(!1),b=u.useRef(t);b.current=t;const y=u.useRef(s);y.current=s;const g=u.useRef({onNextStage:r,onPrevStage:a,onScrollToTop:o,onScrollToFooter:i,onDirectStage:l});g.current={onNextStage:r,onPrevStage:a,onScrollToTop:o,onScrollToFooter:i,onDirectStage:l};const S=u.useCallback((_=1200)=>{d.current=!0,f.current&&clearTimeout(f.current),f.current=setTimeout(()=>{d.current=!1,f.current=null},_+c)},[c]),C=u.useCallback(()=>{f.current&&(clearTimeout(f.current),f.current=null),f.current=setTimeout(()=>{d.current=!1,f.current=null},c)},[c]),T=u.useCallback(()=>{if(d.current)return;S();const _=y.current,k=b.current;_==="above"?g.current.onDirectStage(1):_==="inside"&&(k<5?g.current.onNextStage():g.current.onScrollToFooter())},[S]),N=u.useCallback(()=>{if(d.current)return;S();const _=y.current,k=b.current;_==="below"?g.current.onDirectStage(5):_==="inside"&&(k>1?g.current.onPrevStage():g.current.onScrollToTop())},[S]);return u.useEffect(()=>{if(!e||typeof window>"u")return;const _=document.documentElement,k=document.body;_.classList.add("landing-scroll-locked"),k.classList.add("landing-scroll-locked");const w=L=>!L||!(L instanceof HTMLElement)?!1:L.tagName==="INPUT"||L.tagName==="TEXTAREA"||L.tagName==="SELECT"||L.isContentEditable,$=L=>{if(!w(L.target)){if(L.preventDefault(),d.current){m.current=0;return}if(m.current+=L.deltaY,h.current&&clearTimeout(h.current),h.current=setTimeout(()=>{m.current=0},xj),Math.abs(m.current)>=gj){const U=m.current;m.current=0,U>0?T():N()}}},I=L=>{w(L.target)||L.touches.length===1&&(p.current=L.touches[0].clientY,x.current=L.touches[0].clientX,v.current=!0)},j=L=>{w(L.target)||L.preventDefault()},D=L=>{if(!v.current||(v.current=!1,d.current)||L.changedTouches.length===0)return;const U=p.current-L.changedTouches[0].clientY,G=x.current-L.changedTouches[0].clientX;Math.abs(U)>Math.abs(G)&&Math.abs(U)>=vj&&(U>0?T():N())},H=L=>{if(!w(L.target)){if(L.key==="ArrowDown"||L.key==="PageDown"||L.key==="ArrowRight")L.preventDefault(),T();else if(L.key==="ArrowUp"||L.key==="PageUp"||L.key==="ArrowLeft")L.preventDefault(),N();else if(L.key==="Home")L.preventDefault(),d.current||(S(),g.current.onScrollToTop());else if(L.key==="End")L.preventDefault(),d.current||(S(),g.current.onScrollToFooter());else if(["1","2","3","4","5"].includes(L.key)){L.preventDefault();const U=parseInt(L.key,10);d.current||(S(),g.current.onDirectStage(U))}}};return window.addEventListener("wheel",$,{passive:!1}),window.addEventListener("touchstart",I,{passive:!0}),window.addEventListener("touchmove",j,{passive:!1}),window.addEventListener("touchend",D,{passive:!0}),window.addEventListener("keydown",H,{passive:!1}),()=>{_.classList.remove("landing-scroll-locked"),k.classList.remove("landing-scroll-locked"),window.removeEventListener("wheel",$),window.removeEventListener("touchstart",I),window.removeEventListener("touchmove",j),window.removeEventListener("touchend",D),window.removeEventListener("keydown",H),f.current&&(clearTimeout(f.current),f.current=null),h.current&&(clearTimeout(h.current),h.current=null)}},[e,T,N,S]),{isTransitioning:d.current,lockTransition:S,unlockTransition:C}}function Vu(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(s=>s.charAt(0).toUpperCase()+s.slice(1).toLowerCase()).join(" ")}function yj(e,t='section[id], [data-toc-title][id], [data-toc="true"][id]',s=Vu){var i,l,c;const r=Array.from(e.querySelectorAll(t)),a=new Set,o=[];for(const d of r){const f=(i=d.id)==null?void 0:i.trim();if(!f||a.has(f))continue;a.add(f);const m=d.getAttribute("data-toc-title")||d.getAttribute("data-title"),h=d.getAttribute("aria-label"),p=d.querySelector('h1, h2, h3, [class*="sectionTitle"], [class*="SectionTitle"]'),x=(l=p==null?void 0:p.textContent)==null?void 0:l.trim(),v=m||h||x||s(f),b=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 y;if(!b){const g=d.getAttribute("data-toc-number")||d.getAttribute("data-number"),S=d.querySelector('[class*="sectionNumber"], [class*="SectionNumber"]'),C=(c=S==null?void 0:S.textContent)==null?void 0:c.replace(/^Section\s*/i,"").trim();y=g&&g!=="false"?g:C||void 0}o.push({id:f,label:v,number:y,href:`#${f}`})}return o}function _j(e={}){const{containerId:t="node-content",containerRef:s,sectionSelector:r,formatIdToTitle:a=Vu}=e,[o,i]=u.useState([]),l=u.useRef(null);return u.useEffect(()=>{if(typeof window>"u")return;const c=()=>s!=null&&s.current?s.current:t?document.getElementById(t):null,d=()=>{const p=c();if(!p){i([]);return}const x=yj(p,r,a);i(v=>v.length===x.length&&v.every((b,y)=>b.id===x[y].id&&b.label===x[y].label&&b.number===x[y].number&&b.href===x[y].href)?v:x)},f=()=>{l.current===null&&(l.current=requestAnimationFrame(()=>{d(),l.current=null}))};d();const m=c();if(!m){f();return}const h=new MutationObserver(()=>{f()});return h.observe(m,{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"]}),()=>{h.disconnect(),l.current!==null&&(cancelAnimationFrame(l.current),l.current=null)}},[t,s,r,a]),o}const wj=JSON.parse('[{"id":"access","index":0,"nodeNumber":1,"title":"Project Initiation","subtitle":"Discovery, Scoping & Baseline Requirements","summary":"Establishing foundational project parameters, stakeholder alignment, and baseline operational requirements.","tagline":"Stage 01 · Initial Phase","accentColor":"#0284c7","accentTint":"#e0f2fe","heroImage":{"src":"https://images.unsplash.com/photo-1451187580459-43490279c0fa?w=1200&q=80&auto=format&fit=crop","alt":"Abstract network graph illustrating project baseline parameters","caption":"Baseline project scoping and preliminary operational requirements.","showCaption":true},"annotation":"Stage 01 outlines initial project parameters and documentation.","stages":[{"step":1,"stageName":"Current Assessment","narrative":"Evaluating existing operational workflows and establishing initial baseline metrics."},{"step":2,"stageName":"Requirements Definition","narrative":"Defining core project requirements, functional criteria, and resource allocation targets."},{"step":3,"stageName":"Process Alignment","narrative":"Standardizing task execution plans, administrative schedules, and procedural guidelines."},{"step":4,"stageName":"Milestone Deliverables","narrative":"Fulfilling initial milestone criteria and verifying procedural compliance documentation."},{"step":5,"stageName":"Stakeholder Review","narrative":"Providing routine progress updates and operational status briefings to project leads."}],"sourceItems":[{"id":"src-acc-01","title":"Project Scoping & Charter Brief","dateStamp":"2026-01-15","photo":{"src":"https://images.unsplash.com/photo-1504639725590-34d0984388bd?w=800&q=80","alt":"Standard project documentation and technical briefing","caption":"Baseline project scoping and preliminary operational documentation.","showCaption":false},"imageSrc":"https://images.unsplash.com/photo-1504639725590-34d0984388bd?w=800&q=80","reference":"Operational Briefing Doc 101"},{"id":"src-acc-02","title":"Resource Allocation Matrix","dateStamp":"2026-02-10","photo":{"src":"https://images.unsplash.com/photo-1551288049-bebda4e38f71?w=800&q=80","alt":"Resource allocation matrix and schedule table","caption":"Resource allocation matrix and procedural benchmarks.","showCaption":false},"imageSrc":"https://images.unsplash.com/photo-1551288049-bebda4e38f71?w=800&q=80","reference":"Planning Document Ref 204"}],"metadata":{"category":"planning","stability":"stable","version":"1.0.0"}},{"id":"equity","index":1,"nodeNumber":2,"title":"System Planning","subtitle":"Functional Analysis & Workflow Specification","summary":"Detailed analysis of operational workflows, data specifications, and departmental integration criteria.","tagline":"Stage 02 · Analysis Phase","accentColor":"#881337","accentTint":"#ffe4e6","heroImage":{"src":"https://images.unsplash.com/photo-1518770660439-4636190af475?w=1200&q=80&auto=format&fit=crop","alt":"System schematics and workflow architecture diagram","caption":"Workflow mapping and procedural specification review.","showCaption":true},"annotation":"Stage 02 defines procedural workflows and operational specifications.","stages":[{"step":1,"stageName":"Workflow Review","narrative":"Assessing current task sequences and identifying operational dependencies across units."},{"step":2,"stageName":"Specification Mapping","narrative":"Documenting detailed functional criteria and outlining operational boundaries."},{"step":3,"stageName":"Standardization","narrative":"Establishing uniform reporting templates and administrative operating guidelines."},{"step":4,"stageName":"Review Checkpoints","narrative":"Confirming alignment between planned workflows and overall operational criteria."},{"step":5,"stageName":"Team Coordination","narrative":"Sharing documented specifications and coordinating task schedules across departments."}],"sourceItems":[{"id":"src-eq-01","title":"Functional Specifications Sheet","dateStamp":"2026-03-01","photo":{"src":"https://images.unsplash.com/photo-1581291518857-4e27b48ff24e?w=800&q=80","alt":"Functional specifications checklist and procedural audit","caption":"Procedural verification across functional components.","showCaption":false},"imageSrc":"https://images.unsplash.com/photo-1581291518857-4e27b48ff24e?w=800&q=80","reference":"System Specification Document 2026-A"}],"metadata":{"category":"analysis","stability":"active","version":"1.0.0"}},{"id":"quality","index":2,"nodeNumber":3,"title":"Execution & Implementation","subtitle":"Scheduled Deliverables & Core Execution","summary":"Carrying out scheduled milestones, core task execution, and standard operational activities.","tagline":"Stage 03 · Execution Phase","accentColor":"#f59e0b","accentTint":"#fef3c7","heroImage":{"src":"https://images.unsplash.com/photo-1460925895917-afdab827c52f?w=1200&q=80&auto=format&fit=crop","alt":"Operational dashboard displaying routine project metrics","caption":"Implementation phase tracking scheduled deliverables and operational metrics.","showCaption":true},"annotation":"Stage 03 focuses on active implementation and milestone delivery.","stages":[{"step":1,"stageName":"Task Scheduling","narrative":"Organizing active work streams and allocating resources according to the schedule."},{"step":2,"stageName":"Activity Rollout","narrative":"Executing routine operational tasks and tracking day-to-day project milestones."},{"step":3,"stageName":"Progress Monitoring","narrative":"Maintaining central task logs and recording progress against defined benchmarks."},{"step":4,"stageName":"Deliverable Verification","narrative":"Verifying completed work items against established criteria and output requirements."},{"step":5,"stageName":"Operational Reporting","narrative":"Compiling regular progress reports and updating central project tracking tools."}],"sourceItems":[{"id":"src-qual-01","title":"Milestone Delivery Record","dateStamp":"2026-03-20","photo":{"src":"https://images.unsplash.com/photo-1551836022-d5d88e9218df?w=800&q=80","alt":"Operational milestone progress tracking chart","caption":"Delivery verification records across core work streams.","showCaption":false},"imageSrc":"https://images.unsplash.com/photo-1551836022-d5d88e9218df?w=800&q=80","reference":"Delivery Status Report Q1"}],"metadata":{"category":"execution","stability":"active","version":"1.0.0"}},{"id":"resiliency","index":3,"nodeNumber":4,"title":"Testing & Quality Assurance","subtitle":"Operational Verification & Compliance Checks","summary":"Conducting systematic quality assurance checks, compliance audits, and procedural evaluations.","tagline":"Stage 04 · Review Phase","accentColor":"#15803d","accentTint":"#dcfce7","heroImage":{"src":"https://images.unsplash.com/photo-1526374965328-7f61d4dc18c5?w=1200&q=80&auto=format&fit=crop","alt":"Quality assurance testing logs and review data","caption":"Systematic verification procedures ensuring procedural quality and compliance.","showCaption":true},"annotation":"Stage 04 ensures procedural consistency and operational quality.","stages":[{"step":1,"stageName":"Quality Review","narrative":"Reviewing completed deliverables against established operational guidelines."},{"step":2,"stageName":"Compliance Check","narrative":"Verifying procedural compliance with standard organizational requirements."},{"step":3,"stageName":"Remediation Procedures","narrative":"Addressing identified feedback and refining procedural workflows accordingly."},{"step":4,"stageName":"Verification Sign-Off","narrative":"Confirming full compliance and signing off on verified milestone requirements."},{"step":5,"stageName":"Documentation Filing","narrative":"Archiving verification checklists and filing quarterly quality audit summaries."}],"sourceItems":[{"id":"src-res-01","title":"Quality Audit Checklist","dateStamp":"2026-04-05","photo":{"src":"https://images.unsplash.com/photo-1544197150-b99a580bb7a8?w=800&q=80","alt":"Quality audit records and verification checklist","caption":"Audit summary records and verification checklist data.","showCaption":false},"imageSrc":"https://images.unsplash.com/photo-1544197150-b99a580bb7a8?w=800&q=80","reference":"Audit Summary Log QA-44"}],"metadata":{"category":"verification","stability":"active","version":"1.0.0"}},{"id":"governance","index":4,"nodeNumber":5,"title":"Operations & Maintenance","subtitle":"Routine Administration & Lifecycle Management","summary":"Managing ongoing operations, regular maintenance schedules, and long-term administrative reporting.","tagline":"Stage 05 · Maintenance Phase","accentColor":"#d97706","accentTint":"#ffedd5","heroImage":{"src":"https://images.unsplash.com/photo-1507679799987-c73779587ccf?w=1200&q=80&auto=format&fit=crop","alt":"Administrative office workspace representing routine operations","caption":"Ongoing administration and routine maintenance operations.","showCaption":true},"annotation":"Stage 05 coordinates ongoing administrative processes and routine oversight.","stages":[{"step":1,"stageName":"Operational Handover","narrative":"Transitioning completed project components into routine administrative management."},{"step":2,"stageName":"Maintenance Scheduling","narrative":"Establishing recurring service calendars and standard upkeep procedures."},{"step":3,"stageName":"Performance Tracking","narrative":"Monitoring ongoing operational metrics and tracking periodic indicators."},{"step":4,"stageName":"Administrative Oversight","narrative":"Maintaining central documentation and reviewing operational logs periodically."},{"step":5,"stageName":"Lifecycle Reporting","narrative":"Providing periodic administrative summaries and ongoing lifecycle updates."}],"sourceItems":[{"id":"src-gov-01","title":"Administrative Operations Log","dateStamp":"2026-04-18","photo":{"src":"https://images.unsplash.com/photo-1563986768609-322da13575f3?w=800&q=80","alt":"Administrative documentation and operational log UI","caption":"Periodic operational review records and maintenance logs.","showCaption":false},"imageSrc":"https://images.unsplash.com/photo-1563986768609-322da13575f3?w=800&q=80","reference":"Operations Manual Standard 2026"}],"metadata":{"category":"operations","stability":"active","version":"1.0.0"}}]'),Sj="_header_1k4ie_8",Cj="_kicker_1k4ie_15",kj="_kickerDot_1k4ie_27",Nj="_title_1k4ie_34",jj="_subtitle_1k4ie_44",Tj="_pinContainer_1k4ie_53",Ij="_nativeHiddenInput_1k4ie_63",Aj="_slotsRow_1k4ie_78",Ej="_pinSlot_1k4ie_85",$j="_pinSlotFilled_1k4ie_98",Lj="_pinSlotActive_1k4ie_103",Mj="_pinSlotDisabled_1k4ie_109",Dj="_pinDot_1k4ie_115",Rj="_pinCaret_1k4ie_124",Bj="_shake_1k4ie_152",Pj="_statusBox_1k4ie_157",Oj="_statusText_1k4ie_165",Fj="_errorText_1k4ie_173",Uj="_lockoutText_1k4ie_178",Gj="_verifyingText_1k4ie_184",Hj="_successText_1k4ie_189",zj="_actions_1k4ie_195",Ee={header:Sj,kicker:Cj,kickerDot:kj,title:Nj,subtitle:jj,pinContainer:Tj,nativeHiddenInput:Ij,slotsRow:Aj,pinSlot:Ej,pinSlotFilled:$j,pinSlotActive:Lj,pinSlotDisabled:Mj,pinDot:Dj,pinCaret:Rj,shake:Bj,statusBox:Pj,statusText:Oj,errorText:Fj,lockoutText:Uj,verifyingText:Gj,successText:Hj,actions:zj},Wu=()=>{const{isPinModalOpen:e,pinState:t,attemptsRemaining:s,lockoutRemainingSeconds:r,isRenewal:a,closePinModal:o,submitPin:i}=Ne(),[l,c]=u.useState(""),[d,f]=u.useState(!1),[m,h]=u.useState(!1),p=u.useRef(null),x=t==="locked_out"||r>0,v=t==="verifying";u.useEffect(()=>{var C;if(e&&(c(""),h(!1),!x)){(C=p.current)==null||C.focus();const T=requestAnimationFrame(()=>{var _;(_=p.current)==null||_.focus()}),N=setTimeout(()=>{var _;(_=p.current)==null||_.focus()},30);return()=>{cancelAnimationFrame(T),clearTimeout(N)}}},[e,x]),u.useEffect(()=>{if(t==="error"){h(!0);const C=setTimeout(()=>{var T;h(!1),c(""),(T=p.current)==null||T.focus()},450);return()=>clearTimeout(C)}},[t]);const b=u.useCallback(C=>{if(x||v)return;const T=C.target.value.replace(/\D/g,"").slice(0,4);c(T),T.length===4&&i(T)},[x,v,i]),y=u.useCallback(C=>{C.key==="Enter"&&l.length===4&&!x&&!v&&(C.preventDefault(),i(l))},[l,x,v,i]),g=u.useCallback(()=>{l.length===4&&!x&&!v&&i(l)},[l,x,v,i]),S=C=>{const T=Math.floor(C/60),N=C%60;return`${T}:${N<10?"0":""}${N}`};return n.jsxs(ut,{isOpen:e,onClose:o,initialFocusRef:p,onConfirm:g,maxWidth:"440px",ariaLabelledBy:"dev-pin-title",ariaDescribedBy:"dev-pin-desc",children:[n.jsxs("div",{className:Ee.header,children:[n.jsxs("div",{className:Ee.kicker,children:[n.jsx("span",{className:Ee.kickerDot,"aria-hidden":"true"}),n.jsx("span",{children:a?"Session Renewal":"Developer Access"})]}),n.jsx("h2",{id:"dev-pin-title",className:Ee.title,children:a?"Renew Developer Session":"Developer Authentication"}),n.jsx("p",{id:"dev-pin-desc",className:Ee.subtitle,children:a?"Enter PIN to renew session.":"Enter 4-digit PIN."})]}),n.jsxs("div",{className:`${Ee.pinContainer} ${m?Ee.shake:""}`,onClick:()=>{var C;!x&&!v&&((C=p.current)==null||C.focus())},children:[n.jsx("input",{ref:p,type:"password",inputMode:"numeric",pattern:"[0-9]*",maxLength:4,value:l,onChange:b,onKeyDown:y,onFocus:()=>f(!0),onBlur:()=>f(!1),disabled:x||v,className:Ee.nativeHiddenInput,autoComplete:"off","data-autofocus":!0,"aria-label":"4-digit Developer PIN"}),n.jsx("div",{className:Ee.slotsRow,"aria-hidden":"true",children:[0,1,2,3].map(C=>{const T=!!l[C],N=d&&!x&&!v&&(l.length===C||l.length===4&&C===3);return n.jsx("div",{className:`
5
+ ${Ee.pinSlot}
6
+ ${T?Ee.pinSlotFilled:""}
7
+ ${N?Ee.pinSlotActive:""}
8
+ ${x||v?Ee.pinSlotDisabled:""}
9
+ `,children:T?n.jsx("span",{className:Ee.pinDot}):N?n.jsx("span",{className:Ee.pinCaret}):null},C)})})]}),n.jsx("div",{className:Ee.statusBox,children:x?n.jsxs("p",{className:`${Ee.statusText} ${Ee.lockoutText}`,children:["Too many failed attempts. Please wait ",S(r)]}):v?n.jsx("p",{className:`${Ee.statusText} ${Ee.verifyingText}`,children:"Verifying..."}):t==="error"?n.jsxs("p",{className:`${Ee.statusText} ${Ee.errorText}`,children:["Incorrect PIN. ",s," ",s===1?"attempt":"attempts"," remaining."]}):t==="success"?n.jsx("p",{className:`${Ee.statusText} ${Ee.successText}`,children:"Authenticated."}):s<5?n.jsxs("p",{className:Ee.statusText,children:[s," attempts remaining."]}):null}),n.jsx("div",{className:Ee.actions,children:n.jsx(he,{variant:"secondary",size:"sm",type:"button",onClick:o,children:"Cancel"})})]})},qj="_container_10oun_12",Vj="_subtitle_10oun_20",Wj="_timelineList_10oun_29",Kj="_emptyState_10oun_36",Yj="_historyList_10oun_47",Xj="_historyItem_10oun_56",Jj="_itemMain_10oun_79",Zj="_itemTitleRow_10oun_87",Qj="_itemTitle_10oun_87",eT="_itemMeta_10oun_103",tT="_metaInterval_10oun_113",nT="_metaDot_10oun_125",sT="_metaTimestamp_10oun_131",rT="_itemAction_10oun_138",aT="_confirmModalContent_10oun_146",oT="_confirmHeader_10oun_153",iT="_confirmTitle_10oun_159",lT="_confirmDesc_10oun_169",cT="_confirmNotice_10oun_177",dT="_confirmActions_10oun_185",Ie={container:qj,subtitle:Vj,timelineList:Wj,emptyState:Kj,historyList:Yj,historyItem:Xj,itemMain:Jj,itemTitleRow:Zj,itemTitle:Qj,itemMeta:eT,metaInterval:tT,metaDot:nT,metaTimestamp:sT,itemAction:rT,confirmModalContent:aT,confirmHeader:oT,confirmTitle:iT,confirmDesc:lT,confirmNotice:cT,confirmActions:dT};function sr(e){return e?e.replace(/\s*\([^)]*\)/g,"").trim():""}function uT(e){try{const t=new Date(e).getTime();if(Number.isNaN(t))return"Recently";const s=Date.now(),r=Math.max(0,s-t),a=Math.floor(r/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 hT(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 Dc(e){if(e.id==="snap-system-baseline"||!!(e.title&&e.title.toLowerCase().includes("baseline")))return sr(e.title)||"System Baseline";const s="description"in e&&e.description?e.description:"notes"in e&&e.notes?e.notes:"",r=sr(s);if(r)return r;const a=sr(e.title);return a&&!a.toLowerCase().includes("published revision")&&!a.toLowerCase().includes("published version")?a:"Revision"}const Ku=u.memo(({snapshot:e,isCurrentLive:t,onRequestRestore:s})=>{const r=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=sr(a),i=sr(e.title);let l="";return r?l=i||"System Baseline":o?l=o:l=i&&!i.toLowerCase().includes("published revision")&&!i.toLowerCase().includes("published version")?i:"Revision",n.jsxs("li",{className:Ie.historyItem,children:[n.jsxs("div",{className:Ie.itemMain,children:[n.jsxs("div",{className:Ie.itemTitleRow,children:[n.jsx("span",{className:Ie.itemTitle,children:l}),t?n.jsx(or,{label:"Live",variant:"primary",size:"sm"}):null]}),n.jsxs("div",{className:Ie.itemMeta,children:[n.jsx("span",{className:Ie.metaInterval,children:uT(e.createdAt)}),n.jsx("span",{className:Ie.metaDot,"aria-hidden":"true",children:"•"}),n.jsx("time",{className:Ie.metaTimestamp,dateTime:e.createdAt,children:hT(e.createdAt)})]})]}),!t&&n.jsx("div",{className:Ie.itemAction,children:n.jsx(he,{variant:"secondary",size:"sm",type:"button",onClick:()=>s(e),"aria-label":`Restore "${l}" to Draft`,children:"Load as Draft"})})]})});Ku.displayName="HistoryTimelineRow";const mT=({isOpen:e,onClose:t,onRestored:s})=>{const[r,a]=u.useState([]),[o,i]=u.useState(null),[l,c]=u.useState(!1),[d,f]=u.useState(null),[m,h]=u.useState("success"),[p,x]=u.useState(null),[v,b]=u.useState(!1),y=u.useCallback(async()=>{c(!0);try{await ri().catch(()=>{});const T=await Ad();if(T.length>0){a(T);const N=T.find(_=>_.isActive);i(N?N.id:Yt())}else{const N=dn();a(N);const _=N.find(k=>k.isActive);i(_?_.id:Yt())}}catch{const T=dn();a(T);const N=T.find(_=>_.isActive);i(N?N.id:Yt())}finally{c(!1)}},[]);u.useEffect(()=>e?(y(),Id(()=>{y()})):void 0,[e,y]);const g=u.useCallback(T=>{x(T)},[]),S=u.useCallback(()=>{if(!p)return;const T=p;x(null);const N=Co(T),_=Dc(T);N?(s==null||s(_),t()):(f("Failed to restore draft."),h("error"))},[p,s,t]),C=u.useCallback(()=>{b(!1);const T=Pa(!1);Co(T)?(s==null||s("System Baseline"),t()):(f("Failed to restore default baseline."),h("error"))},[s,t]);return e?n.jsxs(n.Fragment,{children:[n.jsx(Vi,{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:n.jsx(he,{variant:"ghost",size:"sm",type:"button",onClick:()=>b(!0),title:"Restore workspace back to official factory default baseline",children:"Restore to default"}),footerRight:n.jsx(he,{variant:"secondary",size:"sm",type:"button",onClick:t,children:"Close"}),children:n.jsxs("div",{className:Ie.container,children:[n.jsx("p",{id:"history-drawer-desc",className:Ie.subtitle,children:"Revision history and published configurations."}),n.jsx("div",{className:Ie.timelineList,children:l&&r.length===0?n.jsx("div",{className:Ie.emptyState,children:"Loading history..."}):r.length===0?n.jsx("div",{className:Ie.emptyState,children:"No saved configurations yet."}):n.jsx("ul",{className:Ie.historyList,children:r.map(T=>n.jsx(Ku,{snapshot:T,isCurrentLive:o?T.id===o:!!("isActive"in T&&T.isActive),onRequestRestore:g},T.id))})})]})}),p&&n.jsx(ut,{isOpen:!!p,onClose:()=>x(null),maxWidth:460,role:"alertdialog",ariaLabelledBy:"preview-confirm-title",ariaDescribedBy:"preview-confirm-desc",children:n.jsxs("div",{className:Ie.confirmModalContent,children:[n.jsxs("div",{className:Ie.confirmHeader,children:[n.jsx("h3",{id:"preview-confirm-title",className:Ie.confirmTitle,children:"Load as Draft?"}),n.jsxs("p",{id:"preview-confirm-desc",className:Ie.confirmDesc,children:["Are you sure you want to load"," ",n.jsxs("strong",{children:['"',Dc(p),'"']})," into your Developer Mode draft to preview and edit?"]}),n.jsx("p",{className:Ie.confirmNotice,children:"Your live public portal will remain unchanged until you review and publish."})]}),n.jsxs("div",{className:Ie.confirmActions,children:[n.jsx(he,{variant:"ghost",size:"sm",type:"button",onClick:()=>x(null),children:"Cancel"}),n.jsx(he,{variant:"primary",size:"sm",type:"button",onClick:S,children:"Load as Draft"})]})]})}),v&&n.jsx(ut,{isOpen:v,onClose:()=>b(!1),maxWidth:460,role:"alertdialog",ariaLabelledBy:"restore-default-title",ariaDescribedBy:"restore-default-desc",children:n.jsxs("div",{className:Ie.confirmModalContent,children:[n.jsxs("div",{className:Ie.confirmHeader,children:[n.jsx("h3",{id:"restore-default-title",className:Ie.confirmTitle,children:"Restore System Baseline?"}),n.jsx("p",{id:"restore-default-desc",className:Ie.confirmDesc,children:"Are you sure you want to reset your Developer Mode draft back to the official baseline?"}),n.jsx("p",{className:Ie.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."})]}),n.jsxs("div",{className:Ie.confirmActions,children:[n.jsx(he,{variant:"ghost",size:"sm",type:"button",onClick:()=>b(!1),children:"Cancel"}),n.jsx(he,{variant:"primary",size:"sm",type:"button",onClick:C,children:"Restore Baseline"})]})]})}),d?n.jsx(Ot,{message:d,type:m,onDismiss:()=>f(null)}):null]}):null},Yu=mT,fT="_form_11pme_7",pT="_fieldGroup_11pme_14",gT="_textarea_11pme_19",vT="_footer_11pme_46",xT="_meta_11pme_53",bT="_shortcutHint_11pme_59",yT="_kbd_11pme_64",_T="_charCounter_11pme_81",wT="_charCounterLimit_11pme_87",ST="_error_11pme_92",CT="_actions_11pme_102",kT="_staleContent_11pme_118",NT="_staleMessage_11pme_124",jT="_btnDanger_11pme_132",tt={form:fT,fieldGroup:pT,textarea:gT,footer:vT,meta:xT,shortcutHint:bT,kbd:yT,charCounter:_T,charCounterLimit:wT,error:ST,actions:CT,staleContent:kT,staleMessage:NT,btnDanger:jT},Qi=({isOpen:e,onClose:t,onPublished:s})=>{const[r,a]=u.useState(""),[o,i]=u.useState(!1),[l,c]=u.useState(null),[d,f]=u.useState(!1);if(u.useEffect(()=>{e||(a(""),i(!1),c(null),f(!1))},[e]),!e)return null;const m=kr();if(m.isStale&&!d)return n.jsx(ut,{isOpen:e,onClose:o?()=>{}:t,closeOnEscape:!o,title:"Published Version Changed",maxWidth:"440px",role:"dialog",children:n.jsxs("div",{className:tt.staleContent,children:[n.jsxs("p",{className:tt.staleMessage,children:["A newer snapshot (",m.currentActiveId,") was published by another session. Publishing now will overwrite it."]}),n.jsxs("div",{className:tt.actions,children:[n.jsx(he,{variant:"secondary",size:"sm",type:"button",onClick:()=>{Xo(),t()},children:"Discard Draft"}),n.jsx(he,{variant:"primary",size:"sm",type:"button",className:tt.btnDanger,onClick:()=>f(!0),children:"Publish Anyway"})]})]})});const h=r.trim(),p=h.length>3,x=async y=>{if(y&&y.preventDefault(),!(!p||o)){i(!0),c(null);try{const g=await $d(h,void 0,void 0,{forcePublish:!0});g.success?(s==null||s(g.snapshot,g.cloudSynced),t()):c(g.error||"Failed to publish version.")}catch{c("Unexpected error during publishing.")}finally{i(!1)}}},v=y=>{if(y.key==="Escape"&&o){y.preventDefault();return}(y.metaKey||y.ctrlKey)&&y.key==="Enter"&&(y.preventDefault(),p&&!o&&x())},b=typeof navigator<"u"&&(/Mac|iPod|iPhone|iPad/.test(navigator.platform)||/Macintosh|MacIntel|MacPPC|Mac68K/.test(navigator.userAgent));return n.jsx(ut,{isOpen:e,onClose:o?()=>{}:t,closeOnEscape:!o,title:"Publish Changes",maxWidth:"440px",role:"dialog",children:n.jsxs("form",{className:tt.form,onSubmit:x,children:[n.jsx("div",{className:tt.fieldGroup,children:n.jsx("textarea",{id:"publish-changelog",className:tt.textarea,placeholder:"What changed in this version?",value:r,onChange:y=>a(y.target.value),onKeyDown:v,rows:3,maxLength:400,autoFocus:!0,disabled:o,"aria-label":"Describe what changed in this version",required:!0})}),l&&n.jsx("p",{className:tt.error,role:"alert",children:l}),n.jsxs("div",{className:tt.footer,children:[n.jsxs("div",{className:tt.meta,children:[n.jsx("span",{className:tt.shortcutHint,title:b?"Press ⌘+Enter to publish":"Press Ctrl+Enter to publish","aria-label":b?"Press Command plus Enter to publish":"Press Control plus Enter to publish",children:n.jsx("kbd",{className:tt.kbd,children:b?"⌘↵":"Ctrl+↵"})}),h.length>0&&h.length<4&&n.jsx("span",{className:tt.charCounter,"aria-live":"polite",children:"Min 4 characters"}),r.length>=300&&n.jsxs("span",{className:`${tt.charCounter} ${r.length>=400?tt.charCounterLimit:""}`,"aria-live":"polite",children:[r.length,"/400"]})]}),n.jsxs("div",{className:tt.actions,children:[n.jsx(he,{variant:"secondary",size:"sm",type:"button",onClick:t,disabled:o,children:"Cancel"}),n.jsx(he,{variant:"primary",size:"sm",type:"submit",disabled:!p||o,children:o?"Publishing...":"Publish"})]})]})]})})},TT="_floatingCapsule_4z54a_8",IT="_statusPill_4z54a_31",AT="_statusIcon_4z54a_45",ET="_statusTitle_4z54a_55",$T="_sessionTime_4z54a_62",LT="_cloudSyncIndicator_4z54a_70",MT="_actionButton_4z54a_79",DT="_buttonDisabled_4z54a_124",RT="_actionIcon_4z54a_130",BT="_actionLabel_4z54a_149",Be={floatingCapsule:TT,statusPill:IT,statusIcon:AT,statusTitle:ET,sessionTime:$T,cloudSyncIndicator:LT,actionButton:MT,buttonDisabled:DT,actionIcon:RT,actionLabel:BT},PT=({className:e})=>n.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:[n.jsx("polyline",{points:"16 16 12 12 8 16"}),n.jsx("line",{x1:"12",y1:"12",x2:"12",y2:"21"}),n.jsx("path",{d:"M20.39 18.39A5 5 0 0 0 18 9h-1.26A8 8 0 1 0 3 16.3"})]}),OT=({className:e})=>n.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:n.jsx("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"})}),FT=({className:e})=>n.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:[n.jsx("polyline",{points:"1 4 1 10 7 10"}),n.jsx("path",{d:"M3.51 15a9 9 0 1 0 2.13-9.36L1 10"})]}),UT=({className:e})=>n.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:[n.jsx("polyline",{points:"23 4 23 10 17 10"}),n.jsx("path",{d:"M20.49 15a9 9 0 1 1-2.12-9.36L23 10"})]}),GT=({className:e})=>n.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:[n.jsx("circle",{cx:"12",cy:"12",r:"10"}),n.jsx("polyline",{points:"12 6 12 12 16 14"})]}),HT=({className:e})=>n.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:[n.jsx("path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"}),n.jsx("polyline",{points:"16 17 21 12 16 7"}),n.jsx("line",{x1:"21",y1:"12",x2:"9",y2:"12"})]}),Xu=()=>{const{isDevMode:e,isDesktop:t,sessionRemainingMinutes:s,requestExitDevMode:r,cloudSyncStatus:a}=Ne(),{canUndo:o,canRedo:i,lastActionDescription:l,nextRedoDescription:c,undo:d,redo:f}=Ir(),[m,h]=u.useState(!1),[p,x]=u.useState(!1),[v,b]=u.useState(null),[y,g]=u.useState("success");if(!e||!t)return null;const S=typeof navigator<"u"&&/Mac|iPod|iPhone|iPad/.test(navigator.platform),C=S?"⌘Z":"Ctrl+Z",T=S?"⇧⌘Z":"Ctrl+Shift+Z",N=o?l?`Undo: ${l} (${C})`:`Undo (${C})`:`Undo (${C})`,_=i?c?`Redo: ${c} (${T})`:`Redo (${T})`:`Redo (${T})`;return n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:Be.floatingCapsule,role:"status","aria-live":"polite","aria-label":"Developer mode is active",children:[n.jsxs("div",{className:Be.statusPill,children:[n.jsx(OT,{className:Be.statusIcon}),n.jsxs("span",{className:Be.statusTitle,children:["Dev Mode",n.jsx(Pn,{text:"Lets you edit the page. Changes are saved as a private draft until you publish.",label:"Dev Mode"})]}),n.jsxs("span",{className:Be.sessionTime,title:`${s} minutes remaining in session`,children:[s,"m left"]}),a&&n.jsx("span",{className:Be.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":""})]}),n.jsxs("button",{type:"button",className:`${Be.actionButton} ${o?"":Be.buttonDisabled}`,onClick:k=>{k.preventDefault(),k.stopPropagation(),o&&d()},disabled:!o,"aria-label":"Undo last change",title:N,children:[n.jsx(FT,{className:Be.actionIcon}),n.jsx("span",{className:Be.actionLabel,children:"Undo"})]}),n.jsxs("button",{type:"button",className:`${Be.actionButton} ${i?"":Be.buttonDisabled}`,onClick:k=>{k.preventDefault(),k.stopPropagation(),i&&f()},disabled:!i,"aria-label":"Redo last change",title:_,children:[n.jsx(UT,{className:Be.actionIcon}),n.jsx("span",{className:Be.actionLabel,children:"Redo"})]}),n.jsxs("button",{type:"button",className:Be.actionButton,onClick:k=>{k.preventDefault(),k.stopPropagation(),h(!0)},"aria-label":"Open History",title:"Revision history",children:[n.jsx(GT,{className:Be.actionIcon}),n.jsx("span",{className:Be.actionLabel,children:"History"})]}),n.jsxs("button",{type:"button",className:Be.actionButton,onClick:k=>{k.preventDefault(),k.stopPropagation(),x(!0)},"aria-label":"Publish Changes",title:"Publish changes live to portal",children:[n.jsx(PT,{className:Be.actionIcon}),n.jsx("span",{className:Be.actionLabel,children:"Publish"})]}),n.jsxs("button",{type:"button",className:Be.actionButton,onClick:k=>{k.preventDefault(),k.stopPropagation(),r()},"aria-label":"Exit Developer Mode",children:[n.jsx(HT,{className:Be.actionIcon}),n.jsx("span",{className:Be.actionLabel,children:"Exit"})]})]}),n.jsx(Yu,{isOpen:m,onClose:()=>h(!1),onRestored:k=>{const w=k.replace(/\s*\([^)]*\)/g,"").trim(),$=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.`;b($),g("success")}}),n.jsx(Qi,{isOpen:p,onClose:()=>x(!1),onPublished:(k,w)=>{w===!1?(b("Published locally. Cloud sync pending reconnection."),g("info")):(b("Published changes live to portal."),g("success"))}}),v&&n.jsx(Ot,{message:v,type:y,onDismiss:()=>b(null)})]})},zT="_content_150bw_8",qT="_header_150bw_15",VT="_title_150bw_21",WT="_subtitle_150bw_31",KT="_metaList_150bw_40",YT="_metaItem_150bw_47",XT="_metaLabel_150bw_53",JT="_metaValue_150bw_62",ZT="_metaValueData_150bw_69",QT="_noticeText_150bw_76",e2="_actions_150bw_85",mt={content:zT,header:qT,title:VT,subtitle:WT,metaList:KT,metaItem:YT,metaLabel:XT,metaValue:JT,metaValueData:ZT,noticeText:QT,actions:e2};function t2(e){if(!e)return"Just now";const t=new Date(e).getTime();if(Number.isNaN(t))return"Just now";const s=Math.max(0,Math.floor((Date.now()-t)/1e3));if(s<10)return"Just now";if(s<60)return`${s}s ago`;const r=Math.floor(s/60);if(r===1)return"1 minute ago";if(r<60)return`${r} minutes ago`;const a=Math.floor(r/60);return a===1?"1 hour ago":`${a} hours ago`}const Ju=()=>{const{isLockBlocked:e,activeLockInfo:t,closeLockBlockedModal:s,refreshLockStatus:r}=Ne(),[a,o]=u.useState(10),[i,l]=u.useState(!1);u.useEffect(()=>{if(!e){o(10);return}const f=window.setInterval(()=>{o(m=>m<=1?(r(),10):m-1)},1e3);return()=>clearInterval(f)},[e,r]);const c=u.useCallback(async()=>{l(!0);try{await r(),o(10)}finally{l(!1)}},[r]);if(!e)return null;const d=t2(t==null?void 0:t.lockedAt);return n.jsx(ut,{isOpen:e,onClose:s,onConfirm:i?void 0:c,maxWidth:"480px",ariaLabelledBy:"dev-lock-title",ariaDescribedBy:"dev-lock-desc",children:n.jsxs("div",{className:mt.content,children:[n.jsxs("div",{className:mt.header,children:[n.jsx("h2",{id:"dev-lock-title",className:mt.title,children:"Developer Mode is active elsewhere"}),n.jsx("p",{id:"dev-lock-desc",className:mt.subtitle,children:"Another user is currently editing."})]}),n.jsxs("div",{className:mt.metaList,children:[n.jsxs("div",{className:mt.metaItem,children:[n.jsx("span",{className:mt.metaLabel,children:"Started"}),n.jsx("span",{className:mt.metaValue,children:d})]}),n.jsxs("div",{className:mt.metaItem,children:[n.jsx("span",{className:mt.metaLabel,children:"Auto-refresh"}),n.jsxs("span",{className:mt.metaValueData,children:[a,"s"]})]})]}),n.jsx("p",{className:mt.noticeText,children:"Frees automatically after 1 minute of inactivity."}),n.jsxs("div",{className:mt.actions,children:[n.jsx(he,{variant:"secondary",size:"sm",type:"button",onClick:s,children:"Close"}),n.jsx(he,{variant:"primary",size:"sm",type:"button",disabled:i,onClick:c,children:i?"Checking...":"Check Status"})]})]})})},n2="_content_pegda_8",s2="_header_pegda_15",r2="_title_pegda_21",a2="_subtitle_pegda_31",o2="_actions_pegda_40",i2="_destructiveButton_pegda_57",Qn={content:n2,header:s2,title:r2,subtitle:a2,actions:o2,destructiveButton:i2},el=u.memo(()=>{const{isExitConfirmOpen:e,closeExitConfirmModal:t,confirmExitDevMode:s,hasUnpublishedChanges:r}=Ne(),{clearHistory:a}=Ir(),[o,i]=u.useState(!1),l=u.useCallback(()=>{a(),s({discard:!1})},[a,s]),c=u.useCallback(()=>{a(),s({discard:!0})},[a,s]),d=u.useCallback(()=>{t(),i(!0)},[t]),f=u.useCallback(()=>{i(!1),a(),s({discard:!1})},[a,s]);if(!e&&!o)return null;const m=r?"Unpublished Changes":"Exit Developer Mode",h=r?"You have unpublished changes. Drafts will not be kept once you exit.":"Active editing session will end and session history will be cleared.";return n.jsxs(n.Fragment,{children:[e&&n.jsx(ut,{isOpen:e,onClose:t,onConfirm:r?d:c,maxWidth:r?"500px":"420px",role:"alertdialog",ariaLabelledBy:"dev-exit-title",ariaDescribedBy:"dev-exit-desc",children:n.jsxs("div",{className:Qn.content,children:[n.jsxs("div",{className:Qn.header,children:[n.jsx("h2",{id:"dev-exit-title",className:Qn.title,children:m}),n.jsx("p",{id:"dev-exit-desc",className:Qn.subtitle,children:h})]}),n.jsx("div",{className:Qn.actions,children:r?n.jsxs(n.Fragment,{children:[n.jsx(he,{variant:"secondary",size:"sm",type:"button",onClick:t,children:"Keep Editing"}),n.jsx(he,{variant:"secondary",size:"sm",type:"button",className:Qn.destructiveButton,onClick:c,children:"Discard Draft & Exit"}),n.jsx(he,{variant:"primary",size:"sm",type:"button",onClick:d,children:"Publish & Exit"})]}):n.jsxs(n.Fragment,{children:[n.jsx(he,{variant:"secondary",size:"sm",type:"button",onClick:t,children:"Cancel"}),n.jsx(he,{variant:"primary",size:"sm",type:"button",onClick:l,children:"Exit"})]})})]})}),o&&n.jsx(Qi,{isOpen:o,onClose:()=>i(!1),onPublished:f})]})});el.displayName="DevExitConfirmModal";const l2="_appShell_kzbod_13",c2="_mainContent_kzbod_22",d2="_nodePageShell_kzbod_29",u2="_breadcrumbContainer_kzbod_40",h2="_backButton_kzbod_52",m2="_nodeLayout_kzbod_80",f2="_sidebarColumn_kzbod_92",p2="_contentColumn_kzbod_98",g2="_overviewSection_kzbod_105",Ht={appShell:l2,mainContent:c2,nodePageShell:d2,breadcrumbContainer:u2,backButton:h2,nodeLayout:m2,sidebarColumn:f2,contentColumn:p2,overviewSection:g2},v2=wj,x2=[{id:"node-overview",label:"Overview",href:"#node-overview"},{id:"node-canvas",label:"Document Canvas",number:"01",href:"#node-canvas"}],b2=()=>{const e=me.getEngineConfig(),t=e.nodes&&e.nodes.length>0?e.nodes:v2,s=u.useMemo(()=>t.map(R=>R.id),[t]),{route:r,nodeId:a,pageId:o,targetStage:i,navigateToNode:l,navigateToHome:c}=Zi(s,e.basePath),[d,f]=u.useState(1),[m,h]=u.useState("above"),[p,x]=u.useState([]),v=u.useRef(null),b=u.useRef(null),y=a||o,g=y?t.find(R=>R.id===y):null,S=u.useCallback((R,W)=>{f(R),h(W)},[]);u.useEffect(()=>{if(r==="home"&&i){const R=setTimeout(()=>{var W;(W=v.current)==null||W.scrollToStage(i)},50);return()=>clearTimeout(R)}},[r,i]),u.useEffect(()=>{x([])},[r,y]),u.useEffect(()=>{ri().catch(R=>{console.warn("[App] History hydration notice:",R)})},[]);const C=r==="node"||r==="page",T=_j({containerId:"node-content"}),N=u.useMemo(()=>T&&T.length>0?T:p&&p.length>0?p:x2,[T,p]),_=u.useMemo(()=>C?N:r==="home"?m==="above"?[{label:"Roadmap",href:"#sequence-roadmap"}]:[{label:"Overview",href:"#main-content"}]:[],[C,N,r,m]),k=u.useCallback(()=>{ir({top:0,interruptible:!1})},[]),w=u.useCallback(()=>{ir({top:document.documentElement.scrollHeight,interruptible:!1})},[]),$=u.useCallback(R=>{var W;R&&R.preventDefault(),r==="home"?(W=v.current)==null||W.scrollToStage(1):c(1)},[r,c]),I=u.useCallback(R=>{R&&R.preventDefault(),r==="home"?k():c()},[r,c,k]),j=u.useCallback(()=>{var R,W;m==="above"?(R=v.current)==null||R.scrollToStage(1):d<t.length?(W=v.current)==null||W.scrollToStage(d+1):w()},[m,d,w]),D=u.useCallback(()=>{var R,W;m==="below"?(R=v.current)==null||R.scrollToStage(t.length):d>1?(W=v.current)==null||W.scrollToStage(d-1):k()},[m,d,k]);bj({enabled:r==="home",activeStage:d,scrollZone:m,onNextStage:j,onPrevStage:D,onScrollToTop:k,onScrollToFooter:w,onDirectStage:R=>{var W;return(W=v.current)==null?void 0:W.scrollToStage(R)}});const H=u.useMemo(()=>r!=="home"?!1:m!=="above",[r,m]),L=u.useMemo(()=>r!=="home"?!1:m!=="above",[r,m]),U=u.useMemo(()=>m==="below"||d===t.length?"Top":"Next",[m,d]),G=u.useMemo(()=>m==="below"||d===t.length?"up":"down",[m,d]),z=u.useCallback(()=>{m==="below"||d===t.length?k():j()},[m,d,j,k]),q=u.useCallback(R=>{R==null||R.stopPropagation(),D()},[D]),P=u.useCallback(R=>{l(R)},[l]),F=u.useCallback(()=>{if(g){const R=g.nodeNumber??g.index+1;c(R)}else c(1)},[g,c]);return n.jsxs("div",{className:Ht.appShell,children:[n.jsx(Ud,{brandTitle:e.branding.appName||"Folio",brandLetter:e.branding.logoText||"F",navItems:_,mobileOnlyNav:C,onRoadmapClick:$,onOverviewClick:I,onBrandClick:I}),C&&g?n.jsxs("div",{className:Ht.nodePageShell,children:[n.jsxs("div",{className:Ht.breadcrumbContainer,children:[n.jsx(wi,{items:[{label:"Overview",onClick:()=>c()},{label:"Milestones",onClick:()=>c(g.nodeNumber??1)},{label:g.title,isCurrent:!0}]}),n.jsx("button",{type:"button",className:Ht.backButton,onClick:F,"aria-label":"Return to roadmap sequence",children:n.jsx("span",{children:"← Return to Roadmap"})})]}),n.jsxs("div",{className:Ht.nodeLayout,children:[n.jsx("div",{className:Ht.sidebarColumn,children:n.jsx(au,{title:"Contents",items:N,accentColor:g.accentColor,nodeNumber:g.nodeNumber??1,nodeTitle:g.title,onBack:F})}),n.jsxs("main",{id:"node-content",className:Ht.contentColumn,children:[n.jsx("section",{id:"node-overview",className:Ht.overviewSection,"aria-label":"Node Overview",children:n.jsx(Si,{kicker:`Stage 0${g.nodeNumber??1}: ${g.title}`,kickerPointId:`node.${g.id}.kicker`,title:g.subtitle??g.title,titlePointId:`node.${g.id}.title`,subtitle:g.summary,subtitlePointId:`node.${g.id}.subtitle`,accentColor:g.accentColor})}),n.jsx("section",{id:"node-canvas","aria-label":"Dynamic Document Canvas",children:n.jsx(Ji,{nodeId:g.id,nodeTitle:g.title,accentColor:g.accentColor})})]})]}),n.jsx(aa,{orgName:e.branding.orgName||"Folio Engine Open Sequence Architecture",onRoadmapClick:$,onOverviewClick:I,onNodeClick:P})]}):r==="not-found"?n.jsxs(n.Fragment,{children:[n.jsx("div",{style:{paddingTop:"calc(var(--space-8) + 68px)",flex:1},children:n.jsx(uj,{onReturn:()=>c(1)})}),n.jsx(aa,{orgName:e.branding.orgName||"Folio Engine Open Sequence Architecture",onRoadmapClick:$,onOverviewClick:I,onNodeClick:P})]}):n.jsxs(n.Fragment,{children:[n.jsxs("main",{id:"main-content",className:Ht.mainContent,children:[n.jsx(xi,{heroCtaRef:b,onStartJourney:$,kickerText:e.branding.heroKicker,title:e.branding.heroTitle,subtitle:e.branding.heroSubtitle}),n.jsx(_i,{ref:v,nodes:t,onStageChange:S,onExploreNode:P})]}),n.jsx(aa,{orgName:e.branding.orgName||"Folio Engine Open Sequence Architecture",onRoadmapClick:$,onOverviewClick:I,onNodeClick:P}),n.jsx(To,{position:"left",label:"Previous",direction:"up",revolving:!0,pulse:!1,isVisible:L,onClick:q,"aria-label":"Return to the previous milestone"}),n.jsx(To,{position:"right",label:U,direction:G,revolving:!0,isVisible:H,onClick:z})]}),n.jsx(Wu,{}),n.jsx(Ju,{}),n.jsx(el,{}),n.jsx(Xu,{})]})},y2=({config:e})=>(e&&me.setEngineConfig(e),u.useEffect(()=>{},[e]),n.jsx(Fd,{children:n.jsx(Yd,{children:n.jsx(b2,{})})})),_2=e=>{const t=e==null?void 0:e.target,[s,r]=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 g=typeof document<"u"?Math.max(document.documentElement.scrollHeight,document.body.scrollHeight,window.innerHeight):window.innerHeight,S=Math.max(g-window.innerHeight,1),C=Math.min(Math.max(d/S,0),1);return{scrollY:d,scrollProgress:C}}const m=t.current.getBoundingClientRect(),h=m.top+d,p=m.height,x=typeof document<"u"&&document.documentElement.clientHeight||window.innerHeight,v=p-x,b=d-h;if(v<=0)return{scrollY:d,scrollProgress:0};const y=Math.min(Math.max(b/v,0),1);return{scrollY:d,scrollProgress:y}},[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 f=l();i.current=f,a.current.forEach(m=>m(f)),r(f)}))};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]),{...s,subscribeScroll:c}},w2="_cardContainer_dfk33_7",S2="_cardInteractiveTarget_dfk33_21",C2="_imageWrapper_dfk33_41",k2="_heroImage_dfk33_56",Zs={cardContainer:w2,cardInteractiveTarget:S2,imageWrapper:C2,heroImage:k2},N2=({node:e,heroImage:t,onExploreNode:s,className:r,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(p=>{p.stopPropagation(),l?l():e!=null&&e.id&&s&&s(e.id)},[l,s,e==null?void 0:e.id]),f=u.useCallback(p=>{(p.key==="Enter"||p.key===" ")&&(p.preventDefault(),l?l():e!=null&&e.id&&s&&s(e.id))},[l,s,e==null?void 0:e.id]);if(!c.src&&!e)return null;const m=`${i.x}% ${i.y}%`,h=l?`View photograph: ${c.caption||c.alt||(e==null?void 0:e.title)||"Photograph"}`:`Explore ${(e==null?void 0:e.title)||"Node"}`;return n.jsx("div",{className:`${Zs.cardContainer} ${o?Zs.docked:""} ${r||""}`,"data-node-id":e==null?void 0:e.id,children:n.jsx("button",{type:"button",className:Zs.cardInteractiveTarget,onClick:d,onKeyDown:f,"aria-label":h,children:n.jsx("div",{className:Zs.imageWrapper,children:n.jsx("img",{src:c.src,alt:c.alt,loading:a?"eager":"lazy",fetchPriority:a?"high":"auto",className:Zs.heroImage,style:{objectPosition:`var(--card-crop-focal, ${m})`}})})})})},j2="_container_1gczx_12",T2="_panel_1gczx_19",I2="_formField_1gczx_25",A2="_fieldLabel_1gczx_31",E2="_requiredMark_1gczx_40",$2="_input_1gczx_45",L2="_textarea_1gczx_72",M2="_checkboxLabel_1gczx_101",D2="_checkbox_1gczx_101",R2="_segmentedControl_1gczx_148",B2="_segmentButton_1gczx_156",P2="_segmentButtonActive_1gczx_177",O2="_imagePreviewWrapper_1gczx_184",F2="_previewThumb_1gczx_195",U2="_fileRow_1gczx_202",G2="_hiddenFileInput_1gczx_208",H2="_actions_1gczx_212",ue={container:j2,panel:T2,formField:I2,fieldLabel:A2,requiredMark:E2,input:$2,textarea:L2,checkboxLabel:M2,checkbox:D2,segmentedControl:R2,segmentButton:B2,segmentButtonActive:P2,imagePreviewWrapper:O2,previewThumb:F2,fileRow:U2,hiddenFileInput:G2,actions:H2},Zu=({isOpen:e,type:t,nodeId:s,targetSectionId:r,targetIndex:a,targetSubsectionId:o,onClose:i,onConfirmAdd:l})=>{const{showToast:c}=Ne(),[d,f]=u.useState(""),[m,h]=u.useState(!0),[p,x]=u.useState(""),[v,b]=u.useState("p"),[y,g]=u.useState(""),[S,C]=u.useState(""),[T,N]=u.useState(""),[_,k]=u.useState(!1),[w,$]=u.useState(""),[I,j]=u.useState(""),[D,H]=u.useState("upload"),[L,U]=u.useState(!1),[G,z]=u.useState(null),q=u.useRef(null),P=u.useRef(null);u.useEffect(()=>{if(e){f(""),h(!0),x(""),b("p"),g(""),C(""),N(""),k(!1),$(""),j(""),H("upload");const M=setTimeout(()=>{var K;(K=P.current)==null||K.focus()},50);return()=>clearTimeout(M)}},[e,t]);const F=u.useMemo(()=>e?!!(d.trim()||p.trim()||y.trim()||S.trim()||T.trim()||w.trim()||I.trim()):!1,[e,d,p,y,S,T,w,I]);if(Fa(e&&F,"canvas-add-modal"),!e||!t)return null;let R=!1,W="Add Element",se="Add Element";switch(t){case"section":R=d.trim().length>0,W="Add Section",se="Add Section";break;case"subsection":R=d.trim().length>0,W="Add Subsection",se="Add Subsection";break;case"text":R=p.trim().length>0,W="Add Narrative Text",se="Add Text";break;case"photo":R=y.trim().length>0&&S.trim().length>0,W="Add Photo Evidence",se="Add Photo";break;case"gallery":R=d.trim().length>0,W="Add Photo Gallery",se="Add Gallery";break;case"chart":R=d.trim().length>0,W="Add Indicator Chart",se="Add Chart";break}const re=async M=>{var X;const K=(X=M.target.files)==null?void 0:X[0];if(!K)return;const Q=K.name.replace(/\.[^/.]+$/,"");S||C(Q),U(!0),z(null);try{const ee=await ha(K,"photos");g(ee)}catch(ee){console.error("[CanvasAddModal] Photo upload failed:",ee),z(ee instanceof Error?ee.message:"Photo upload failed")}finally{U(!1)}},le=M=>{if(M&&M.preventDefault(),!R)return;const K={title:d.trim(),isNumbered:m,content:p.trim(),as:v,src:y.trim(),alt:S.trim(),caption:T.trim(),showCaption:_,driveUrl:w.trim(),subtitle:I.trim()};l(t,K,r,a,o),c("Element added to canvas.","success"),i()};return n.jsx(ut,{isOpen:e,onClose:i,onConfirm:R&&!L?le:void 0,title:W,maxWidth:"500px",ariaLabel:W,children:n.jsxs("form",{onSubmit:le,className:ue.container,children:[t==="section"&&n.jsxs("div",{className:ue.panel,children:[n.jsxs("div",{className:ue.formField,children:[n.jsxs("label",{className:ue.fieldLabel,htmlFor:"add-section-title",children:["Section Title ",n.jsx("span",{className:ue.requiredMark,children:"*"})]}),n.jsx("input",{ref:M=>{P.current=M},id:"add-section-title",type:"text",className:ue.input,value:d,onChange:M=>f(M.target.value),placeholder:"e.g. Learning Continuity & Remediation",required:!0})]}),n.jsxs("div",{className:ue.formField,children:[n.jsx("label",{className:ue.fieldLabel,children:"Section Numbering"}),n.jsxs("div",{className:ue.segmentedControl,role:"radiogroup","aria-label":"Section Numbering",children:[n.jsx("button",{type:"button",role:"radio","aria-checked":m,className:`${ue.segmentButton} ${m?ue.segmentButtonActive:""}`,onClick:()=>h(!0),children:"Numbered"}),n.jsx("button",{type:"button",role:"radio","aria-checked":!m,className:`${ue.segmentButton} ${m?"":ue.segmentButtonActive}`,onClick:()=>h(!1),children:"Unnumbered"})]})]})]}),t==="subsection"&&n.jsx("div",{className:ue.panel,children:n.jsxs("div",{className:ue.formField,children:[n.jsxs("label",{className:ue.fieldLabel,htmlFor:"add-subsec-title",children:["Subsection Title ",n.jsx("span",{className:ue.requiredMark,children:"*"})]}),n.jsx("input",{ref:M=>{P.current=M},id:"add-subsec-title",type:"text",className:ue.input,value:d,onChange:M=>f(M.target.value),placeholder:"e.g. Grade 7 Catch-Up Fridays & Remediation",required:!0})]})}),t==="text"&&n.jsxs("div",{className:ue.panel,children:[n.jsxs("div",{className:ue.formField,children:[n.jsx("label",{className:ue.fieldLabel,children:"Typography Style"}),n.jsxs("div",{className:ue.segmentedControl,role:"radiogroup","aria-label":"Text Typography Style",children:[n.jsx("button",{type:"button",role:"radio","aria-checked":v==="p",className:`${ue.segmentButton} ${v==="p"?ue.segmentButtonActive:""}`,onClick:()=>b("p"),children:"Body Paragraph"}),n.jsx("button",{type:"button",role:"radio","aria-checked":v==="blockquote",className:`${ue.segmentButton} ${v==="blockquote"?ue.segmentButtonActive:""}`,onClick:()=>b("blockquote"),children:"Editorial Quote"})]})]}),n.jsxs("div",{className:ue.formField,children:[n.jsxs("label",{className:ue.fieldLabel,htmlFor:"add-text-content",children:["Narrative Content ",n.jsx("span",{className:ue.requiredMark,children:"*"})]}),n.jsx("textarea",{ref:M=>{P.current=M},id:"add-text-content",className:ue.textarea,value:p,onChange:M=>x(M.target.value),placeholder:"Type narrative overview, milestone progress, or strategic initiative...",rows:5,required:!0})]})]}),t==="photo"&&n.jsxs("div",{className:ue.panel,children:[y&&n.jsx("div",{className:ue.imagePreviewWrapper,children:n.jsx("img",{src:y,alt:S||"Selected preview",className:ue.previewThumb,onError:M=>{M.target.style.display="none"}})}),n.jsxs("div",{className:ue.formField,children:[n.jsx("span",{className:ue.fieldLabel,children:"Photo Source"}),n.jsxs("div",{className:ue.segmentedControl,role:"radiogroup","aria-label":"Photo Source",children:[n.jsx("button",{type:"button",role:"radio","aria-checked":D==="upload",className:`${ue.segmentButton} ${D==="upload"?ue.segmentButtonActive:""}`,onClick:()=>H("upload"),children:"Upload Photo"}),n.jsx("button",{type:"button",role:"radio","aria-checked":D==="url",className:`${ue.segmentButton} ${D==="url"?ue.segmentButtonActive:""}`,onClick:()=>H("url"),children:"Photo URL"})]})]}),D==="upload"?n.jsxs("div",{className:ue.formField,children:[n.jsxs("span",{className:ue.fieldLabel,children:["Select Photo File ",n.jsx("span",{className:ue.requiredMark,children:"*"})]}),n.jsxs("div",{className:ue.fileRow,children:[n.jsx(he,{type:"button",variant:"secondary",size:"sm",onClick:()=>{var M;return(M=q.current)==null?void 0:M.click()},children:"Upload Photo"}),n.jsx("input",{ref:q,type:"file",accept:"image/*",className:ue.hiddenFileInput,onChange:re,"aria-label":"Upload photo file"}),n.jsx("span",{className:ue.fieldLabel,children:y?"Photo selected":"No photo chosen"})]})]}):n.jsxs("div",{className:ue.formField,children:[n.jsxs("label",{className:ue.fieldLabel,htmlFor:"add-photo-url",children:["Photo URL ",n.jsx("span",{className:ue.requiredMark,children:"*"})]}),n.jsx("input",{id:"add-photo-url",type:"text",className:ue.input,value:y.startsWith("data:")?"":y,onChange:M=>g(M.target.value),placeholder:"https://... or /images/..."})]}),n.jsxs("div",{className:ue.formField,children:[n.jsxs("label",{className:ue.fieldLabel,htmlFor:"add-photo-alt",children:["Alt Text ",n.jsx("span",{className:ue.requiredMark,children:"*"})]}),n.jsx("input",{ref:M=>{P.current||(P.current=M)},id:"add-photo-alt",type:"text",className:ue.input,value:S,onChange:M=>C(M.target.value),placeholder:"Brief visual description for screen readers",required:!0})]}),n.jsxs("label",{className:ue.checkboxLabel,children:[n.jsx("input",{type:"checkbox",className:ue.checkbox,checked:_,onChange:M=>k(M.target.checked)}),n.jsx("span",{children:"Show caption below photo"})]}),_&&n.jsxs("div",{className:ue.formField,children:[n.jsx("label",{className:ue.fieldLabel,htmlFor:"add-photo-caption",children:"Caption"}),n.jsx("input",{id:"add-photo-caption",type:"text",className:ue.input,value:T,onChange:M=>N(M.target.value),placeholder:"Editorial context or story shown beneath photo"})]})]}),t==="gallery"&&n.jsxs("div",{className:ue.panel,children:[n.jsxs("div",{className:ue.formField,children:[n.jsxs("label",{className:ue.fieldLabel,htmlFor:"add-gallery-title",children:["Gallery Title ",n.jsx("span",{className:ue.requiredMark,children:"*"})]}),n.jsx("input",{ref:M=>{P.current=M},id:"add-gallery-title",type:"text",className:ue.input,value:d,onChange:M=>f(M.target.value),placeholder:"e.g. Photo & Activity Evidence Gallery",required:!0})]}),n.jsxs("div",{className:ue.formField,children:[n.jsx("label",{className:ue.fieldLabel,htmlFor:"add-gallery-drive",children:"Google Drive Folder URL (Optional)"}),n.jsx("input",{id:"add-gallery-drive",type:"text",className:ue.input,value:w,onChange:M=>$(M.target.value),placeholder:"https://drive.google.com/drive/folders/..."})]})]}),t==="chart"&&n.jsxs("div",{className:ue.panel,children:[n.jsxs("div",{className:ue.formField,children:[n.jsxs("label",{className:ue.fieldLabel,htmlFor:"add-chart-title",children:["Chart Title ",n.jsx("span",{className:ue.requiredMark,children:"*"})]}),n.jsx("input",{ref:M=>{P.current=M},id:"add-chart-title",type:"text",className:ue.input,value:d,onChange:M=>f(M.target.value),placeholder:"e.g. Learner Mastery by Learning Area",required:!0})]}),n.jsxs("div",{className:ue.formField,children:[n.jsx("label",{className:ue.fieldLabel,htmlFor:"add-chart-subtitle",children:"Subtitle / Description (Optional)"}),n.jsx("input",{id:"add-chart-subtitle",type:"text",className:ue.input,value:I,onChange:M=>j(M.target.value),placeholder:"Quarterly performance against benchmark standard"})]})]}),n.jsxs("div",{className:ue.actions,children:[G&&n.jsx("span",{style:{fontSize:"0.8125rem",color:"var(--color-danger, #e11d48)",marginRight:"auto"},children:G}),n.jsx(he,{type:"button",variant:"ghost",onClick:i,disabled:L,children:"Cancel"}),n.jsx(he,{type:"submit",variant:"primary",disabled:!R||L,children:L?"Uploading...":se})]})]})})};Zu.displayName="CanvasAddModal";const z2="_searchForm_xyd73_2",q2="_searchPill_xyd73_9",V2="_searchIconWrap_xyd73_35",W2="_searchIcon_xyd73_35",K2="_searchInput_xyd73_55",Y2="_clearBtn_xyd73_84",X2="_shortcutKbd_xyd73_107",J2="_searchSubmitBtn_xyd73_127",Z2="_searchSubmitText_xyd73_140",Q2="_searchSubmitBtnBottom_xyd73_145",eI="_arrowIcon_xyd73_156",ft={searchForm:z2,searchPill:q2,searchIconWrap:V2,searchIcon:W2,searchInput:K2,clearBtn:Y2,shortcutKbd:X2,searchSubmitBtn:J2,searchSubmitText:Z2,searchSubmitBtnBottom:Q2,arrowIcon:eI},tI=({placeholder:e="Search nodes, projects, or indicators...",mobilePlaceholder:t="Search",onSearch:s,className:r})=>{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),f=u.useRef(null),m=u.useRef(null);u.useEffect(()=>{const v=window.matchMedia("(max-width: 640px)"),b=y=>{l(y.matches)};return b(v),v.addEventListener("change",b),()=>v.removeEventListener("change",b)},[]),u.useEffect(()=>{const v=b=>{var y;(b.metaKey||b.ctrlKey)&&b.key.toLowerCase()==="k"&&(b.preventDefault(),(y=c.current)==null||y.focus())};return window.addEventListener("keydown",v),()=>window.removeEventListener("keydown",v)},[]);const h=v=>{var b;if(v.key==="Enter"&&!v.nativeEvent.isComposing){v.preventDefault();const g=i||typeof window<"u"&&window.matchMedia("(max-width: 640px)").matches?f.current||d.current:d.current||f.current;g?g.click():(b=m.current)==null||b.requestSubmit()}},p=v=>{if(v.preventDefault(),s)s(a.trim());else{const b=document.getElementById("roadmap");b&&b.scrollIntoView({behavior:"smooth"})}},x=()=>{var v;o(""),(v=c.current)==null||v.focus()};return n.jsxs("form",{ref:m,role:"search",className:`${ft.searchForm} ${r||""}`,onSubmit:p,"aria-label":"Search Plan",children:[n.jsxs("div",{className:ft.searchPill,children:[n.jsx("span",{className:ft.searchIconWrap,"aria-hidden":"true",children:n.jsxs("svg",{className:ft.searchIcon,width:"21",height:"21",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("circle",{cx:"11",cy:"11",r:"8"}),n.jsx("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]})}),n.jsx("input",{ref:c,type:"search",className:ft.searchInput,value:a,onChange:v=>o(v.target.value),onKeyDown:h,placeholder:i?t:e,"aria-label":i?t:e,autoComplete:"off",spellCheck:"false"}),a?n.jsx("button",{type:"button",className:ft.clearBtn,onClick:x,"aria-label":"Clear search input",children:n.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),n.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})}):n.jsx("kbd",{className:ft.shortcutKbd,"aria-hidden":"true",title:"Press ⌘K or Ctrl+K to search",children:"⌘K"}),n.jsxs(he,{ref:d,id:"search-submit-btn",type:"submit",variant:"revolving-outline",outlineWidth:6,className:ft.searchSubmitBtn,"aria-label":"Search",children:[n.jsx("span",{className:ft.searchSubmitText,children:"Search"}),n.jsxs("svg",{className:ft.arrowIcon,width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"}),n.jsx("polyline",{points:"12 5 19 12 12 19"})]})]})]}),n.jsxs(he,{ref:f,id:"search-submit-btn-mobile",type:"submit",variant:"revolving-outline",outlineWidth:6,className:ft.searchSubmitBtnBottom,"aria-label":"Search",children:[n.jsx("span",{className:ft.searchSubmitText,children:"Search"}),n.jsxs("svg",{className:ft.arrowIcon,width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"}),n.jsx("polyline",{points:"12 5 19 12 12 19"})]})]})]})},nI="_editorialSection_bx623_1",sI={editorialSection:nI},Qu=u.memo(({id:e,title:t,number:s,as:r="section",className:a,style:o,children:i})=>{const l=s!=null?typeof s=="number"?String(s).padStart(2,"0"):String(s):void 0;return n.jsx(r,{id:e,"data-toc-title":t,"data-toc-number":l,"aria-label":t,className:`${sI.editorialSection} ${a||""}`,style:o,children:i})});Qu.displayName="EditorialSection";exports.EngineBrandingConfigSchema=me.EngineBrandingConfigSchema;exports.EngineConfigSchema=me.EngineConfigSchema;exports.createDefaultEngineConfig=me.createDefaultEngineConfig;exports.getEngineConfig=me.getEngineConfig;exports.getStorageKey=me.getStorageKey;exports.getStorageNamespace=me.getStorageNamespace;exports.resetEngineConfig=me.resetEngineConfig;exports.runEngineSelfAudit=me.runEngineSelfAudit;exports.setEngineConfig=me.setEngineConfig;exports.validateNodePayload=me.validateNodePayload;exports.verifyEngineWiring=me.verifyEngineWiring;exports.isChartElement=$e.isChartElement;exports.isGalleryElement=$e.isGalleryElement;exports.isLeafElement=$e.isLeafElement;exports.isPhotoElement=$e.isPhotoElement;exports.isSectionElement=$e.isSectionElement;exports.isSubsectionElement=$e.isSubsectionElement;exports.isTextElement=$e.isTextElement;exports.AUTOSAVE_DEBOUNCE_MS=Td;exports.AUTOSYNC_DEBOUNCE_MS=id;exports.AccordionSection=wt;exports.App=y2;exports.AppFooter=aa;exports.AppHeader=Ud;exports.BROADCAST_CHANNEL_NAME=Oh;exports.BarChart=Lu;exports.Breadcrumb=wi;exports.Button=he;exports.CANVAS_DRAFT_STORAGE_PREFIX=Dh;exports.CANVAS_LEGACY_STORAGE_PREFIX=Rh;exports.CANVAS_LIVE_STORAGE_PREFIX=vd;exports.CANVAS_SCHEMA_VERSION=na;exports.CANVAS_STORAGE_PREFIX=Bh;exports.CanvasAddBar=qt;exports.CanvasAddModal=Zu;exports.CanvasChart=Yi;exports.CanvasDeleteConfirmModal=Xi;exports.CanvasGallery=zi;exports.CanvasItemControls=cs;exports.CanvasPhoto=Gi;exports.CanvasSection=Di;exports.CanvasSubsection=Ri;exports.CanvasText=Bi;exports.ChartCard=Ki;exports.ChartConfigDrawer=Wi;exports.ChartGhostWireframe=qi;exports.ChartLegend=Us;exports.ChartRouter=Pu;exports.ChartSortingControls=Hu;exports.ChartTableModal=zu;exports.ChartTooltip=Fs;exports.ColumnSelect=Dn;exports.ColumnTypeBadge=sS;exports.DEFAULT_IMAGE_QUALITY=Jd;exports.DEFAULT_MAX_DIMENSION=Xd;exports.DEV_LOCK_STORAGE_KEY=rr;exports.DEV_SALT=mh;exports.DEV_SESSION_ID_KEY=zc;exports.DRAFT_ACTIVE_KEY=od;exports.DRAFT_CANVAS_PREFIX=Eh;exports.DRAFT_CONTENT_KEY=$h;exports.DRAFT_DIRTY_KEY=Lh;exports.DataPendingCard=Ou;exports.DevActionAffordance=Ln;exports.DevExitConfirmModal=el;exports.DevHelpTooltip=Pn;exports.DevLockBlockedModal=Ju;exports.DevModeBadge=Xu;exports.DevPinModal=Wu;exports.DevPublishModal=Qi;exports.DeveloperModeProvider=Fd;exports.DocumentCanvas=Ji;exports.DonutChart=Du;exports.DraggableRows=Fu;exports.Drawer=Vi;exports.DrawerTier=Lw;exports.EVENT_CHART_SOURCE_CHANGE=_a;exports.EVENT_CLOUD_DRAFT_SYNC_STATUS=ca;exports.EVENT_DRAFT_CANVAS_CHANGE=Ds;exports.EVENT_DRAFT_CONTENT_CHANGE=_r;exports.EVENT_DRAFT_STATUS_CHANGE=la;exports.EVENT_HISTORY_CHANGE=ua;exports.EVENT_LIVE_CANVAS_CHANGE=Ms;exports.EVENT_LIVE_CONTENT_CHANGE=Ia;exports.EVENT_SOURCE_SOURCE_CHANGE=wa;exports.EXPECTED_PIN_HASH=Rc;exports.EditableText=gt;exports.EditorialSection=Qu;exports.EditorialSidebar=au;exports.EnzoLogo=pr;exports.FAB=To;exports.HEARTBEAT_INTERVAL_MS=qc;exports.HISTORY_SCHEMA_VERSION=Bs;exports.HeroPhoto=N2;exports.HeroSection=xi;exports.HeroWelcome=xi;exports.HistogramChart=Bu;exports.HistoryHubModal=Yu;exports.LEGACY_STORAGE_KEY_ACTIVE_PUBLISHED_ID=ks;exports.LOCAL_STORAGE_ALL_KEY=Px;exports.LOCAL_STORAGE_PREFIX=Bx;exports.LOCKOUT_DURATION_MS=uo;exports.LOCK_EXPIRATION_MS=Na;exports.LineChart=Mu;exports.MAX_ATTEMPTS=es;exports.MAX_AUTOSAVES=jd;exports.MAX_STACK_DEPTH=ra;exports.MEDIA_BUCKET_ID=jo;exports.Modal=ut;exports.NODE_IDS=Zt;exports.NODE_TO_STAGE=Bo;exports.PHOTO_STACKED_BREAKPOINT=su;exports.PageTitle=Si;exports.ParametricShape=pr;exports.RangePreviewMatrix=Gu;exports.RevolvingButton=Mw;exports.RoadmapNode=bi;exports.RoadmapSection=_i;exports.RoadmapTrack=yi;exports.SESSION_DURATION_MS=Oo;exports.STAGE_TO_NODE=mj;exports.STORAGE_KEY_ACTIVE_PUBLISHED_ID=Uh;exports.STORAGE_KEY_CONTENT_OVERRIDES=Nh;exports.STORAGE_KEY_DRAFT_CONTENT=Ch;exports.STORAGE_KEY_FAILED_ATTEMPTS=ph;exports.STORAGE_KEY_HISTORY_MANIFEST=si;exports.STORAGE_KEY_LEGACY_CONTENT=kh;exports.STORAGE_KEY_LIVE_ACTIVE_PUBLISHED_ID=Fh;exports.STORAGE_KEY_LIVE_CONTENT=nd;exports.STORAGE_KEY_LOCKOUT_UNTIL=fh;exports.STORAGE_KEY_MISSING_TABLES=xr;exports.STORAGE_KEY_SOURCE_CACHE=Pi;exports.STORAGE_KEY_UNLOCKED_AT=Ca;exports.ScatterPlot=Ru;exports.SearchField=tI;exports.SectionTitle=Ha;exports.SeriesSelectToolbar=xS;exports.StatusPill=or;exports.TAB_INSTANCE_ID=Qs;exports.TieredSlider=Uu;exports.Toast=Ot;exports.UndoRedoContext=vi;exports.UndoRedoManager=Wd;exports.UndoRedoProvider=Yd;exports.UniversalEditModal=An;exports.VALID_NODES=hj;exports.ValueLabelToggle=ia;exports.acquireDevLock=xo;exports.acquireScrollLock=ci;exports.broadcastLiveSync=Ld;exports.canPublishDraft=Yh;exports.cancelCinematicScroll=ma;exports.canvasLayoutService=Ph;exports.captureCurrentSnapshot=Oa;exports.checkDevLockStatus=In;exports.checkDraftStaleness=kr;exports.cinematicScrollTo=ir;exports.clearAllDirtyEditors=gm;exports.clearAllHistory=Vh;exports.clearDraftStorage=tr;exports.clearLockoutUntil=po;exports.clearSessionUnlockTime=Tn;exports.closeSyncBroadcastChannel=Xh;exports.computeMetricsSummary=Ba;exports.deleteSnapshot=qh;exports.deployNodeCanvasToCloud=ti;exports.discardDraftSession=Xo;exports.dispatchAggregateCanvasChange=Tr;exports.dispatchDraftChange=mn;exports.downscaleImage=Qd;exports.exportHistoryBackupJson=Wh;exports.fetchActiveCloudDraft=fd;exports.fetchActivePublishedVersionFromCloud=Ed;exports.fetchChartConfig=wu;exports.fetchChartConfigsByNode=Fx;exports.fetchLiveSourceSources=Oi;exports.fetchPublishedHistoryFromCloud=Ad;exports.findCanvasItemLocation=sa;exports.findPositiveActionElement=pi;exports.foldCanvasOverridesIntoDocument=wd;exports.formatSaveErrorMessage=ss;exports.generateParametricPath=hh;exports.generateSerpentineRoadmap=tu;exports.generateWavyPolygonPath=Po;exports.getActiveNodeIds=At;exports.getActivePublishedId=Yt;exports.getAllContentOverrides=Sr;exports.getBroadcastChannelName=ni;exports.getCachedChartConfig=Is;exports.getCanvasDraftStoragePrefix=Jo;exports.getCanvasLegacyStoragePrefix=Zo;exports.getCanvasLiveStoragePrefix=gn;exports.getCanvasStorageKey=xd;exports.getChartSourcePrefix=Ts;exports.getChartSourcesManifestKey=$r;exports.getCloudDraftSyncStatus=ud;exports.getContent=hn;exports.getContentObject=zo;exports.getContentSnapshot=ad;exports.getDefaultSystemBaselineSnapshot=Pa;exports.getDevFailedAttemptsKey=vr;exports.getDevLockStorageKey=Hc;exports.getDevLockoutUntilKey=gr;exports.getDevSalt=Sa;exports.getDevSessionIdKey=bs;exports.getDevUnlockedAtKey=Bc;exports.getDraftActiveKey=fn;exports.getDraftBaseId=Cr;exports.getDraftCanvasKey=Ls;exports.getDraftCanvasPrefix=Vo;exports.getDraftCanvasStorageKey=bd;exports.getDraftContentKey=Wo;exports.getDraftContentStorageKey=Hn;exports.getDraftDirtyKey=Un;exports.getFailedAttempts=ea;exports.getHistoryDbName=Jc;exports.getHistoryManifest=$t;exports.getHistoryManifestKey=Ss;exports.getHydrationState=Zh;exports.getInMemoryDraftCanvas=cd;exports.getLegacyContentStorageKey=yr;exports.getLiveActivePublishedIdKey=Cs;exports.getLiveContentOverrides=Ih;exports.getLiveContentStorageKey=Gn;exports.getLiveNodeCanvas=Ra;exports.getLiveSourceSource=qa;exports.getLocalFallbackSnapshots=dn;exports.getLocalLock=br;exports.getLockoutUntil=cn;exports.getMissingTablesStorageKey=Uc;exports.getNodeCanvas=It;exports.getRemainingSessionMinutes=mo;exports.getSessionBroadcastChannel=Vc;exports.getSessionId=ja;exports.getSessionUnlockTime=Wt;exports.getSourceCacheStorageKey=mr;exports.getSourceSourceSync=vs;exports.getStorage=Se;exports.getSupabaseConfig=qe;exports.getSyncBroadcastChannel=oi;exports.handleBeforeUnloadGuard=li;exports.handleIncomingSyncBroadcast=Md;exports.hasAnyUnsavedChanges=Pd;exports.hasContentOverride=sd;exports.hasDraftKeys=md;exports.hashPin=Pc;exports.hydrateActiveVersionFromCloud=Rd;exports.hydrateHistoryFromIndexedDB=ri;exports.importHistoryBackupJson=Kh;exports.initDraftSession=ta;exports.insertLeafElement=So;exports.insertSection=_o;exports.insertSubsection=wo;exports.invalidateContentCache=ms;exports.isClickablePositiveCandidate=$n;exports.isCloudHydrating=Jh;exports.isDesktopDevice=Qr;exports.isDraftDirty=Nr;exports.isDraftModeActive=Ma;exports.isDraftStale=Mh;exports.isInitialHydrationPending=ii;exports.isLockExpired=Fo;exports.isPositiveShortcut=fi;exports.isSessionValid=En;exports.isTableAvailable=St;exports.isTextInput=Kd;exports.isTopmostModal=mi;exports.loadFromIndexedDB=ed;exports.mapChartConfigToDbRow=_u;exports.mapDbRowToChartConfig=Li;exports.markTableAvailable=Gc;exports.markTableMissing=Et;exports.migrateCanvasOverridesIntoAst=ws;exports.migrateLegacyStorageKeys=yd;exports.moveCanvasItem=Sd;exports.notifyChartChange=Ua;exports.parseHash=fj;exports.parseRoute=ds;exports.progressToDrawnLength=nu;exports.pruneAutoSaves=ai;exports.publishNewSnapshot=$d;exports.purgeLegacyDocumentStorage=td;exports.regenerateSessionId=Wc;exports.registerActiveModal=ui;exports.registerDirtyEditor=Bd;exports.releaseDevLock=bo;exports.releaseDevLockBeacon=Yc;exports.releaseScrollLock=di;exports.relocateCanvasItem=Cd;exports.removeCanvasItem=kd;exports.renewDevLockHeartbeat=Kc;exports.renumberSections=vt;exports.resetAllContentOverrides=Th;exports.resetChartSourceCache=Gx;exports.resetContent=hs;exports.resetFailedAttempts=vo;exports.resetHydrationStateForTesting=Qh;exports.resetMissingTablesForTesting=yh;exports.resetNodeCanvas=Qo;exports.resetSessionIdForTesting=_h;exports.resetSourceCache=my;exports.restoreSnapshotToDraft=Co;exports.restoreUnifiedSnapshot=zh;exports.sanitizeFilename=Zd;exports.sanitizeLiveSourceSource=za;exports.sanitizePublicChartConfig=Ox;exports.saveChartConfig=Ux;exports.saveChartConfigDetailed=As;exports.saveHistoryManifest=en;exports.saveLiveNodeCanvas=Rs;exports.saveMilestone=Gh;exports.saveNodeCanvas=jr;exports.saveToIndexedDB=Qc;exports.setActivePublishedId=Ps;exports.setAllContentOverrides=Ea;exports.setCachedChartConfig=jt;exports.setContent=Kt;exports.setContentObject=jh;exports.setDraftDirty=pn;exports.setDraftModeActive=as;exports.setFailedAttempts=go;exports.setInMemoryDraftCanvas=La;exports.setLiveContentOverrides=$a;exports.setLocalLock=pt;exports.setLockoutUntil=fo;exports.setSessionUnlockTime=Fc;exports.sha256Fallback=ho;exports.subscribeContentKey=rd;exports.subscribeToCanvasChange=ei;exports.subscribeToCloudDraftSync=hd;exports.subscribeToContentChange=qo;exports.subscribeToDraftStatus=dd;exports.subscribeToHistoryChange=Id;exports.subscribeToHydration=Dd;exports.subscribeToLockStorage=Xc;exports.syncDraftToCloud=pd;exports.syncDraftWithPublished=gd;exports.triggerAutoSave=Hh;exports.triggerDebouncedCloudDraftSync=Da;exports.triggerPositiveAction=gi;exports.undoRedoService=zt;exports.unregisterActiveModal=hi;exports.unregisterDirtyEditor=No;exports.updateCanvasItem=Nd;exports.uploadMediaAsset=ha;exports.upsertLiveSourceSource=Es;exports.useAppRoute=pj;exports.useDeveloperMode=Ne;exports.useDocumentCanvas=Mi;exports.useHashRoute=Zi;exports.useLightboxHistory=Su;exports.useNodeCanvas=zx;exports.useRoadmapScroll=eu;exports.useScroll=_2;exports.useScrollspy=ru;exports.useUndoRedo=Ir;exports.verifyPin=Oc;