1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/browser-CHqGei6v.js","assets/TrialOnboardingPage-PzYt0IP7.js","assets/app-entry-C-S2bLk_.js","assets/index-BiKk9ReD.css","assets/TrialOnboardingPage-GZAhcZEq.css","assets/web-C8Nc9ZnS.js","assets/use-member-navigation-vFtIpYkR.js","assets/PublicShopPage-Bw42osiS.js","assets/public-onboarding-DGoA89Ym.js","assets/public-onboarding-ZYdWQyDt.css","assets/member-auth-context-ChvFobOE.js","assets/timetable-snapshot-store-Btqgy-lu.js","assets/public-runtime-MF82CMTq.js","assets/PublicShopPage-BcCx_ro2.css","assets/runtime-Cd2pG7iS.js","assets/public-checkout-status-utils-Bd3-BRzv.js","assets/DiscountSummary-DxT2Hd67.js","assets/member-utils-kyqO714T.js","assets/PublicLinkPage-C1Edw9JX.js","assets/page-error-utils-C0YWWKqS.js","assets/AdultMembershipLandingPage-CJtl1yEZ.js","assets/membership-onboarding-steps-Dnld-uMS.js","assets/use-external-redirect-recovery-Bi5G5Dzd.js","assets/draft-storage-6EBryOlj.js","assets/public-link-fallbacks-BW6qTwX2.js","assets/use-onboarding-wording-D1vSLmWR.js","assets/PublicLinkPage-9aqToByI.css","assets/PlanOnboardingPage-DMbixdUq.js","assets/conversion-status-utils-BN8hSVaf.js","assets/MemberFormEditor-CyUU3QAP.js","assets/MemberFormEditor-BoSbdP3_.css","assets/member-event-link-_d1QJ5_H.js","assets/WorkshopRegistrationPage-BX2Ezw2w.js","assets/WorkshopCommercePage-DBFapfmM.css","assets/BookATrialPage-DiBgBXTL.js","assets/trial-family-availability-DuPoKoAM.js","assets/trial-booking-gateway-D9CfC8nJ.js","assets/ConversionOnboardingPage-qEqufUjM.js","assets/FundraiserPage-Cu2En-yj.js","assets/contracts-Cvex37F7.js","assets/PurchaseLinkPage-B495oNiD.js","assets/PublicWorkoutDisplayPage-DuFWvBLT.js","assets/PublicWorkoutDisplayPage-D3vhmGhU.css","assets/PublicRedirectPage-DCbaC0t-.js","assets/EventChangeResponsePage-B9FLZ5Xw.js","assets/TrialOnboardingPage-v3iaCnws.js","assets/TrialIntakePage-DYpViZTY.js","assets/WorkshopFormsPage-DK_W52JD.js"])))=>i.map(i=>d[i]); 2import{g as St,B as Hu,u as mt,k as Vu,r,l as po,N as ms,m as Gi,b as he,n as Or,a as zu,o as Gu,j as e,p as Ku,q as Yu,s as xa,t as ln,v as Ni,M as Qu,w as Zu,x as Qs,A as cn,y as Kl,z as Ju,C as Do,D as rr,L as tr,E as Yl,F as Xu,G as Lo,H as Ql,T as ed,R as td,P as sd,d as nd,e as ad,f as rd,h as id,i as od}from"./TrialOnboardingPage-PzYt0IP7.js";import{L as ld,g as Br,R as Zl,N as cd,V as ud,I as Qr,a as dd,b as Jl,S as md,c as hd,u as tt,d as pd,e as bd,f as fd,h as gd,i as wn,j as xd,k as pt,l as V,m as yt,n as jd,p as Fn,o as at,q as Te,r as Cn,s as bo,t as fo,v as Dt,w as Hn,x as Ps,y as vt,z as Xl,A as Vn,B as Zr,C as ec,D as yd,E as js,F as vd,G as Nd,H as Io,J as $o,K as Oo,M as $n,O as Fs,P as kd,Q as wd,T as Cd,U as Sd,W as Pd}from"./use-member-navigation-vFtIpYkR.js";import{PublicShopPage as ki,PublicShopOrderPage as Rd}from"./PublicShopPage-Bw42osiS.js";import{M as sr,d as Td,e as Bo,n as _d,f as Ks,_ as ir,g as Fr,s as tc,m as Md,p as Ud,i as Ed,h as Ad,j as Dd,k as sc,l as go,q as Ld,t as Id,u as nc,r as $d,o as Od,L as $a,a as Bd,v as Fd,w as Wd,x as qd,y as Hd,z as Vd,c as zd}from"./app-entry-C-S2bLk_.js";import{u as Ge,M as Gd}from"./member-auth-context-ChvFobOE.js";import{p as ac,g as Fo,a as Wo,c as Kd}from"./public-runtime-MF82CMTq.js";import{m as T,r as Oa,a as Yd}from"./runtime-Cd2pG7iS.js";import"./timetable-snapshot-store-Btqgy-lu.js";import{R as ys,M as Qd,N as Ds,l as Ki,O as Un,u as Zd}from"./public-onboarding-DGoA89Ym.js";import{c as Ut,h as rc,t as ha,a as Ka,p as As,b as Wn,l as xo,s as Ar,d as nr,e as qs,f as da,r as Jr,g as Wr,i as or,j as ic,k as Xr,m as ei,n as Jd,o as zn,q as Hs,u as Xd,v as jo,w as oc,x as ti,y as Ya,z as lc,A as em,B as cc,C as kn,D as si,E as Vs,F as uc,G as dc,H as tm,I as mc,J as sm,K as qr,L as ni,M as ja,N as nm,O as hc,P as pa,Q as Hr,R as qo,S as am,T as rm,U as ai,V as yo,W as im,X as ar,Y as om,Z as qn,_ as pc,$ as lm,a0 as cm,a1 as bc,a2 as fc,a3 as Yi,a4 as um,a5 as ri,a6 as gc,a7 as xc,a8 as Ho,a9 as dm,aa as mm,ab as Vo,ac as wr,ad as wi,ae as jc,af as hm,ag as yc,ah as pm,ai as bm,aj as fm}from"./public-checkout-status-utils-Bd3-BRzv.js";import{f as gs,c as ka,a as Vr,t as Qa,b as ba,d as zs}from"./member-utils-kyqO714T.js";import{Q as vc,P as gm}from"./PublicLinkPage-C1Edw9JX.js";import{d as Nc,b as kc,a as xm,c as wc,f as jm,s as ym,g as En,l as vm,m as Nm,e as Ci,h as km,i as wm,j as Cm,P as Sm,k as Pm}from"./PlanOnboardingPage-DMbixdUq.js";import{u as wa}from"./use-external-redirect-recovery-Bi5G5Dzd.js";import{m as Rm}from"./conversion-status-utils-BN8hSVaf.js";import{n as re,e as Cc,a as na}from"./page-error-utils-C0YWWKqS.js";import{A as Tm}from"./AdultMembershipLandingPage-CJtl1yEZ.js";import{c as Gn,b as ya,r as On,h as Qi,s as Si,f as $t,a as An,d as _m,w as Mm,e as Sc,t as Um,g as Em,E as Pc,i as Am}from"./member-event-link-_d1QJ5_H.js";import{f as gt,b as Rc,a as Dm,W as zo}from"./WorkshopRegistrationPage-BX2Ezw2w.js";import{BookATrialPage as Lm}from"./BookATrialPage-DiBgBXTL.js";import{ConversionOnboardingPage as Im,ConversionOnboardingStatusPage as $m}from"./ConversionOnboardingPage-qEqufUjM.js";import{M as Om,a as rs,b as Bt,c as vn}from"./MemberFormEditor-CyUU3QAP.js";import{FundraiserPage as Bm}from"./FundraiserPage-Cu2En-yj.js";import{readerBrowseRows as Fm,readerLabel as Dn,readerLocation as Pi,readerText as Cr,readerExcerpt as Wm,highlightParts as qm}from"./contracts-Cvex37F7.js";import{PurchaseLinkPage as Hm}from"./PurchaseLinkPage-B495oNiD.js";import{PublicWorkoutDisplayPage as Vm}from"./PublicWorkoutDisplayPage-DuFWvBLT.js";import{PublicRedirectPage as zm}from"./PublicRedirectPage-DCbaC0t-.js";import{EventChangeResponsePage as Gm}from"./EventChangeResponsePage-B9FLZ5Xw.js";import{TrialOnboardingStatusPage as Km,TrialOnboardingPage as Go}from"./TrialOnboardingPage-v3iaCnws.js";import{TrialIntakePage as Ym}from"./TrialIntakePage-DYpViZTY.js";import{WorkshopFormsPage as Qm}from"./WorkshopFormsPage-DK_W52JD.js";const Zm=({path:t,index:s,caseSensitive:n,element:a})=>St.createElement(he,{path:t,index:s,caseSensitive:n,element:a}),lr=({pathname:t,componentProps:s})=>{const{path:n,index:a,...i}=s;
2if(a&&!n)return t===""||t==="/"?{params:{},pathname:t,pathnameBase:t||"/",pattern:{path:"",caseSensitive:!1,end:!0}}:null;if(n===""||n===void 0)return t===""||t==="/"?{params:{},pathname:t,pathnameBase:t||"/",pattern:{path:"",caseSensitive:i.caseSensitive??!1,end:i.end??!0}}:null;if(!n.startsWith("/")){const l={path:`/${n}`,...i};l?.end===void 0&&(l.end=!n.endsWith("*"));const c=t.startsWith("/")?t:`/${t}`,u=Or(l,c);return u?{...u,pathname:t,pathnameBase:u.pathnameBase==="/"?"/":u.pathnameBase.slice(1),pattern:{...u.pattern,path:n}}:null}const o={path:n,...i};return o?.end===void 0&&(o.end=!n.endsWith("*")),Or(o,t)},Tc=(t,s)=>{if(!s||s===""||s.startsWith("/"))return t;const n=t.startsWith("/")?t.slice(1):t;if(!n)return t;const a=n.split("/").filter(Boolean);if(a.length===0)return"";const i=s.split("/").filter(Boolean);if(i.length===0)return n;const o=i.findIndex(l=>l==="*"||l==="**");if(o>=0){const l=i.slice(0,o);if(l.length===0)return n;const c=a.findIndex((u,d)=>l.every((h,m)=>{const f=a[d+m];return f?h.startsWith(":")?!0:f===h:!1}));if(c>=0)return a.slice(c).join("/")}return i.length<=a.length?a.slice(a.length-i.length).join("/"):a[a.length-1]??n},_c=t=>{if(t.length===0)return"";if(t.length===1){const i=t[0].split("/").filter(Boolean);return i.length>1?"/"+i.slice(0,-1).join("/"):"/"+i[0]}const s=t.map(i=>i.split("/").filter(Boolean)),n=Math.min(...s.map(i=>i.length)),a=[];for(let i=0;i<n;i++){const o=s[0][i];if(o.includes(":")||o.includes("*"))break;if(s.every(c=>c[i]===o))a.push(o);else break}return a.length>0?"/"+a.join("/"):""},zr=(t,s)=>s==="/"?!0:t===s||t.startsWith(s+"/"),Mc=t=>t==="*"||t==="/*",Jm=t=>!!t&&t.includes("*")&&!Mc(t),vo=(t,s)=>{const n=t.props.path;return Jm(n)?!!lr({pathname:s,componentProps:t.props}):!1},Uc=(t,s)=>{const n=t.props.path;return t.props.index||Mc(n)?!1:!!lr({pathname:s,componentProps:t.props})},Ec=t=>{const s=t.some(i=>{const o=i.props.path;return o&&!o.startsWith("/")&&o!=="*"}),n=t.some(i=>i.props.index),a=t.some(i=>{const o=i.props.path;return o==="*"||o==="/*"});return{hasRelativeRoutes:s,hasIndexRoute:n,hasWildcardRoute:a,routeChildren:t}},Xm=(t,s)=>t.some(n=>Uc(n,s)||vo(n,s)),eh=(t,s)=>t.find(n=>Uc(n,s)||vo(n,s)),th=(t,s)=>{const n=s.split("/")[0];return t.some(a=>{const i=a.props.path;if(!i||i==="*"||i==="/*"||a.props.index)return!1;const o=i.split("/")[0].replace(/[*:]/g,"");return o?o===n:!1})},sh=(t,s,n)=>t??s??n,nh=(t,s,n)=>{const a=t.filter(c=>{const u=c.props.path;return u&&u.startsWith("/")});if(a.length===0)return;const i=a.map(c=>c.props.path),o=_c(i);if(!o||o==="/")return;const l=n||o;return s.startsWith(o)?{parentPath:o,outletMountPath:l}:{parentPath:void 0,outletMountPath:l}},Ac=t=>{const{currentPathname:s,outletMountPath:n,routeChildren:a,hasRelativeRoutes:i,hasIndexRoute:o,hasWildcardRoute:l}=t;if(n&&!zr(s,n))return{parentPath:void 0,outletMountPath:n};if(n&&(i||o))return{parentPath:n,outletMountPath:n};if(!n&&(i||o)&&s.includes("/")){const c=s.split("/").filter(Boolean);if(c.length>=1){let u,d,h;for(let f=1;f<=c.length;f++){const b="/"+c.slice(0,f).join("/"),p=c.slice(f).join("/");if(!u&&Xm(a,p)){if(d){const v=eh(a,p);if(v){const N=v.props.path;if(!N||N==="")continue}}u=b;break}!d&&(p!==""&&p!=="/")&&l&&(th(a,p)||(d=b)),(p===""||p==="/")&&o&&(h=b)}if(!u){const f=c.join("/");a.some(b=>vo(b,f))&&(u="/")}const m=sh(u,d,h);return{parentPath:m,outletMountPath:m}}}if(!i&&!o){const c=nh(a,s,n);if(c)return c}return{parentPath:n,outletMountPath:n}},ah=t=>t===""?"/":t.startsWith("/")?t:`/${t}`,Dc=t=>t.length>1&&t.endsWith("/")?t.slice(0,-1):t,Ss=t=>{if(!t||t==="")return"/";const s=ah(t);return Dc(s)},No=t=>{let s;if(St.Children.forEach(t,n=>{n.type===zu&&(s=n)}),s)return s.props.children},Zi=t=>{const s=No(t)??t;return St.Children.toArray(s).filter(n=>St.isValidElement(n)&&(n.type===he||n.type===Qr))},Ji=t=>St.isValidElement(t)&&(t.type===ms||typeof t.type=="function"&&t.type.name==="Navigate"),rh=(t,s)=>{if(t.index&&!s.index)return-1;if(!t.index&&s.index)return 1;const n=t.path==="*"||t.path==="/*",a=s.path==="*"||s.path==="/*";if(!n&&a)return-1;if(n&&!a)return 1;const i=t.path.includes("*")||t.path.includes(":"),o=s.path.includes("*")||s.path.includes(":");return!i&&o?-1:i&&!o?1:t.path.length!==s.path.length?s.path.length-t.path.length:0},Ko=t=>[...t].sort((s,n)=>rh({path:s.routeData?.childProps?.path||"",index:!!s.routeData?.childProps?.index},{path:n.routeData?.childProps?.path||"",index:!!n.routeData?.childProps?.index})),ih=100,oh=200,lh=(t,s,n,a)=>{const i=t.props.path,o=i&&!i.startsWith("/"),l=!!t.props.index;if(i==="*"||i==="/*")return n;if(o&&s?.pathnameBase){const u=s.pathnameBase.startsWith("/")?s.pathnameBase.slice(1):s.pathnameBase;return n==="/"?`/${u}`:`${n}/${u}`}return l?n:s?.pathnameBase||a},ch=(t,s,n)=>{const a=[];for(const o of t){if(o.outletId===s)continue;const l=o.routeData?.match;if(l?.params&&Object.keys(l.params).length>0){const c=l.pathnameBase||l.pathname;c&&n.startsWith(c)&&a.push({params:l.params,pathLength:c.length})}}a.sort((o,l)=>o.pathLength-l.pathLength);const i={};for(const o of a)Object.assign(i,o.params);return i},uh=(t,s,n,a,i,o,l,c)=>[...t,{params:s,pathname:n?.pathname||a,pathnameBase:i,route:{id:o.id,path:l.props.path,element:c,index:!!l.props.index,caseSensitive:l.props.caseSensitive,hasErrorBoundary:!1}}],fa=(t,s)=>{const n=!!s.index,a=s.path??"",i=t===""?"/":t,o=s.end!==void 0?s.end:a!==""?!a.endsWith("*"):!0;return{params:{},pathname:n?"":t,pathnameBase:i,pattern:{path:a,caseSensitive:s.caseSensitive??!1,end:n?!0:o}}},Lc=(t,s)=>{if(!s)return null;const n=Ss(s),a=Ss(t);if(a===n)return"";const i=n==="/"?"/":n+"/";return a.startsWith(i)?a.slice(i.length):null},Sr=(t,s,n)=>{if(!t.routeData?.childProps?.index)return null;const a=Lc(s,n);if(a!==null)return a===""||a==="/"?fa(n||s,t.routeData.childProps):null;const i=t.routeData?.match;if(!i)return null;const o=Ss(s),l=Ss(i.pathnameBase||i.pathname||"");return o===l?i:null};class dh extends ud{outletParentPaths=new Map;outletMountPaths=new Map;constructor(){super()}createViewItem=(s,n,a,i)=>{const o=n.props.path||"",l=this.getViewItemsForOutlet(s).find(h=>{const m=h.reactElement?.props??{},f=m.path||"",b=m.element,p=n.props.element,g=!!m.index,v=!!n.props.index,N=St.isValidElement(b)&&b.type===ms,x=St.isValidElement(p)&&p.type===ms;if(N&&x){const k=b.props?.to,j=p.props?.to;if(k===j)return!0}if(g&&v)return!0;
2if(f===o&&f!==""&&f!=="*"){const k=o.includes(":"),j=o.includes("*");if(k){if(j){const I=h.routeData?.match?.pathnameBase,M=Ln(n,a.pathname,!1,this.outletParentPaths.get(s))?.pathnameBase;if(I!==M)return!1}else if(h.routeData?.match?.pathname!==a.pathname)return!1}return!0}return!!(f===o&&f.endsWith("/*")&&f!=="/*")});if(l){l.reactElement=n,l.mount=!0,l.ionPageElement=i||l.ionPageElement;const h=Ln(n,a.pathname,!1,this.outletParentPaths.get(s))||l.routeData?.match||fa(a.pathname,n.props);return l.routeData={match:h,childProps:n.props,lastPathname:l.routeData?.lastPathname},l}const u={id:`${s}-${Br(s)}`,outletId:s,ionPageElement:i,reactElement:n,mount:!0,ionRoute:!0};n.type===Qr&&(u.disableIonPageManagement=n.props.disableIonPageManagement);const d=Ln(n,a.pathname,!0,this.outletParentPaths.get(s))||fa(a.pathname,n.props);return u.routeData={match:d,childProps:n.props},this.add(u),u};renderViewItem=(s,n,a,i)=>{const o=s.reactElement.props.path||"";let l=Ln(s.reactElement,n.pathname,!1,a);if(!l){const N=Sr(s,n.pathname,a);N&&(l=N)}const c=o.includes(":"),u=s.routeData?.match,d=l?.pathname===u?.pathname,h=c&&l&&u&&!d,m=s.reactElement?.props?.element,f=Ji(m);if(f){const N=s.routeData?.childProps?.index?Sr(s,n.pathname,a):null;!(l||N)&&s.mount&&(s.mount=!1,setTimeout(()=>{this.remove(s),i?.()},ih))}!l&&s.mount&&!s.ionPageElement&&!f&&(s.routeData.lastPathname===n.pathname||s.routeData.match?.pathname===n.lastPathname?s.mount=!1:(s.mount=!1,setTimeout(()=>{!s.mount&&!s.ionPageElement&&(this.remove(s),i?.())},oh)));const b=o==="*"||o==="/*";if(l&&!s.mount&&!h&&!b&&(s.mount=!0,s.routeData.match=l),o==="*"||o===""){const N=this.getViewItemsForOutlet(s.outletId),x=a?Lc(n.pathname,a):null;let k=N.some(j=>{if(j.id===s.id)return!1;const I=j.reactElement?.props?.path||"";return I==="*"||I===""?!1:a&&I&&!I.startsWith("/")?x===null?!1:!!lr({pathname:x,componentProps:j.reactElement.props}):!!(j.reactElement?Ln(j.reactElement,n.pathname):null)});if(!k&&o==="*"){const j=this.outletParentPaths.get(s.outletId);if(j){const I=Ss(j);Ss(n.pathname)===I&&N.some(y=>{if(y.id===s.id)return!1;const P=y.reactElement?.props?.path;return P===""||P===void 0||!!y.routeData?.childProps?.index})&&(k=!0)}}k&&(s.mount=!1,s.ionPageElement&&(s.ionPageElement.classList.add("ion-page-hidden"),s.ionPageElement.setAttribute("aria-hidden","true")))}const p=St.cloneElement(s.reactElement),g=p.props.element;l&&s.routeData.match!==l&&!h&&(s.routeData.match=l);const v=h?s.routeData?.match:l||s.routeData?.match;return St.createElement(Gi.Consumer,{key:`view-context-${s.id}`},N=>{const x=N?.matches??[];let k=x.reduce((P,U)=>({...P,...U.params}),{});x.length===0&&Object.keys(k).length===0&&(k=ch(this.getAllViewItems(),s.outletId,n.pathname));const j={...k,...v?.params??{}},I=x.length>0?x[x.length-1].pathnameBase:"/",S=lh(p,v,I,n.pathname),M=uh(x,j,v,n.pathname,S,s,p,g),y=N?{...N,matches:M}:{outlet:null,matches:M,isDataRoute:!1};return St.createElement(dd,{key:`view-${s.id}`,mount:s.mount,removeView:()=>this.remove(s)},St.createElement(Gi.Provider,{value:y},g))})};getChildrenToRender=(s,n,a,i,o)=>{const l=this.getViewItemsForOutlet(s);o&&!this.outletMountPaths.has(s)&&this.outletMountPaths.set(s,o);let c;try{const m=Zi(n.props.children),{hasRelativeRoutes:f,hasIndexRoute:b,hasWildcardRoute:p}=Ec(m);if(f||b){const g=Ac({currentPathname:a.pathname,outletMountPath:this.outletMountPaths.get(s),routeChildren:m,hasRelativeRoutes:f,hasIndexRoute:b,hasWildcardRoute:p});c=g.parentPath,g.outletMountPath&&!this.outletMountPaths.has(s)&&this.outletMountPaths.set(s,g.outletMountPath)}}catch{}return c!==void 0?this.outletParentPaths.set(s,c):this.outletParentPaths.has(s)&&this.outletParentPaths.delete(s),Zi(n.props.children).forEach(m=>{const f=m.props.path,b=l.find(p=>p.reactElement?.props?.path===f);b&&(b.reactElement=m)}),l.filter((m,f,b)=>b.findIndex(g=>g.id===m.id)===f).filter(m=>{const f=m.reactElement?.props?.element;if(Ji(f)&&!m.mount)return!1;if(!m.mount&&!m.ionPageElement){const p=m.reactElement?.props?.path;if(p){if(Ln(m.reactElement,a.pathname,!1,c))return!0;const v=Ss(p.replace(/\/?\*$/,"")),N=Ss(a.pathname);if(!(N===v||N.startsWith(v+"/")))return setTimeout(()=>{this.remove(m),i()},0),!1}}return!0}).map(m=>this.renderViewItem(m,a,c,i))};findViewItemByRouteInfo=(s,n,a)=>{const{viewItem:i,match:o}=this.findViewItemByPath(s.pathname,n);return(a===void 0||a===!0)&&i&&o&&(i.routeData.match=o),i};findLeavingViewItemByRouteInfo=(s,n,a=!0)=>
2{if(!s.lastPathname)return;const{viewItem:i}=this.findViewItemByPath(s.lastPathname,n,a);return i};findViewItemByPathname=(s,n)=>{const{viewItem:a}=this.findViewItemByPath(s,n);return a};findViewItemByPath(s,n,a,i=!0){let o,l=null,c;const u=this.outletParentPaths;if(n)c=Ko(this.getViewItemsForOutlet(n)),c.some(d),!o&&i&&c.some(h);else{const m=Ko(this.getAllViewItems());m.some(d),!o&&i&&m.some(h)}return{viewItem:o,match:l};function d(m){if(a&&!m.ionRoute)return!1;const f=m.routeData.childProps.path||"";if((f==="*"||f==="/*")&&!m.mount)return!1;const b=!!m.routeData.childProps.index,p=m.routeData?.match,g=u.get(m.outletId),v=m.reactElement?Ln(m.reactElement,s,!1,g):null;if(!v){const N=Sr(m,s,g);if(N)return l=N,o=m,!0;if(f===""&&!b&&g){const x=Ss(g);if(Ss(s)===x)return l=fa(s,m.routeData.childProps),o=m,!0}}if(v){const N=v.params&&Object.keys(v.params).length>0,x=v.pathname===p?.pathname,k=f.includes("*"),j=f.includes(":");if(!f&&!b&&s!=="/"&&s!=="")return!1;if(j&&!x)return k&&v.pathnameBase===p?.pathnameBase?(l=v,o=m,!0):!1;if(!N||x||!p||k&&!j&&v.pathnameBase===p?.pathnameBase)return l=v,o=m,!0}return!1}function h(m){const f=m.routeData.childProps,b=f.path===void 0||f.path==="";if(!!f.index){const g=u.get(m.outletId),v=Sr(m,s,g);return v?(l=v,o=m,!0):!1}if(b){const g=m.routeData?.match?.pathnameBase||"",v=Ss(g);return Ss(s)!==v?!1:(l={params:{},pathname:s,pathnameBase:s===""?"/":s,pattern:{path:"",caseSensitive:f.caseSensitive??!1,end:!0}},o=m,!0)}return!1}}cleanupStaleViewItems=s=>{const n=this.getViewItemsForOutlet(s),a=3,i=n.filter(o=>!o.mount);i.length>a&&i.slice(0,i.length-a).forEach(l=>{this.remove(l)})};add=s=>{this.getViewItemsForOutlet(s.outletId).find(a=>a.id===s.id)||(super.add(s),this.cleanupStaleViewItems(s.outletId))};clear=s=>(this.outletParentPaths.delete(s),this.outletMountPaths.delete(s),super.clear(s));remove=s=>{super.remove(s)}}function Ln(t,s,n=!1,a){const i=t?.props??{},o=i.path;let l;a&&o&&!o.startsWith("/")?l=s.startsWith(a)?s.slice(a.length).replace(/^\//,""):s:l=Tc(s,o);const c=lr({pathname:l,componentProps:i});return c||!n?c:!!i.index||!o||o===""?fa(s,i):null}function mh(t){let s;if(typeof t=="string"?s=t:s=t.outerHTML,document){const n=document.createElement("div");n.innerHTML=s,n.style.zIndex="";const a=n.getElementsByTagName("ion-back-button");return a[0]&&a[0].remove(),n.firstChild}}const aa=250,Yo=300,Ri=hd("react-router"),Ba=t=>!t.classList.contains("ion-page-invisible")&&!t.classList.contains("ion-page-hidden")&&t.style.visibility!=="hidden",jn=t=>{t&&(t.classList.add("ion-page-hidden"),t.setAttribute("aria-hidden","true"))},Pr=t=>{t&&(t.style.removeProperty("visibility"),t.style.removeProperty("display"),t.style.removeProperty("transform"),t.style.removeProperty("opacity"),t.classList.remove("ion-page-hidden"),t.removeAttribute("aria-hidden"))},hh=t=>{t&&(t.style.removeProperty("display"),t.classList.remove("ion-page-hidden"),t.removeAttribute("aria-hidden"))},Rr=t=>{const s=t?.reactElement?.props?.path;return!s||s==="*"||s.endsWith("/*")?!1:!s.includes(":")};class ph extends St.PureComponent{id;ionRouterOutlet;routerOutletElement;prevProps;skipTransition;stackContextValue={registerIonPage:this.registerIonPage.bind(this),isInOutlet:()=>!0};pendingPageTransition=!1;waitingForIonPage=!1;ionPageWaitTimeout;outOfScopeUnmountTimeout;wasInScope=!0;lastTransition;preservedViewItems=new Set;_isMounted=!1;transitionRafIds=[];transitionObserver;transitionGeneration=0;transitionEnteringElement;constructor(s){super(s),this.registerIonPage=this.registerIonPage.bind(this),this.transitionPage=this.transitionPage.bind(this),this.handlePageTransition=this.handlePageTransition.bind(this),this.id=s.id||`routerOutlet-${Br("routerOutlet")}`,this.prevProps=void 0,this.skipTransition=!1}outletMountPath=void 0;isRootOutlet=!0;getParentPath(){const s=this.props.routeInfo.pathname;if(!(this.outletMountPath&&!zr(s,this.outletMountPath))){if(this.outletMountPath&&!this.isRootOutlet)return this.outletMountPath;if(this.ionRouterOutlet){const n=Zi(this.ionRouterOutlet.props.children),{hasRelativeRoutes:a,hasIndexRoute:i,hasWildcardRoute:o}=Ec(n);if(!this.isRootOutlet||a||i){const l=Ac({currentPathname:s,outletMountPath:this.outletMountPath,routeChildren:n,hasRelativeRoutes:a,hasIndexRoute:i,hasWildcardRoute:o});return l.outletMountPath&&!this.outletMountPath&&(this.outletMountPath=l.outletMountPath),l.parentPath}}return this.outletMountPath}}findViewItems(s){const n=this.context.findViewItemByRouteInfo(s,this.id);let a=this.context.findLeavingViewItemByRouteInfo(s,this.id);if(!a&&s.prevRouteLastPathname&&(a=this.context.findViewItemByPathname(s.prevRouteLastPathname,this.id)),n&&a&&n===a&&s.routeAction==="replace"&&s.prevRouteLastPathname){const i=this.context.findViewItemByPathname(s.prevRouteLastPathname,this.id);i&&i!==n&&(a=i)}if(n&&!a&&s.routeAction==="replace"&&s.prevRouteLastPathname){const i=this.context.findViewItemByPathname(s.prevRouteLastPathname,this.id);i&&i!==n&&(a=i)}
2return{enteringViewItem:n,leavingViewItem:a}}shouldUnmountLeavingView(s,n,a){if(!a)return!1;if(s.routeAction==="replace"){const o=a?.reactElement?.props?.path;return!(!o||o==="/"||o==="")}return!(s.routeAction==="push"&&s.routeDirection==="forward")&&s.routeDirection!=="none"&&n!==a}handleOutOfScopeOutlet(s){if(!this.outletMountPath||zr(s.pathname,this.outletMountPath))return this.wasInScope=!0,this.outOfScopeUnmountTimeout&&(clearTimeout(this.outOfScopeUnmountTimeout),this.outOfScopeUnmountTimeout=void 0),!1;if(!this.wasInScope)return!0;if(this.wasInScope=!1,this.routerOutletElement?.classList.contains("ion-page")&&this.routerOutletElement?.parentElement?.closest("ion-router-outlet")?.swipeGesture===!0)return this.dismissPresentedOverlays(),!0;const a=this.context.getViewItemsForOutlet(this.id);return a.forEach(i=>{i.ionPageElement&&Ba(i.ionPageElement)&&(i.ionPageElement.dispatchEvent(new CustomEvent("ionViewWillLeave",{bubbles:!1,cancelable:!1})),i.ionPageElement.dispatchEvent(new CustomEvent("ionViewDidLeave",{bubbles:!1,cancelable:!1})))}),this.outOfScopeUnmountTimeout=setTimeout(()=>{this._isMounted&&(a.forEach(i=>{this.context.unMountViewItem(i)}),this.forceUpdate())},aa),!0}handleRootNavigation(s){this.context.getViewItemsForOutlet(this.id).forEach(a=>{a!==s&&(a.ionPageElement&&Ba(a.ionPageElement)&&(a.ionPageElement.dispatchEvent(new CustomEvent("ionViewWillLeave",{bubbles:!1,cancelable:!1})),a.ionPageElement.dispatchEvent(new CustomEvent("ionViewDidLeave",{bubbles:!1,cancelable:!1}))),this.context.unMountViewItem(a))})}handleOutOfContextNestedOutlet(s,n){if(this.isRootOutlet||s!==void 0||!this.ionRouterOutlet)return!1;const a=No(this.ionRouterOutlet.props.children)??this.ionRouterOutlet.props.children;return St.Children.toArray(a).filter(l=>St.isValidElement(l)&&(l.type===he||l.type===Qr)).some(l=>{const c=l.props.path;return c&&!c.startsWith("/")&&c!=="*"})?(jn(n?.ionPageElement),n&&(n.mount=!1),this.forceUpdate(),!0):!1}handleNoMatchingRoute(s,n,a){return this.isRootOutlet||s||n?!1:(jn(a?.ionPageElement),a&&(a.mount=!1),this.forceUpdate(),!0)}handleReadyEnteringView(s,n,a,i){const o=n.reactElement?.props?.path,l=o?o.includes(":"):!1,c=o?o.endsWith("/*"):!1;if(n===a&&(l||c)){const b=Ti(n.reactElement,s.pathname,!0,this.outletMountPath);b&&(n.routeData.match=b);const p=n.ionPageElement;p&&(Pr(p),p.classList.remove("ion-page-invisible"),s.pushedByRoute?p.classList.add("can-go-back"):p.classList.remove("can-go-back")),this.forceUpdate();return}if(c&&s.lastPathname){const b=o.replace(/\/\*$/,""),p=s.pathname.startsWith(b+"/")||s.pathname===b,g=s.lastPathname.startsWith(b+"/")||s.lastPathname===b;if(p&&g){const v=Ti(n.reactElement,s.pathname,!0,this.outletMountPath);v&&(n.routeData.match=v),this.forceUpdate();return}}!a&&this.props.routeInfo.prevRouteLastPathname&&(a=this.context.findViewItemByPathname(this.props.routeInfo.prevRouteLastPathname,this.id)),n.mount||(n.mount=!0),this.preservedViewItems.delete(n);const u=n.ionPageElement&&Ba(n.ionPageElement),d=a!==void 0&&a.ionPageElement&&!Ba(a.ionPageElement),h={enteringId:n.id,leavingId:a?.id},m=a&&this.lastTransition&&this.lastTransition.leavingId&&this.lastTransition.enteringId===h.enteringId&&this.lastTransition.leavingId===h.leavingId;if(u&&d&&m){this.skipTransition&&i&&a&&n!==a&&(a.mount=!1,this.transitionPage(s,n,a,"back")),this.skipTransition=!1,this.forceUpdate();return}if(Pr(n.ionPageElement),m||this.skipTransition){this.skipTransition&&i&&a&&n!==a&&(a.mount=!1,this.transitionPage(s,n,a,"back")),this.skipTransition=!1,this.forceUpdate();return}this.lastTransition=h;const f=this.applySkipAnimationIfNeeded(n,a);if(this.transitionPage(s,n,a,void 0,!1,f),i&&a&&n!==a){const b=s.routeAction==="pop"&&Rr(a);s.routeAction!=="replace"&&!b?a.mount=!1:b&&this.preservedViewItems.add(a),this.handleLeavingViewUnmount(s,n,a)}this.cleanupOrphanedSiblingViews(s,n,a),this.cleanupPreservedViewsOnPush(s,n,a)}cleanupPreservedViewsOnPush(s,n,a){if(s.routeAction==="push"&&this.preservedViewItems.size!==0)for(const i of Array.from(this.preservedViewItems)){if(i===n||i===a){this.preservedViewItems.delete(i);continue}if(!i.mount){this.preservedViewItems.delete(i);continue}i.mount=!1,this.preservedViewItems.delete(i);const o=i;setTimeout(()=>{o.mount||(this.context.unMountViewItem(o),this.forceUpdate())},aa)}}handleLeavingViewUnmount(s,n,a){if(s.routeAction!=="replace")return;if(!a.ionPageElement){a.mount=!1;const d=a;setTimeout(()=>{d.mount||(this.context.unMountViewItem(d),this.forceUpdate())},aa);return}const i=n.reactElement?.props?.path,o=a.reactElement?.props?.path,l=i&&i.endsWith("/*"),c=o&&o!==""&&o!=="*"&&!o.endsWith("/*")&&!a.reactElement?.props?.index;if(l&&!c)return;a.mount=!1;const u=a;setTimeout(()=>{u.mount||(this.context.unMountViewItem(u),this.forceUpdate())},aa)}cleanupOrphanedSiblingViews(s,n,a){const i=n.reactElement?.props?.path;if(!i)return;const o=a?.reactElement?.props?.path,l=p=>p?.endsWith("/*"),c=s.routeAction==="replace",u=s.routeAction==="push"&&s.routeDirection==="none"&&l(i);if(!c&&!u)return;const d=n===a,h=l(i)&&o===i,m=u&&!a&&s.prevRouteLastPathname?.startsWith(i.replace(/\/\*$/,""));if(d||h||m)return;
2const f=this.context.getViewItemsForOutlet(this.id),b=(p,g)=>{const v=!p.startsWith("/"),N=!g.startsWith("/");if(v&&N){const j=p.replace(/\/\*$/,"").split("/").filter(Boolean).length,I=g.replace(/\/\*$/,"").split("/").filter(Boolean).length;return j===I&&j<=1}const x=j=>{const S=j.replace(/\/\*$/,"").split("/").filter(Boolean);for(;S.length>0&&S[S.length-1].startsWith(":");)S.pop();return S.pop(),S.length>0?"/"+S.join("/"):"/"},k=x(p);return k==="/"?!1:k===x(g)};for(const p of f){const g=p.reactElement?.props?.path;if(p.id===n.id||a&&p.id===a.id||!p.mount||!g||g.endsWith("/*")&&i.endsWith("/*"))continue;const N=!g.endsWith("/*");let x=!1;if((c||u)&&N&&(x=b(i,g)),x){jn(p.ionPageElement),p.mount=!1;const k=p;setTimeout(()=>{k.mount||(this.context.unMountViewItem(k),this.forceUpdate())},aa)}}}applySkipAnimationIfNeeded(s,n){let a=!1,i=this.routerOutletElement?.parentElement??null;for(;i&&!i.classList.contains("ion-page");){if(i.tagName==="ION-CONTENT"){a=!0;break}i=i.parentElement}const o=a&&!!n&&s!==n;return o&&n?.ionPageElement&&(n.ionPageElement.style.setProperty("visibility","hidden"),n.ionPageElement.setAttribute("aria-hidden","true")),o}handleWaitingForIonPage(s,n,a,i){const o=n.reactElement?.props?.element;if(Ji(o)){if(this.waitingForIonPage=!1,this.ionPageWaitTimeout&&(clearTimeout(this.ionPageWaitTimeout),this.ionPageWaitTimeout=void 0),this.pendingPageTransition=!1,this.context.getViewItemsForOutlet(this.id).forEach(c=>{c.id!==n.id&&c.ionPageElement&&jn(c.ionPageElement)}),i&&a&&n!==a){const c=s.routeAction==="pop"&&Rr(a);s.routeAction!=="replace"&&!c?a.mount=!1:c&&this.preservedViewItems.add(a),this.handleLeavingViewUnmount(s,n,a)}this.cleanupPreservedViewsOnPush(s,n,a),this.forceUpdate();return}this.waitingForIonPage=!0,this.ionPageWaitTimeout&&clearTimeout(this.ionPageWaitTimeout),this.ionPageWaitTimeout=setTimeout(()=>{if(this.ionPageWaitTimeout=void 0,!this.waitingForIonPage)return;this.waitingForIonPage=!1;const l=this.context.findViewItemByRouteInfo(s,this.id)??n,c=this.context.findLeavingViewItemByRouteInfo(s,this.id)??a;if(l?.ionPageElement){const u=this.applySkipAnimationIfNeeded(l,c??void 0);if(this.transitionPage(s,l,c??void 0,void 0,!1,u),i&&c&&l!==c){const d=s.routeAction==="pop"&&Rr(c);s.routeAction!=="replace"&&!d?c.mount=!1:d&&this.preservedViewItems.add(c),this.handleLeavingViewUnmount(s,l,c)}this.cleanupPreservedViewsOnPush(s,l,c??void 0),this.forceUpdate()}else this.context.getViewItemsForOutlet(this.id).forEach(d=>{d.id!==l.id&&d.ionPageElement&&jn(d.ionPageElement)}),this.forceUpdate(),setTimeout(()=>{if(!this._isMounted||!this.routerOutletElement)return;this.routerOutletElement.querySelectorAll(":scope > .ion-page-invisible").forEach(h=>{h.classList.remove("ion-page-invisible")})},Yo)},Yo),this.forceUpdate()}getSwipeBackRouteInfo(){const{routeInfo:s}=this.props;return this.prevProps&&this.prevProps.routeInfo.pathname===s.pushedByRoute?this.prevProps.routeInfo:{pathname:s.pushedByRoute||""}}componentDidMount(){if(this._isMounted=!0,this.routerOutletElement){this.setupRouterOutlet(this.routerOutletElement);const s=this.props.routeInfo;queueMicrotask(()=>{this._isMounted&&this.props.routeInfo.pathname===s.pathname&&this.handlePageTransition(s)})}}componentDidUpdate(s){const{pathname:n}=this.props.routeInfo,{pathname:a}=s.routeInfo;n!==a?(this.prevProps=s,this.handlePageTransition(this.props.routeInfo)):this.pendingPageTransition&&(this.handlePageTransition(this.props.routeInfo),this.pendingPageTransition=!1)}componentWillUnmount(){this._isMounted=!1;for(const n of this.transitionRafIds)cancelAnimationFrame(n);this.transitionRafIds=[],this.transitionObserver&&(this.transitionObserver.disconnect(),this.transitionObserver=void 0),this.ionPageWaitTimeout&&(clearTimeout(this.ionPageWaitTimeout),this.ionPageWaitTimeout=void 0),this.outOfScopeUnmountTimeout&&(clearTimeout(this.outOfScopeUnmountTimeout),this.outOfScopeUnmountTimeout=void 0),this.waitingForIonPage=!1,this.preservedViewItems.clear(),this.context.getViewItemsForOutlet(this.id).forEach(n=>{jn(n.ionPageElement)}
2),this.context.clearOutlet(this.id)}async handlePageTransition(s){if(!this.routerOutletElement||!this.routerOutletElement.commit){this.pendingPageTransition=!0;return}const n=this.findViewItems(s);let a=n.enteringViewItem,i=n.leavingViewItem,o=this.shouldUnmountLeavingView(s,a,i);const l=this.getParentPath();if(this.handleOutOfScopeOutlet(s)||(s.routeDirection==="root"&&(this.handleRootNavigation(a),i=void 0,o=!1),this.outOfScopeUnmountTimeout&&(clearTimeout(this.outOfScopeUnmountTimeout),this.outOfScopeUnmountTimeout=void 0),this.handleOutOfContextNestedOutlet(l,i)))return;const c=fh(this.ionRouterOutlet?.props.children,s,l);if(this.handleNoMatchingRoute(c,a,i))return;a&&c?a.reactElement=c:c&&(a=this.context.createViewItem(this.id,c,s),this.context.addViewItem(a));const u=a?.ionPageElement&&document.body.contains(a.ionPageElement);if(a&&u)this.waitingForIonPage&&(this.waitingForIonPage=!1),this.ionPageWaitTimeout&&(clearTimeout(this.ionPageWaitTimeout),this.ionPageWaitTimeout=void 0),this.handleReadyEnteringView(s,a,i,o);else if(a&&!u){a.ionPageElement&&!document.body.contains(a.ionPageElement)&&(a.ionPageElement=void 0),a.mount||(a.mount=!0),this.handleWaitingForIonPage(s,a,i,o);return}else if(!a&&!c&&i){jn(i.ionPageElement);const d=s.routeAction==="pop"&&Rr(i);o&&!d?i.mount=!1:o&&d&&this.preservedViewItems.add(i)}this.forceUpdate()}registerIonPage(s,n){this.waitingForIonPage=!1,this.ionPageWaitTimeout&&(clearTimeout(this.ionPageWaitTimeout),this.ionPageWaitTimeout=void 0),this.pendingPageTransition=!1;const a=this.context.findViewItemByRouteInfo(n,this.id);if(a){const i=a.ionPageElement;if(this.shouldRejectOrphanedPage(s,i,n)){this.hideAndRemoveOrphanedPage(s);return}if(i&&i!==s&&i.isConnected&&i.contains(s)||(a.ionPageElement=s,a.ionRoute=!0,i===s))return}this.handlePageTransition(n)}shouldRejectOrphanedPage(s,n,a){if(!n||n===s)return!1;const i=s.getAttribute("data-pageid"),o=n.getAttribute("data-pageid");return!i||!o||i===o?!1:this.props.routeInfo.pathname!==a.pathname}hideAndRemoveOrphanedPage(s){s.classList.add("ion-page-hidden"),s.setAttribute("aria-hidden","true"),setTimeout(()=>{s.parentElement&&s.remove()},aa)}dismissPresentedOverlays(){document.querySelectorAll("ion-modal, ion-popover, ion-action-sheet, ion-alert, ion-loading").forEach(n=>{n.classList.contains("overlay-hidden")||typeof n.dismiss!="function"||n.dismiss().catch(()=>{})})}findEnteringViewForSwipe(s){const n=this.context.findViewItemByRouteInfo(s,this.id,!1);if(n)return n;const a=this.context.findViewItemByRouteInfo(s,void 0,!1);if(a?.ionPageElement&&this.routerOutletElement?.contains(a.ionPageElement))return a}async setupRouterOutlet(s){const n=()=>{const{routeInfo:o}=this.props,l=this.getSwipeBackRouteInfo(),c=this.findEnteringViewForSwipe(l),u=!!(c?.ionPageElement&&document.body.contains(c.ionPageElement)),d=!!c&&(c.mount||u)&&c.routeData.match.pattern.path!==o.pathname&&c.routeData.match.pathname!==o.pathname;return Ri("SwipeBackCanStart",()=>({outletId:this.id,routePathname:o.pathname,swipeBackPathname:l?.pathname,enteringViewId:c?.id,enteringViewPath:c?.reactElement?.props?.path,enteringMount:c?.mount,ionPageInDocument:u,canStartSwipe:d})),d},a=async()=>{const{routeInfo:o}=this.props,l=this.getSwipeBackRouteInfo(),c=this.findEnteringViewForSwipe(l),u=this.context.findViewItemByRouteInfo(o,this.id,!1);return Ri("SwipeBackOnStart:entry",()=>({outletId:this.id,routePathname:o.pathname,swipeBackPathname:l?.pathname,enteringViewId:c?.id,enteringViewPath:c?.reactElement?.props?.path,enteringMount:c?.mount,hasEnteringIonPageElement:!!c?.ionPageElement,leavingViewId:u?.id})),c&&!c.mount&&(c.mount=!0),hh(c?.ionPageElement),c&&u&&await this.transitionPage(o,c,u,"back",!0),Ri("SwipeBackOnStart:exit",()=>({outletId:this.id,enteringFinalComputedDisplay:c?.ionPageElement?getComputedStyle(c.ionPageElement).display:null,enteringFinalInlineDisplay:c?.ionPageElement?.style.display??null,enteringFinalHiddenClass:c?.ionPageElement?.classList.contains("ion-page-hidden")??null})),Promise.resolve()},i=o=>{if(o)this.skipTransition=!0,this.context.goBack();else{const{routeInfo:l}=this.props,c=this.getSwipeBackRouteInfo(),u=this.findEnteringViewForSwipe(c),d=this.context.findViewItemByRouteInfo(l,this.id,!1);u!==d&&u?.ionPageElement!==void 0&&jn(u.ionPageElement)}};s.swipeHandler={canStart:n,onStart:a,onEnd:i}}async transitionPage(s,n,a,i,o=!1,l=!1){const c=++this.transitionGeneration,u=this.routerOutletElement,d=s.routeDirection==="none"||s.routeDirection==="root"?void 0:s.routeDirection,h=i??d,m=()=>this.skipTransition||l||h===void 0,f=()=>{if(m())return!1;const p=Jl();return!!u.animated&&(p?p.getBoolean("animated",!0):!0)},b=async(p,g)=>{const v=this.skipTransition,N=m()?0:void 0;v?this.skipTransition=!1:(p.classList.add("ion-page"),Ba(p)||p.classList.add("ion-page-invisible"));const x=u.commit(p,g,{duration:N,direction:h,showGoBack:!!s.pushedByRoute,progressAnimation:o,animationBuilder:s.routeAnimation}),k=5e3,j=new Promise(S=>setTimeout(()=>S("timeout"),k)),I=await Promise.race([x.then(()=>"done"),j]);this._isMounted&&(I==="timeout"&&p.classList.remove("ion-page-invisible"),c!==this.transitionGeneration&&g&&g===this.transitionEnteringElement&&Pr(g),o||p.classList.remove("ion-page-invisible"))};if(n&&n.ionPageElement&&this.routerOutletElement)if(this.transitionEnteringElement=n.ionPageElement,a&&a.ionPageElement&&n===a)if(Ti(a.reactElement,s.pathname,void 0,this.outletMountPath)&&f()){const g=mh(a.ionPageElement.outerHTML);g&&(this.routerOutletElement.appendChild(g),await b(n.ionPageElement,g),this.routerOutletElement.removeChild(g))}else await b(n.ionPageElement,void 0);else{const p=a?.ionPageElement;if(h===void 0&&!o&&p){const v=n.ionPageElement;if(v.classList.add("ion-page"),Pr(v),s.pushedByRoute?v.classList.add("can-go-back"):v.classList.remove("can-go-back"),await new Promise(x=>{const k=()=>{const S=v.querySelectorAll("ion-header, ion-toolbar, ion-buttons, ion-menu-button, ion-title, ion-content"),M=Array.from(S).every(U=>U.classList.contains("hydrated")),y=v.querySelectorAll("ion-menu-button"),P=Array.from(y).every(U=>!U.classList.contains("menu-button-hidden"));return M&&P};if(k()){x();return}let j=!1;const I=new MutationObserver(()=>{!j&&k()&&(j=!0,I.disconnect(),this.transitionObserver===I&&(this.transitionObserver=void 0),x())});this.transitionObserver&&this.transitionObserver.disconnect(),this.transitionObserver=I,I.observe(v,{subtree:!0,attributes:!0,attributeFilter:["class"]}),setTimeout(()=>{j||(j=!0,I.disconnect(),this.transitionObserver===I&&(this.transitionObserver=void 0),x())},100)}),!this._isMounted)return;v.classList.remove("ion-page-invisible"),(c===this.transitionGeneration||p!==this.transitionEnteringElement)&&(p.classList.add("ion-page-hidden"),p.setAttribute("aria-hidden","true"))}
2else await b(n.ionPageElement,p),p&&!o&&(c===this.transitionGeneration||p!==this.transitionEnteringElement)&&(p.classList.add("ion-page-hidden"),p.setAttribute("aria-hidden","true"))}}render(){const{children:s}=this.props,n=St.Children.only(s);return this.ionRouterOutlet=n,St.createElement(Gi.Consumer,null,a=>{const i=a?.matches,o=i&&i.length>0?i[i.length-1].pathnameBase:void 0;this.isRootOutlet=!i||i.length===0,o&&!this.outletMountPath&&(this.outletMountPath=o);const l=this.context.getChildrenToRender(this.id,this.ionRouterOutlet,this.props.routeInfo,()=>{this.forceUpdate()},o);return St.createElement(md.Provider,{value:this.stackContextValue},St.cloneElement(n,{ref:c=>{n.props.setRef&&n.props.setRef(c),n.props.forwardedRef&&(n.props.forwardedRef.current=c),this.routerOutletElement=c;const{ref:u}=n;typeof u=="function"&&u(c)}},l))})}static get contextType(){return Zl}}function bh(t,s){return t.filter(n=>n.props.path!=null||n.props.index).map(n=>{const a={_element:n};let i=n.props.path;return i&&i.startsWith("/")&&s&&(i===s?i="":i.startsWith(s+"/")&&(i=i.slice(s.length+1))),n.props.index?{index:!0,handle:a,caseSensitive:n.props.caseSensitive||void 0}:{path:i,handle:a,caseSensitive:n.props.caseSensitive||void 0}})}function fh(t,s,n){let a,i;const o=No(t)??t,l=St.Children.toArray(o).filter(h=>St.isValidElement(h)&&(h.type===he||h.type===Qr)),c=n?Dc(n.replace("/*","")):void 0,u=bh(l,c),d=Gu(u,{pathname:s.pathname},c);if(d&&d.length>0&&(a=d[d.length-1].route.handle?._element??void 0),!a){let h=!0;if(n)h=zr(s.pathname,n);else{const m=l.filter(f=>f.props.path&&f.props.path.startsWith("/"));if(m.length>0){const f=m.map(p=>p.props.path),b=_c(f);b&&b!=="/"&&(h=s.pathname.startsWith(b))}}if(h){for(const m of l)if(!m.props.path){i=m;break}}}return a??i}function Ti(t,s,n,a){const i=t?.props?.path;let o;return a&&i&&!i.startsWith("/")?o=s.startsWith(a)?s.slice(a.length).replace(/^\//,""):s:o=Tc(s,i),lr({pathname:o,componentProps:{...t.props,end:n}})}const Qo=t=>{const s={};for(const n of Object.keys(t)){const a=t[n];a!==void 0&&(s[n]=a)}return s},gh=(t,s,n)=>{if(!t||t.pathname===s)return!1;const a=new Set;let i=t;for(;i?.pushedByRoute&&!a.has(i.id);){if(a.add(i.id),i.pushedByRoute===s)return!0;i=n.findLastLocation(i)}return!1},xh=(t,s)=>{const n=t||{},a=s||{},i=Object.keys(n),o=Object.keys(a);return i.length!==o.length?!1:i.every(l=>{const c=n[l],u=a[l];return Array.isArray(c)&&Array.isArray(u)?c.length!==u.length?!1:c.every((d,h)=>d===u[h]):c===u})},Ic=({children:t,registerHistoryListener:s})=>{const n=mt(),a=po(),i=r.useRef(!1),o=r.useRef(new ld),l=r.useRef(void 0),c=r.useRef(new dh),u=r.useRef(null),d=r.useRef([]),h=r.useRef(n.key),[m,f]=r.useState({id:Br("routeInfo"),pathname:n.pathname,search:n.search,params:{}});r.useEffect(()=>{if(!i.current){if(o.current.add(m),l.current){const S={...o.current.current()};S.tab!==l.current&&(S.tab=l.current,o.current.update(S))}s(b),i.current=!0}},[]),r.useEffect(()=>{const M=c.current.findViewItemByRouteInfo(m,void 0,!0)?.routeData.match?.params;if(M){const y=Qo({...M});if(xh(m.params,y))return;const P={...m,params:y};o.current.update(P),f(P)}},[m]);const b=(S,M)=>{const y=o.current.current();if(y.pathname+y.search!==S.pathname+S.search){if(!u.current){let F=o.current.findTabForPathname(S.pathname);if(!F&&l.current){const D=o.current.getFirstRouteInfoForTab(l.current)?.pathname;D&&(S.pathname===D||S.pathname.startsWith(D+"/"))&&(F=l.current)}if(M==="REPLACE"&&(u.current={routeAction:"replace",routeDirection:"none",tab:F}),M==="POP"){const A=o.current.current();if(d.current.length>0&&d.current[d.current.length-1]===S.key)d.current.pop(),u.current={routeAction:"push",routeDirection:"forward",tab:F};else if(A&&A.pushedByRoute){d.current.push(h.current);const R=o.current.findLastLocation(A);if(gh(R,S.pathname,o.current)){const _=o.current.findLastLocationByPathname(S.pathname);u.current={..._||{},routeAction:"pop",routeDirection:"back"}}else if(R&&R.pathname!==S.pathname&&A.tab){u.current={...R,routeAction:"pop",routeDirection:"back"},d.current=[],k(R.pathname+(R.search||""),"pop","back",void 0,void 0,R.tab);return}else u.current={...R,routeAction:"pop",routeDirection:"back"}}else d.current.push(h.current),u.current={routeAction:"pop",routeDirection:"none",tab:F}}if(!u.current){const A=S.state;u.current={routeAction:"push",routeDirection:A?.direction||"forward",routeOptions:A?.routerOptions,tab:F}}}M==="PUSH"&&(d.current=[]);let U;if(!o.current.findTabForPathname(S.pathname)&&l.current&&(l.current=void 0),u.current?.id)U={...u.current,lastPathname:y.pathname},o.current.add(U);else{const F=u.current?.routeAction==="push"&&u.current.routeDirection==="forward";if(U={id:Br("routeInfo"),...u.current,lastPathname:y.pathname,pathname:S.pathname,search:S.search,params:u.current?.params?Qo(u.current.params):{},prevRouteLastPathname:y.lastPathname},F)U.tab=U.tab||y.tab,U.pushedByRoute=y.pathname;else if(U.routeAction==="push"&&U.routeDirection==="none"&&U.tab===y.tab)U.tab=U.tab||y.tab,U.pushedByRoute=y.pathname;else if(U.routeAction==="pop"){const A=o.current.findLastLocation(U);U.pushedByRoute=A?.pushedByRoute}else if(U.routeAction==="push"&&U.tab!==y.tab){const A=o.current.getCurrentRouteInfoForTab(U.tab);U.routeDirection==="none"?U.pushedByRoute=A?.pushedByRoute:U.pushedByRoute=A?.pushedByRoute??y.pathname}else if(U.routeAction==="replace"){const A=o.current.current(),D=A?.pushedByRoute,R=D!==void 0&&D!==U.pathname?D:U.pushedByRoute;U.lastPathname=A?.pathname||U.lastPathname,U.prevRouteLastPathname=A?.lastPathname,U.pushedByRoute=R,U.routeDirection=U.routeDirection||A?.routeDirection,U.routeAnimation=U.routeAnimation||A?.routeAnimation}o.current.add(U)}f(U)}h.current=S.key,u.current=null},p=(S,M,y)=>{const P=o.current.getFirstRouteInfoForTab(S);if(P){const[U,F]=M.split("?"),A={...P};A.pathname=U,A.search=F?"?"+F:"",A.routeOptions=y,u.current={...A,routeAction:"pop",routeDirection:"back"},a(A.pathname+(A.search||""))}},g=(S,M,y)=>{if(!M)return;const P=o.current.getCurrentRouteInfoForTab(S),[U,F]=M.split("?");if(P){const A={...P,routeAction:"push",routeDirection:"none"};if(P.pathname===U){const D=F?"?"+F:P.search;u.current={...A,search:D||"",routeOptions:y},a(P.pathname+(D||""))}else u.current={...A,pathname:U,search:F?"?"+F:"",routeOptions:y},a(U+(F?"?"+F:""))}else{const A=U+(F?"?"+F:"");k(A,"push","none",void 0,y,S)}},v=(S,M)=>{l.current=S;const y=o.current.current();if(!y)return;const P={...y};P.tab!==S&&(P.tab=S,o.current.update(P))},N=()=>{a(-1)},x=(S,M)=>{const y=Jl();S=S??(y&&y.get("backButtonDefaultHref"));const P=o.current.current();if(P&&P.pushedByRoute){const U=o.current.findLastLocation(P);if(U){const F=M||P.routeAnimation;u.current={...U,routeAction:"pop",routeDirection:"back",routeAnimation:F};const A=P.lastPathname===P.pushedByRoute,D=U.pathname===P.pushedByRoute&&!P.tab&&!U.tab;A||D?(d.current.push(h.current),a(-1)):(d.current=[],k(U.pathname+(U.search||""),"pop","back",F))}else S&&k(S,"pop","back",M)}else S&&k(S,"pop","back",M)},k=(S,M,y,P,U,F)=>{const A=M==="push"&&y===void 0?"forward":y;let D=F;if(!F&&l.current&&S){const w=o.current.findTabForPathname(S);if(w)D=w;else{const _=o.current.getFirstRouteInfoForTab(l.current);if(_){const W=_.pathname;S===W||S.startsWith(W+"/")?D=l.current:(l.current=void 0,D=void 0)}}}if(M==="replace"){const w=o.current.previous(),_=o.current.current(),W=w?w.pathname+(w.search||""):void 0;if(w&&_&&w!==_&&W===S){u.current={...w,routeAction:"replace",routeDirection:"back",routeAnimation:P},d.current.push(h.current),a(-1);return}}const R=u.current??{};u.current={...R,routeAction:M,routeDirection:A,routeOptions:U,routeAnimation:P,tab:D},a(S,{replace:M!=="push"})},j=(S,M)=>{l.current=void 0,d.current=[],u.current={routeAction:"replace",routeDirection:"root",routeAnimation:M},a(S,{replace:!0})},I={canGoBack:()=>o.current.canGoBack(),clearOutlet:c.current.clear,findViewItemByPathname:c.current.findViewItemByPathname,getChildrenToRender:c.current.getChildrenToRender,getViewItemsForOutlet:c.current.getViewItemsForOutlet.bind(c.current),goBack:()=>x(),createViewItem:c.current.createViewItem,findViewItemByRouteInfo:c.current.findViewItemByRouteInfo,findLeavingViewItemByRouteInfo:c.current.findLeavingViewItemByRouteInfo,addViewItem:c.current.add,unMountViewItem:c.current.remove};return St.createElement(Zl.Provider,{value:I},St.createElement(cd,{ionRoute:Zm,stackManager:ph,routeInfo:m,onNativeBack:N,onNavigateBack:x,onNavigate:k,onNavigateRoot:j,onSetCurrentTab:v,onCh
2angeTab:g,onResetTab:p,locationHistory:o.current},t))};Ic.displayName="IonRouter";const jh=({children:t})=>{const s=mt(),n=Vu(),a=r.useRef(),i=r.useCallback(l=>{a.current=l},[]),o=r.useCallback((l,c)=>{a.current&&a.current(l,c)},[]);return r.useEffect(()=>{o(s,n)},[s,n,o]),St.createElement(Ic,{registerHistoryListener:i},t)},yh=({children:t,...s})=>St.createElement(Hu,{...s},St.createElement(jh,null,t)),us=(t,s="GBP")=>new Intl.NumberFormat("en-GB",{style:"currency",currency:s}).format(t/100),ua=t=>Object.values(t).join(" / ")||"Standard",Zo=t=>JSON.stringify(Object.entries(t).sort(([s],[n])=>s.localeCompare(n)));function vh(t,s){return s.status==="cancelled"||!["succeeded","partially_refunded"].includes(s.payment_status)||s.review_reason?null:{unfulfilled:"preparing",preparing:s.fulfilment_method==="pickup"?"ready_for_pickup":"dispatched",ready_for_pickup:"collected",dispatched:"delivered"}[t.status]??null}const Nh=!1;function Qe(t){return t?.role==="instructor"||t?.role==="admin"||t?.role==="owner"}function Ys(t,s){return t?.staffCapabilities?.[s]===!0}function ii(t){return t?.canManageInstructorRota===!0}function oi(t){return Qe(t)||Ys(t,"community_manage_members")||Ys(t,"community_manage_prospects")}function Kn(t){return Qe(t)||Ys(t,"community_manage_members")}function Yn(t){return Qe(t)||Ys(t,"community_manage_prospects")}function Qn(t){return Ys(t,"lead_conversations_view")}function $c(t){return Nh}function Zn(t){return Qe(t)||Ys(t,"community_manage_members")}function Oc(t){return t?.accessPolicy?.lifecycleState==="staff"}function un(t){return!!t&&!Oc(t)}function cr(t){return!!t&&t?.hasMemberHubAccess!==!1}function ur(t){return t?.hasParentHubAccess===!0}function dr(t){return Qe(t)}function an(t){return cr(t)?"/member-hub":ur(t)?"/parent-hub":dr(t)?"/instructor-hub":"/timetable"}function ko(t){return un(t)||Qe(t)}function va(t){return un(t)&&t?.memberType!=="child"}function li(t){return un(t)&&t?.memberType!=="child"}function wo(t){return un(t)&&t?.memberType!=="child"}function Bc(t){return un(t)&&t?.memberType!=="child"}function Xt(t){return Qe(t)}function Ws(t){return Xt(t)}function Gs(t){return Qe(t)||Ys(t,"lesson_planning_access")}function kh(t,s){const n=[...t.flatMap(a=>a.conversionCta?.enabled&&a.conversionCta.trialAccessUuid?[{trialAccessUuid:a.conversionCta.trialAccessUuid,personUuid:a.personUuid,displayName:a.displayName,isSelf:a.isSelf}]:[]),...s.flatMap(a=>a.conversionCta?.enabled&&a.conversionCta.trialAccessUuid?[{trialAccessUuid:a.conversionCta.trialAccessUuid,personUuid:a.id,displayName:`${a.childFirstName} ${a.childLastName}`.trim()||"Child profile",isSelf:!1}]:[])];return n.filter((a,i)=>n.findIndex(o=>o.trialAccessUuid===a.trialAccessUuid)===i)}const wh=300*1e3,Fc=r.createContext(null);function Ch({children:t}){const{isAuthenticated:s,user:n}=Ge(),[a,i]=r.useState([]),o=r.useRef(0),l=r.useCallback(async()=>{const u=++o.current;if(!s||!va(n)){i([]);return}const[d,h]=await Promise.allSettled([T.membership.listManagedStatuses(),T.me.listDependants()]);if(o.current!==u)return;const m=d.status==="fulfilled"?d.value:[],f=h.status==="fulfilled"?h.value:[];i(kh(m,f))},[s,n]);r.useEffect(()=>{if(l(),!s||!va(n))return;const u=window.setInterval(()=>{l()},wh),d=()=>{document.visibilityState==="visible"&&l()};return document.addEventListener("visibilitychange",d),()=>{o.current+=1,window.clearInterval(u),document.removeEventListener("visibilitychange",d)}},[s,l,n]);const c=r.useMemo(()=>({offers:a,hasEligibleTrialConversion:a.length>0,refreshTrialMembershipOffers:l}),[a,l]);return e.jsx(Fc.Provider,{value:c,children:t})}function Sh(){const t=r.useContext(Fc);if(!t)throw new Error("useTrialMembershipOffers must be used inside TrialMembershipOffersProvider.");return t}const Ph=300*1e3,Wc=r.createContext(null);function Rh({children:t}){const{isAuthenticated:s,user:n}=Ge(),[a,i]=r.useState(!1),o=r.useRef(0),l=r.useCallback(async()=>{const u=++o.current;if(!s||!n){i(!1);return}try{const d=await T.commerce.listMemberFundraisers();o.current===u&&i(d.length>0)}catch{o.current===u&&i(!1)}},[s,n]);r.useEffect(()=>{if(l(),!s||!n)return;const u=window.setInterval(()=>{l()},Ph),d=()=>{document.visibilityState==="visible"&&l()};return document.addEventListener("visibilitychange",d),()=>{o.current+=1,window.clearInterval(u),document.removeEventListener("visibilitychange",d)}},[s,l,n]);const c=r.useMemo(()=>({hasActiveFundraiser:a,refreshActiveFundraisers:l}),[a,l]);return e.jsx(Wc.Provider,{value:c,children:t})}function qc(){const t=r.useContext(Wc);if(!t)throw new Error("useActiveFundraisers must be used inside ActiveFundraisersProvider.");return t}function Hc(){const{user:t}=Ge(),[s,n]=r.useState(null);return r.useEffect(()=>{let a=!0;n(null);const i=()=>{t&&T.shop.request("config").then(o=>{a&&n(o)}).catch(()=>{a&&n(null)})};return i(),window.addEventListener("focus",i),()=>{a=!1,window.removeEventListener("focus",i)}},[t?.wpUserId,t?.tenantUuid]),{shopEnabled:!!s?.member_visible,shopPermissions:s?.permissions,shopConfig:s}}async function Th(t){await t.closeMenu(),await t.logout(),t.redirectToLogin()}const _h="0.1.0",Nn="member-main-drawer-menu",Vc="member-app-router-outlet";function Mh({contentId:t}){const s=tt(),n=mt(),{user:a,logout:i}=Ge(),{hasActiveFundraiser:o}=qc(),{shopEnabled:l,shopPermissions:c}=Hc(),[u,d]=r.useState(null),h=a?.accessPolicy?.memberExperienceMode==="booking_beta",m=$c(),f=Qe(a),b=Gs(a),p=Xt(a),g=Ws(a),v=oi(a),N=Qn(a),x=cr(a),k=ur(a),j=dr(a),I=a?.role==="owner"||a?.staffCapabilities?.shop_edit_products===!0,S=r.useMemo(()=>new Set(["/timetable","/events",sr,"/events/fundraisers","/community-groups","/forms","/profile","/settings","/people","/curriculum","/training","/member-hub","/parent-hub","/instructor-hub","/resources","/ai-connections","/staff-tools/availability","/staff-tools/rota","/staff-tools","/staff-tools/log-cash","/staff-tools/share-tools","/staff-tools/lesson-plans","/staff-tools/prompts","/leads"]),[]),{directItems:M,groups:y,footerItems:P}=r.useMemo(()=>{const R=H=>!H.hidden&&(!h||S.has(H.path)),w=[{label:"Classes",path:"/timetable",icon:Ut},{label:"Fundraisers",path:"/events/fundraisers",icon:rc,hidden:!o,featured:!0},{label:"Events",path:"/events",icon:ha},{label:"Shop",path:sr,icon:Ka,hidden:!l&&!f&&!c?.shop_edit_products&&!I},{label:a?.communityGroupsPageTitle||"Community groups",path:"/community-groups",icon:As,hidden:(a?.eligibleCommunityGroupCount??0)<1},{label:"Messages",path:"/chat",icon:Wn,hidden:!m},{label:"Lead conversations",path:"/leads",icon:Wn,hidden:!N},{label:"Share Tools",path:"/staff-tools/share-tools",icon:xo,hidden:!f},{label:"Prompts",path:"/staff-tools/prompts",icon:Wn,hidden:!f},{label:"Log cash",path:"/staff-tools/log-cash",icon:Ka,hidden:!f}].filter(R),_=[{label:"Member Hub",icon:Ar,items:[{label:"Resources",path:"/member-hub",icon:da,hidden:!x}].filter(R)},{label:"Parent Hub",icon:As,items:[{label:"Resources",path:"/parent-hub",icon:da,hidden:!k}].filter(R)},{label:"Instructor Hub",icon:Ar,items:[{label:"Training",path:"/training",icon:Jr,hidden:!p},{label:"Curriculum",path:"/curriculum",icon:Ar,hidden:!g},{label:"Lesson Plans",path:"/staff-tools/lesson-plans",icon:da,hidden:!b}
2,{label:"Resources",path:"/instructor-hub",icon:da,hidden:!j}].filter(R)},{label:"Rota",icon:Ut,items:[{label:"Availability",path:"/staff-tools/availability",icon:Ut,hidden:!f},{label:"Instructor Rota",path:"/staff-tools/rota",icon:Ut,hidden:!f}].filter(R)},{label:"Members",icon:As,items:[{label:"People",path:"/people",icon:As,hidden:!v},{label:"Forms & Questionnaires",path:"/forms",icon:Wr,hidden:!f}].filter(R)},{label:"Staff",icon:nr,items:[{label:"Staff Tools",path:"/staff-tools",icon:nr,hidden:!f}].filter(R)},{label:"Account",icon:qs,items:[{label:"Account",path:"/account",icon:qs,hidden:h},{label:"Profile",path:"/profile",icon:qs},{label:"Forms & Questionnaires",path:"/forms",icon:Wr,hidden:f},{label:"Connect your AI",path:"/ai-connections",icon:or}].filter(R)}].filter(H=>H.items.length>0),W=[{label:"Settings",path:"/settings",icon:ic}].filter(R);return{directItems:w,groups:_,footerItems:W}},[S,f,b,m,g,o,I,h,l,c?.shop_edit_products,j,N,x,k,v,p,a?.communityGroupsPageTitle,a?.eligibleCommunityGroupCount]),U=r.useMemo(()=>[...M,...y.flatMap(R=>R.items),...P].filter(R=>n.pathname===R.path||n.pathname.startsWith(`${R.path}/`)).sort((R,w)=>w.path.length-R.path.length)[0]?.path??"",[M,P,y,n.pathname]);r.useEffect(()=>{const R=y.find(w=>w.items.some(_=>_.path===U));R&&d(R.label)},[U,y]);async function F(R){if(await Fn.close(Nn),R==="/timetable"){s.navigateRoot(R);return}s.push(R)}function A(R){return U===R}async function D(){await Th({closeMenu:()=>Fn.close(Nn),logout:i,redirectToLogin:()=>s.replace("/login")})}return e.jsxs(pd,{menuId:Nn,contentId:t,type:"overlay",side:"end",swipeGesture:!1,className:"member-drawer-menu",children:[e.jsx(bd,{children:e.jsx(fd,{className:"member-drawer-toolbar",children:e.jsx(gd,{children:"Menu"})})}),e.jsxs(wn,{className:"member-drawer-content",children:[e.jsxs("div",{className:"member-drawer-user",children:[e.jsx("strong",{children:`${a?.firstName??""} ${a?.lastName??""}`.trim()||"Member"}),e.jsx("p",{children:a?.email||""})]}),e.jsxs(xd,{className:"member-drawer-list",children:[M.map(R=>e.jsxs(pt,{button:!0,detail:!1,"aria-current":A(R.path)?"page":void 0,onClick:()=>{F(R.path)},className:`member-drawer-item${A(R.path)?" is-active":""}${R.featured?" is-fundraiser":""}`,children:[e.jsx(V,{slot:"start",icon:R.icon}),e.jsx(yt,{children:R.label})]},R.path)),y.map(R=>{const w=u===R.label;return e.jsxs("div",{className:"member-drawer-group",children:[e.jsxs(pt,{button:!0,detail:!1,className:"member-drawer-item member-drawer-group-trigger","aria-expanded":w,onClick:()=>d(w?null:R.label),children:[e.jsx(V,{slot:"start",icon:R.icon}),e.jsx(yt,{children:R.label}),e.jsx(V,{slot:"end",icon:w?Xr:ei})]}),w?e.jsx("div",{className:"member-drawer-group-items",children:R.items.map(_=>e.jsxs(pt,{button:!0,detail:!1,"aria-current":A(_.path)?"page":void 0,onClick:()=>{F(_.path)},className:`member-drawer-item member-drawer-child-item${A(_.path)?" is-active":""}`,children:[e.jsx(V,{slot:"start",icon:_.icon}),e.jsx(yt,{children:_.label})]},_.path))}):null]},R.label)}),P.map(R=>e.jsxs(pt,{button:!0,detail:!1,"aria-current":A(R.path)?"page":void 0,onClick:()=>{F(R.path)},className:`member-drawer-item member-drawer-footer-item${A(R.path)?" is-active":""}`,children:[e.jsx(V,{slot:"start",icon:R.icon}),e.jsx(yt,{children:R.label})]},R.path)),e.jsxs(pt,{button:!0,detail:!1,onClick:()=>{D()},className:"member-drawer-item member-drawer-sign-out",children:[e.jsx(V,{slot:"start",icon:Jd}),e.jsx(yt,{children:"Sign out"})]})]})]}),e.jsx(jd,{className:"member-drawer-footer",children:e.jsxs("p",{children:["Version ",_h]})})]})}function Uh(){const{user:t}=Ge(),s=ii(t),n=r.useSyncExternalStore(Oa.subscribe,Oa.getSnapshot,Oa.getServerSnapshot),[a,i]=r.useState(!1),[o,l]=r.useState(""),[c,u]=r.useState(""),d=r.useRef(!1);r.useEffect(()=>{Oa.clear(),l(""),u("")},[t?.id]);const h=()=>{d.current||!n||(Oa.dismiss(n.fingerprint),l(""),u(""))},m=async()=>{if(!(!n||!s||d.current)){d.current=!0,i(!0),l("");try{const f=await T.instructor.emailCompletedRota(n);u(`Emails sent to ${f.sentCount} instructor${f.sentCount===1?"":"s"}.${f.skippedCount?` ${f.skippedCount} could not be sent. Check communication history.`:""}`)}catch(f){l(f instanceof Error?f.message:"Unable to send rota emails.")}finally{d.current=!1,i(!1)}}};return e.jsx(at,{isOpen:s&&!!n,canDismiss:!a,onDidDismiss:h,children:e.jsxs("div",{className:"member-modal-sheet member-rota-confirm-sheet",children:[e.jsxs("div",{className:"member-modal-header",children:[e.jsx("h2",{children:c?"Rota email result":"This week's rota is complete"}),e.jsx("p",{children:n?`${gs(`${n.from}T00:00:00Z`,"UTC")} to ${gs(`${n.to}T00:00:00Z`,"UTC")} · ${n.class_count} classes assigned`:""})]}),c?e.jsx("p",{role:"status",children:c}):e.jsxs(e.Fragment,{children:[e.jsx("p",{children:"Send each assigned instructor their classes for this week?"}),e.jsxs("p",{children:[n?.recipient_count," instructors can receive an email.",n&&n.instructor_count>n.recipient_count?` ${n.instructor_count-n.recipient_count} have no valid email address.`:""]}),o?e.jsx("p",{role:"alert",className:"member-rota-email-warning",children:o}):null]}),e.jsxs("div",{className:"instructor-rota-footer",children:[e.jsx("button",{type:"button",className:"member-btn is-neutral",disabled:a,onClick:h,children:c||o?"Close":"No, do not send"}),!c&&!o?e.jsx("button",{type:"button",className:"member-btn is-solid",disabled:a||!n?.recipient_count,onClick:()=>{m()},children:a?e.jsxs(e.Fragment,{children:[e.jsx(Te,{name:"crescent"})," Sending..."]}):"Send emails"}):null]})]})})}
2const za=70,Eh=6,Ah=["ion-action-sheet:not(.overlay-hidden)","ion-alert:not(.overlay-hidden)","ion-loading:not(.overlay-hidden)","ion-modal:not(.overlay-hidden)","ion-picker:not(.overlay-hidden)","ion-popover:not(.overlay-hidden)","ion-menu.show-menu"].join(","),Dh=["input","textarea","select",'[contenteditable=""]','[contenteditable="true"]','[role="textbox"]'].join(",");function Lh(t=window){return t.matchMedia("(display-mode: standalone)").matches||t.navigator.standalone===!0}function Ih(t){return t.some(s=>s instanceof Element&&s.matches(Dh))}function $h(t=document){return t.querySelector(Ah)!==null}function Oh(t,s){return s>0&&Math.abs(t)<=s}function Jo(t){return t>za}function _i(t,s=window){return t?t.scrollTop<=1:s.scrollY<=1}function Bh(t,s){const n=t.find(i=>i instanceof HTMLElement&&i.tagName.toLowerCase()==="ion-content");if(n)return n;const a=Array.from(s.querySelectorAll("ion-page:not(.ion-page-hidden)"));for(let i=a.length-1;i>=0;i-=1){const o=a[i]?.querySelector("ion-content");if(o)return o}return null}function Fh(t){switch(t){case"ready":return"Release to refresh";case"blocked":return"Finish current action first";case"offline":return"No connection";case"refreshing":return"Refreshing app";default:return"Pull to refresh"}}function Wh(){const[t,s]=r.useState(!1),[n,a]=r.useState("hidden"),[i,o]=r.useState(0),l=r.useRef(!1);if(r.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const d=window.matchMedia("(display-mode: standalone)"),h=()=>s(Lh());return h(),typeof d.addEventListener=="function"?(d.addEventListener("change",h),()=>d.removeEventListener("change",h)):(d.addListener(h),()=>d.removeListener(h))},[]),r.useEffect(()=>(document.documentElement.classList.toggle("member-global-pull-refresh-enabled",t),()=>document.documentElement.classList.remove("member-global-pull-refresh-enabled")),[t]),r.useEffect(()=>{if(!t){a("hidden"),o(0);return}let d=null,h=null;const m=()=>{h!==null&&(window.clearTimeout(h),h=null)},f=()=>{m(),o(0),a("hidden")},b=x=>{m(),o(za),a(x),h=window.setTimeout(f,1800)},p=x=>{if(l.current||x.touches.length!==1||$h()){d=null;return}const k=x.composedPath();if(k.some(M=>M instanceof Element&&M.closest(".lead-chat-page"))){d=null,f();return}if(Ih(k)){d=null;return}const j=x.touches[0],I=Bh(k,document);if(d={cancelled:!1,distance:0,identifier:j.identifier,ownsGesture:!1,scrollElement:null,startX:j.clientX,startY:j.clientY,topKnown:I===null},!I){_i(null)||(d.cancelled=!0);return}(I.getScrollElement?.()??Promise.resolve(I)).then(M=>{!d||d.identifier!==j.identifier||(d.scrollElement=M,d.topKnown=!0,_i(M)||(d.cancelled=!0))}).catch(()=>{d?.identifier===j.identifier&&(d.cancelled=!0)})},g=x=>{if(!d||d.cancelled||!d.topKnown||x.touches.length!==1)return;const k=Array.from(x.touches).find(S=>S.identifier===d?.identifier);if(!k)return;const j=k.clientX-d.startX,I=k.clientY-d.startY;if(!(Math.hypot(j,I)<Eh)){if(I<=0||Math.abs(j)>I){d.cancelled=!0,f();return}if(!_i(d.scrollElement)){d.cancelled=!0,f();return}Oh(j,I)&&(x.preventDefault(),x.stopPropagation(),d.ownsGesture=!0,d.distance=I,o(Math.min(I,za+36)),a(Jo(I)?"ready":"pull"))}},v=x=>{if(!d||!Array.from(x.changedTouches).find(I=>I.identifier===d?.identifier))return;const j=d;if(d=null,j.ownsGesture&&(x.preventDefault(),x.stopPropagation()),!j.ownsGesture||!Jo(j.distance)){f();return}if(Ku()){b("blocked");return}if(navigator.onLine===!1){b("offline");return}m(),l.current=!0,a("refreshing"),o(za),Td({applyUpdate:Yu,reason:"pull_gesture"}).catch(()=>{l.current=!1,f()})},N=()=>{d=null,f()};return document.addEventListener("touchstart",p,{capture:!0,passive:!0}),document.addEventListener("touchmove",g,{capture:!0,passive:!1}),document.addEventListener("touchend",v,{capture:!0,passive:!1}),document.addEventListener("touchcancel",N,{capture:!0,passive:!0}),()=>{m(),document.removeEventListener("touchstart",p,!0),document.removeEventListener("touchmove",g,!0),document.removeEventListener("touchend",v,!0),document.removeEventListener("touchcancel",N,!0)}},[t]),!t)return null;const c=Math.min(i/za,1),u={"--member-pull-refresh-offset":`${Math.round(c*22)}px`,"--member-pull-refresh-rotation":`${Math.round(c*270)}deg`};return e.jsxs("div",{className:`member-global-pull-refresh is-${n}`,style:u,role:"status","aria-live":"polite","aria-hidden":n==="hidden",children:[e.jsx("span",{className:"member-global-pull-refresh-spinner","aria-hidden":"true"}),e.jsx("span",{children:Fh(n)})]})}function zc({children:t,tone:s="neutral"}){return e.jsx("span",{className:`member-status is-${s}`,children:t})}const Gc=1440*60*1e3,Mi=new Map,Xi=new Set;function Kc(){const t=Symbol();return Xi.add(t),()=>{Xi.delete(t)}}function Yc(t){return`skullsystem:member-optional-prompt:v1:${t}`}
2function Qc(t,s,n=Date.now()){if(!t)return!1;const a=Yc(t);let i=Mi.get(a);try{const o=s?.getItem(a),l=o&&o!=="shown"?Number(o):NaN;Number.isFinite(l)&&l>0&&l<=n&&(i=Math.max(i??0,l))}catch{}if(i!==void 0&&i<=n&&n-i<Gc)return Mi.set(a,i),!1;Mi.set(a,n);try{s?.setItem(a,String(n))}catch{}return!0}function qh(t){const s=()=>{document.visibilityState==="visible"&&Xi.size===0&&t()};window.addEventListener("focus",s),document.addEventListener("visibilitychange",s);const n=window.setInterval(s,Gc);return()=>{window.removeEventListener("focus",s),document.removeEventListener("visibilitychange",s),window.clearInterval(n)}}const Xo=new Set,Hh="We could not save this. Please try again.",Vh=900,zh={information:"#dc2626",celebration:"#15803d",attention:"#b45309"};function Gh(t){const s=/^#[0-9a-fA-F]{6}$/.test(t.accentColor||"")?String(t.accentColor).toLowerCase():zh[t.style],n=Number.parseInt(s.slice(1,3),16),a=Number.parseInt(s.slice(3,5),16),i=Number.parseInt(s.slice(5,7),16),o=(n*299+a*587+i*114)/1e3>160?"#111827":"#ffffff";return{"--member-prompt-accent":s,"--member-prompt-tint":`color-mix(in srgb, ${s} 10%, transparent)`,"--member-prompt-contrast":o}}function Kh(t,s,n){if(!t||!s)return null;const a=Yc(t)+(s.repeatOnLoad?":load":"");return s.repeatOnLoad?Xo.has(a)?null:(Xo.add(a),s):Qc(t,n)?s:null}function Co({memberUuid:t,promptCandidate:s,previewMode:n=!1,onPreviewClose:a}){const i=tt(),[o,l]=r.useState(null),c=r.useRef(null),[u,d]=r.useState(null),[h,m]=r.useState(""),[f,b]=r.useState(!1);if(r.useEffect(()=>{if(o&&!n)return Kc()},[o,n]),r.useEffect(()=>{if(n){if(c.current?.memberUuid===t&&c.current.prompt===s)return;c.current={memberUuid:t,prompt:s},b(!1),l(s);return}if(c.current?.memberUuid===t&&(o||c.current.prompt===s))return;let I=null;try{I=window.sessionStorage}catch{I=null}const S=Kh(t,s,I);S&&(c.current={memberUuid:t,prompt:s},b(!1),l(S),T.me.recordMemberAppPromptAction(S,"shown").catch(()=>{}))},[t,s,n,o]),!o)return null;const p=o.actions??[],g=`member-app-prompt-title-${o.promptUuid}`,v=`member-app-prompt-message-${o.promptUuid}`;function N(){o&&(n||T.me.recordMemberAppPromptAction(o,"dismissed").catch(()=>{}),l(null),n&&a?.())}async function x(I){!I||o?.style!=="celebration"||window.matchMedia("(prefers-reduced-motion: reduce)").matches||(b(!0),await new Promise(S=>window.setTimeout(S,Vh)))}async function k(I,S=!1){if(!(!o||u)){d(I),m("");try{n||await T.me.recordMemberAppPromptAction(o,I),await x(S),l(null),n&&a?.()}catch{m(Hh)}finally{d(null)}}}async function j(I,S=!0){if(!o||u)return;const M=I??{key:"primary",type:o.actionType,label:o.actionLabel||"Open link",url:o.actionUrl};if(!M.url&&M.type!=="trial_conversion_link"&&M.type!=="payment_method_session")return;d(M.key),m("");let y=M.url,P=null;if(M.type==="trial_conversion_link"){if(n){await x(S),l(null),a?.(),d(null);return}P=Bo();try{if(!o.trialAccessUuid)throw new Error("Missing trial");if(y=(await T.trials.createConversionLink(o.trialAccessUuid)).url,!y)throw new Error("Missing conversion link")}catch{P?.close(),m("We could not open your membership choices. Please try again."),d(null);return}}if(M.type==="payment_method_session"){if(n){await x(S),l(null),a?.(),d(null);return}P=Bo();try{if(y=(await T.membership.createPaymentMethodSetupSession()).url,!y)throw new Error("Missing payment link")}catch{P?.close(),m("We could not open your payment details. Please try again."),d(null);return}}if(!y){P?.close(),d(null);return}M.type==="internal_link"?i.push(y):_d(P,y)||Ks(y),n||T.me.recordMemberAppPromptAction(o,"opened").catch(()=>{}),await x(S),l(null),n&&a?.(),d(null)}return e.jsx(at,{className:`member-app-prompt-modal is-${o.style}`,style:Gh(o),isOpen:!0,backdropDismiss:!1,canDismiss:!1,"aria-labelledby":g,"aria-describedby":v,children:e.jsxs("section",{className:"member-modal-sheet member-app-prompt-sheet","aria-busy":!!u,children:[n?null:e.jsx("button",{type:"button",className:"member-app-prompt-close member-btn is-neutral",onClick:N,children:"Close"}),n?e.jsxs("div",{className:"member-row-main",children:[e.jsx(zc,{children:"Staff preview"}),e.jsx("button",{type:"button",className:"member-btn is-neutral",disabled:!!u,onClick:()=>{l(null),a?.()},children:"Close preview"})]}):null,f?e.jsx("div",{className:"member-app-prompt-confetti","aria-hidden":"true",children:Array.from({length:18},(I,S)=>e.jsx("span",{},S))}):null,e.jsx("div",{className:"member-app-prompt-icon",children:e.jsx(vc,{iconKey:o.iconKey})}),e.jsxs("div",{className:"member-app-prompt-copy",children:[e.jsx("p",{className:"member-community-group-audience",children:o.style==="celebration"?"Congratulations":o.style==="attention"?"A message from your gym":"Member update"}),e.jsx("h2",{id:g,children:o.title}),e.jsx("p",{id:v,children:o.bodyText})]}),h?e.jsx("p",{className:"member-panel-error",role:"alert",children:h}):null,e.jsxs("div",{className:"member-list-actions member-community-group-actions",children:[o.actionType==="none"&&p.length===0?e.jsx("button",{type:"button",className:"member-btn is-solid",disabled:!!u,onClick:()=>{k("dismissed",!0)},children:u==="dismissed"?"Saving...":o.actionLabel||"Got it"}):p.length>0?p.map((I,S)=>e.jsx("button",{type:"button",className:`member-btn ${S===0?"is-solid":"is-neutral"}`,disabled:!!u,onClick:()=>{j(I,S===0)},children:u===I.key?"Opening...":I.label},I.key)):e.jsx("button",{type:"button",className:"member-btn is-solid",disabled:!!u,onClick:()=>{j()},children:u==="primary"?"Opening...":o.actionLabel||"Open link"}),o.repeatOnLoad&&o.actionType==="trial_conversion_link"?e.jsx("button",{type:"button",className:"member-btn is-neutral",disabled:!!u,onClick:()=>{k("dismissed")},children:"Maybe later"}):null,o.allowSnooze?e.jsx("button",{type:"button",className:"member-btn is-neutral",disabled:!!u,onClick:()=>{k("snoozed")},children:u==="snoozed"?"Saving...":o.snoozeLabel}):null,o.allowPermanentDismissal?e.jsx("button",{type:"button",className:"member-btn is-neutral",disabled:!!u,onClick:()=>{k("dismissed_permanently")},children:u==="dismissed_permanently"?"Saving...":o.permanentDismissalLabel}):null]})]})})}function Yh({enabled:t,identityKey:s}){const[n,a]=r.useState(null);return r.useEffect(()=>{if(!t){a(null);return}let i=!1;return a(null),T.me.getProfile().then(o=>{!i&&o.member?.uuid&&o.memberAppPromptCandidate?.repeatOnLoad&&a({memberUuid:o.member.uuid,prompt:o.memberAppPromptCandidate})}).catch(()=>{}),()=>{i=!0}},[t,s]),t&&n?e.jsx(Co,{memberUuid:n.memberUuid,promptCandidate:n.prompt}):null}const eo="member:availability-requests-changed";function Zc(){window.dispatchEvent(new Event(eo))}
2function Jc(){const{user:t}=Ge(),s=Qe(t),n=`${t?.tenantUuid||""}:${t?.id||""}`,[a,i]=r.useState(null),[o,l]=r.useState(!0),[c,u]=r.useState(""),d=r.useRef(0),h=r.useCallback(async()=>{if(!s)return l(!1),!1;const m=++d.current;try{const f=await T.instructor.listAvailabilityRequests();return m===d.current?(i({identity:n,value:f}),u(""),!0):!1}catch(f){return m===d.current&&u(f instanceof Error?f.message:"Unable to load availability requests."),!1}finally{m===d.current&&l(!1)}},[s,n]);return r.useEffect(()=>{l(!0),i(null),u(""),h();const m=()=>{document.visibilityState!=="hidden"&&h()};window.addEventListener("focus",m),document.addEventListener("visibilitychange",m),window.addEventListener(eo,m);const f=window.setInterval(m,6e4);return()=>{d.current++,window.clearInterval(f),window.removeEventListener("focus",m),document.removeEventListener("visibilitychange",m),window.removeEventListener(eo,m)}},[h]),{requests:s&&a?.identity===n?a.value:null,loading:o,error:c,reload:h}}const Ui=new Set,to=new Set;let so=!1;function el(t){so!==t&&(so=t,to.forEach(s=>s()))}function Xc(){return r.useSyncExternalStore(t=>(to.add(t),()=>to.delete(t)),()=>so,()=>!1)}function tl(t,s,n){return`skullsystem:availability-banner-snooze:v1:${t||"unknown"}:${s||"unknown"}:${n}`}function sl(t,s,n){return`${t||"unknown"}:${s||"unknown"}:${n}`}function Qh({enabled:t=!0,onVisibilityChange:s}){const n=tt(),a=mt(),{requests:i,error:o,reload:l}=Jc(),[c,u]=r.useState(!1),[d,h]=r.useState(""),[m,f]=r.useState(0),{user:b}=Ge(),[p,g]=r.useState(null),[v,N]=r.useState(!1),x=t&&Qe(b),k=r.useMemo(()=>`${b?.tenantUuid||"unknown"}:${b?.id||"unknown"}`,[b?.id,b?.tenantUuid]),j=x&&!o&&(i?.noticeCount||0)>0&&(i?.throughId||0)>m,I=a.pathname==="/staff-tools/availability",S=!I&&(j||v);if(r.useEffect(()=>{f(0),h("")},[k]),r.useEffect(()=>(s?.(S),el(S),document.body.classList.toggle("member-availability-reminder-visible",S),()=>{el(!1),document.body.classList.remove("member-availability-reminder-visible")}),[s,S]),r.useEffect(()=>{if(!x){g(null),N(!1);return}let U=!1;return T.instructor.getAvailabilityCompletion().then(F=>{if(U)return;if(!F){g(null),N(!1);return}const A=sl(b?.tenantUuid,b?.id,F.weekStart),D=tl(b?.tenantUuid,b?.id,F.weekStart);let R=0;try{R=Number(window.localStorage.getItem(D)||0),R>0&&R<=Date.now()&&(window.localStorage.removeItem(D),R=0)}catch{R=0}const w=!F.isComplete&&F.missingCount>0&&F.reminderPolicy.inAppEnabled&&F.reminderPolicy.inAppAvailableToday&&R<=Date.now()&&!Ui.has(A);g(F),N(w),w&&Ui.add(A)}).catch(()=>{U||(g(null),N(!1))}),()=>{U=!0}},[x,k,b?.id,b?.tenantUuid]),j&&!I&&i)return xa.createPortal(e.jsxs("section",{className:"member-forms-banner member-availability-reminder",role:"status","aria-live":"polite",children:[e.jsxs("div",{className:"member-forms-banner-copy",children:[e.jsx("span",{className:"member-forms-banner-eyebrow",children:"Availability requests"}),e.jsxs("strong",{children:[i.totalCount," new class",i.totalCount===1?"":"es"," need",i.totalCount===1?"s":""," your availability"]}),d?e.jsx("p",{role:"alert",children:d}):null]}),e.jsxs("div",{className:"member-forms-banner-actions",children:[e.jsx("button",{className:"member-btn is-solid member-forms-banner-action",onClick:()=>n.push("/staff-tools/availability?view=requests"),children:"Review classes"}),e.jsx("button",{className:"member-btn is-neutral member-forms-banner-action",disabled:c,onClick:()=>{if(c)return;u(!0),h("");const U=i.throughId;T.instructor.dismissAvailabilityRequests(U).then(()=>{f(U),N(!1),Zc(),l()}).catch(()=>h("Unable to dismiss. Please try again.")).finally(()=>u(!1))},children:c?"Dismissing...":"Dismiss"})]})]}),document.body);if(!v||!p||I)return null;const M=sl(b?.tenantUuid,b?.id,p.weekStart),y=tl(b?.tenantUuid,b?.id,p.weekStart),P=()=>{Ui.add(M),N(!1)};return xa.createPortal(e.jsxs("section",{className:"member-forms-banner member-availability-reminder",role:"status","aria-live":"polite",children:[e.jsxs("div",{className:"member-forms-banner-copy",children:[e.jsx("span",{className:"member-forms-banner-eyebrow",children:"Availability"}),e.jsx("strong",{children:"Next week is incomplete"}),e.jsxs("p",{children:[p.missingCount," class",p.missingCount===1?"":"es"," still need an answer."]}
2)]}),e.jsxs("div",{className:"member-forms-banner-actions",children:[e.jsx("button",{type:"button",className:"member-btn is-solid member-forms-banner-action",onClick:()=>{P(),n.push(`/staff-tools/availability?date=${encodeURIComponent(p.weekStart)}`)},children:"Update availability"}),e.jsx("button",{type:"button",className:"member-btn is-neutral member-forms-banner-action",onClick:()=>{try{window.localStorage.setItem(y,String(Date.now()+p.reminderPolicy.inAppSnoozeHours*60*60*1e3))}catch{}P()},children:"Not now"})]})]}),document.body)}function Zh(t){return t.split(/\s+/).filter(Boolean).slice(0,2).map(s=>s[0]?.toUpperCase()??"").join("")||"MP"}function Jh({isOpen:t,onDismiss:s}){const{appearance:n,tenantName:a}=ln(),[i,o]=r.useState([]),[l,c]=r.useState(0),[u,d]=r.useState(!1),[h,m]=r.useState(""),[f,b]=r.useState({apple:!1,google:!1}),[p,g]=r.useState(null),[v,N]=r.useState(""),x=r.useRef(null),k=r.useRef(null),j=n.headerLogoLightUrl||n.headerLogoDarkUrl,I=n.headerLogoLightUrl?n.headerLogoLightImage:n.headerLogoDarkImage,S=r.useCallback(()=>{k.current?.abort(),k.current=null,o([]),c(0),m(""),b({apple:!1,google:!1}),g(null),N(""),d(!1)},[]),M=r.useCallback(async()=>{k.current?.abort();const D=new AbortController;k.current=D,d(!0),m(""),o([]);try{const R=await T.passes.ensure({signal:D.signal}),{default:w}=await ir(async()=>{const{default:H}=await import("./browser-CHqGei6v.js").then(ne=>ne.b);return{default:H}},__vite__mapDeps([0,1,2,3,4])),_=await Promise.all(R.items.map(async H=>({...H,qrDataUrl:await w.toDataURL(H.qrPayload,{errorCorrectionLevel:"M",margin:4,width:1024,color:{dar
2k:"#000000",light:"#ffffff"}})})));if(D.signal.aborted)return;const W=R.defaultMemberUuid?_.findIndex(H=>H.memberUuid===R.defaultMemberUuid):0;o(_),b(R.walletAvailability),c(W>=0?W:0),requestAnimationFrame(()=>{const H=W>=0?W:0;x.current?.children.item(H)?.scrollIntoView({inline:"center",block:"nearest"})})}catch(R){D.signal.aborted||m(R instanceof Error?R.message:"Unable to load member passes.")}finally{D.signal.aborted||d(!1)}},[]);r.useEffect(()=>(t&&M(),()=>k.current?.abort()),[t,M]);const y=r.useCallback(D=>{const R=Math.max(0,Math.min(i.length-1,D));x.current?.children.item(R)?.scrollIntoView({behavior:"smooth",inline:"center",block:"nearest"}),c(R)},[i.length]),P=r.useCallback(()=>{const D=x.current;if(!D||i.length<2)return;const R=D.scrollLeft+D.clientWidth/2;let w=0,_=Number.POSITIVE_INFINITY;Array.from(D.children).forEach((W,H)=>{const ne=W,K=Math.abs(ne.offsetLeft+ne.offsetWidth/2-R);K<_&&(_=K,w=H)}),c(w)},[i.length]),U=r.useCallback(async()=>{const D=i[l];if(!(!D||p)){g("apple"),N("");try{const R=await T.passes.appleWalletPass(D.memberUuid),w=URL.createObjectURL(R.blob),_=document.createElement("a");_.href=w,_.download=R.filename,document.body.appendChild(_),_.click(),_.remove(),window.setTimeout(()=>URL.revokeObjectURL(w),6e4)}catch(R){N(R instanceof Error?R.message:"Unable to add this pass to Apple Wallet.")}finally{g(null)}}},[l,i,p]),F=r.useCallback(async()=>{const D=i[l];if(!D||p)return;const R=window.open("","_blank");R&&(R.opener=null),g("google"),N("");try{const w=await T.passes.googleWalletUrl(D.memberUuid);R?R.location.replace(w):window.open(w,"_blank","noopener,noreferrer")}catch(w){R?.close(),N(w instanceof Error?w.message:"Unable to add this pass to Google Wallet.")}finally{g(null)}},[l,i,p]),A=r.useMemo(()=>i.length>1?`Member Pass ${l+1} of ${i.length}`:"Member Pass",[l,i.length]);return e.jsx(at,{className:"member-pass-modal",isOpen:t,onDidDismiss:()=>{S(),s()},children:e.jsxs("section",{className:"member-pass-screen","aria-label":A,onKeyDown:D=>{D.key==="ArrowLeft"&&y(l-1),D.key==="ArrowRight"&&y(l+1)},children:[e.jsxs("header",{className:"member-pass-screen-header",children:[e.jsx("strong",{children:a||"SkullSystem"}),e.jsx("button",{type:"button","aria-label":"Close member pass",onClick:s,children:e.jsx(V,{icon:zn})})]}),u?e.jsxs("div",{className:"member-pass-state",role:"status",children:[e.jsx(Te,{}),e.jsx("p",{children:"Loading member passes"}),e.jsx("button",{type:"button",onClick:s,children:"Close"})]}):null,!u&&h?e.jsxs("div",{className:"member-pass-state",role:"alert",children:[e.jsx("h2",{children:"Pass unavailable"}),e.jsx("p",{children:h}),e.jsxs("div",{children:[e.jsx("button",{type:"button",onClick:()=>{M()},children:"Retry"}),e.jsx("button",{type:"button",onClick:s,children:"Close"})]})]}):null,!u&&!h&&i.length===0?e.jsxs("div",{className:"member-pass-state",children:[e.jsx("h2",{children:"No member pass available"}),e.jsx("p",{children:"No training member is available for this login."}),e.jsxs("div",{children:[e.jsx("button",{type:"button",onClick:()=>{M()},children:"Retry"}),e.jsx("button",{type:"button",onClick:s,children:"Close"})]})]}):null,!u&&!h&&i.length>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"member-pass-carousel",ref:x,onScroll:P,tabIndex:0,"aria-label":"Household member passes",children:i.map((D,R)=>e.jsxs("article",{className:"member-pass-card","aria-label":`Member Pass for ${D.displayName}, Pass ${R+1} of ${i.length}`,children:[e.jsxs("div",{className:"member-pass-card-brand",children:[j?e.jsx(ys,{image:I,fallbackUrl:j,alt:"",sizes:"140px",width:140,height:70}):e.jsx("strong",{children:a||"SkullSystem"}),e.jsx("span",{children:"Member Pass"})]}),e.jsxs("div",{className:"member-pass-identity",children:[D.photoUrl?e.jsx("img",{src:D.photoUrl,alt:""}):e.jsx("span",{"aria-hidden":"true",children:Zh(D.displayName)}),e.jsx("h2",{children:D.displayName})]}),e.jsx("div",{className:"member-pass-qr",children:e.jsx("img",{src:D.qrDataUrl,alt:`QR code for ${D.displayName}`})}),i.length>1?e.jsxs("p",{className:"member-pass-counter",children:["Pass ",R+1," of ",i.length]}):null]},D.credentialUuid))}),i.length>1?e.jsxs("div",{className:"member-pass-navigation",children:[e.jsx("p",{children:"Swipe left or right to view another pass"}),e.jsxs("div",{className:"member-pass-controls",children:[e.jsx("button",{type:"button","aria-label":"Previous pass",disabled:l===0,onClick:()=>y(l-1),children:e.jsx(V,{icon:Hs})}),e.jsx("div",{className:"member-pass-dots","aria-label":`Pass ${l+1} of ${i.length}`,children:i.map((D,R)=>e.jsx("button",{type:"button","aria-label":`Show pass ${R+1}`,"aria-current":R===l?"true":void 0,onClick:()=>y(R)},D.credentialUuid))}),e.jsx("button",{type:"button","aria-label":"Next pass",disabled:l===i.length-1,onClick:()=>y(l+1),children:e.jsx(V,{icon:ei})})]})]}):null,f.apple||f.google?e.jsxs("div",{className:"member-pass-wallet-actions","aria-label":"Save member pass",children:[f.apple?e.jsx("button",{type:"button",disabled:p!==null,onClick:()=>{U()},children:p==="apple"?"Preparing Apple Wallet pass":"Add to Apple Wallet"}):null,f.google?e.jsx("button",{type:"button",disabled:p!==null,onClick:()=>{F()},children:p==="google"?"Preparing Google Wallet pass":"Add to Google Wallet"}):null]}):null,v?e.jsx("p",{className:"member-pass-wallet-error",role:"alert",children:v}):null]}):null]})})}function So({content:t,backTo:s=null,backToRoot:n=!1,onMenuClick:a,homePath:i="/timetable",hideMenu:o=!1,allowHomeNavigation:l=!0}){const c=tt(),{user:u}=Ge(),{appearance:d,themeMode:h}=ln(),[m,f]=r.useState(!1),b=i,p=h==="dark"?d.headerLogoDarkUrl||d.headerLogoLightUrl||"":d.headerLogoLightUrl||d.headerLogoDarkUrl||"",g=h==="dark"?d.headerLogoDarkUrl?d.headerLogoDarkImage:d.headerLogoLightImage:d.headerLogoLightUrl?d.headerLogoLightImage:d.headerLogoDarkImage;return e.jsxs("header",{className:"member-app-header",children:[s?e.jsx("button",{type:"button",className:"member-app-header-menu member-app-header-back","aria-label":"Go back",onClick:()=>n?c.navigateRoot(s):c.push(s),children:e.jsx(V,{icon:Hs})}):l?e.jsx("button",{type:"button",className:"member-app-header-brand","aria-label":"Open home",onClick:()=>c.push(b),children:p?e.jsx(ys,{image:g,fallbackUrl:p,className:"member-app-header-logo",alt:"Tenant logo",sizes:"120px",width:120,height:120,eager:!0}):e.jsx("span",{children:"SkullSystem"})}):e.jsx("div",{className:"member-app-header-brand","aria-hidden":"true",children:p?e.jsx(ys,{image:g,fallbackUrl:p,className:"member-app-header-logo",alt:"",sizes:"120px",width:120,height:120,eager:!0}):e.jsx("span",{children:"SkullSystem"})}),t?e.jsx("div",{className:"member-app-header-content",children:t}):null,e.jsxs("div",{className:"member-app-header-actions",children:[u?e.jsx("button",{type:"button",className:"member-app-header-menu","aria-label":"Open member pass",onClick:()=>f(!0),children:e.jsx(V,{icon:Xd})}):null,o?e.jsx("span",{className:"member-app-header-menu","aria-hidden":"true"}):e.jsx("button",{type:"button",className:"member-app-header-menu","aria-label":"Open menu",onClick:()=>
2{if(a){a();return}Fn.toggle(Nn)},children:e.jsx(V,{icon:jo})})]}),e.jsx(Jh,{isOpen:m,onDismiss:()=>f(!1)})]})}function eu(){const{user:t}=Ge(),[s,n]=r.useState(0);return r.useEffect(()=>{let a=!1,i=!1;if(n(0),!Qn(t))return;const o=async()=>{if(!(i||document.visibilityState==="hidden")){i=!0;try{const c=await T.leadConversations.unreadTotal();a||n(c)}catch{}finally{i=!1}}};o();const l=window.setInterval(()=>{o()},3e4);return window.addEventListener("lead-unread-changed",o),document.addEventListener("visibilitychange",o),()=>{a=!0,window.clearInterval(l),window.removeEventListener("lead-unread-changed",o),document.removeEventListener("visibilitychange",o)}},[t]),s}function Po({activeTab:t}){const s=tt(),n=eu(),{user:a}=Ge(),{hasActiveFundraiser:i}=qc(),{offers:o}=Sh(),[l,c]=r.useState(!1),u=wa(()=>c(!1)),d=a?.accessPolicy?.memberExperienceMode==="booking_beta",h=a?.role==="instructor",m=Qn(a),f={key:"fundraisers",label:"Fundraiser",icon:rc,active:t==="fundraisers",featured:!0,onClick:()=>s.push("/events/fundraisers")},b={key:"membership",label:"Memberships",icon:ti,active:t==="membership",featured:!0,onClick:()=>{if(!l){if(o.length!==1){s.push("/memberships");return}c(!0),T.trials.createConversionLink(o[0].trialAccessUuid).then(k=>{if(!k.url)throw new Error("Missing conversion link");u(Rm(k.url))}).catch(()=>{c(!1),s.push("/memberships")})}}},p=o.length>0,g=[{key:"classes",label:"Classes",icon:Ut,active:t==="classes",onClick:()=>s.navigateRoot("/timetable")},...m?[{key:"leads",label:"Leads",icon:Wn,active:t==="leads",onClick:()=>s.push("/leads")}]:[{key:"curriculum",label:"Curriculum",icon:da,active:t==="curriculum",onClick:()=>s.push("/curriculum")}],{key:"availability",label:"Availability",icon:oc,active:t==="availability",onClick:()=>s.push("/staff-tools/availability")},{key:"events",label:"Events",icon:ha,active:t==="events",onClick:()=>s.push("/events")},...i?[f]:[],...p?[b]:[],{key:"more",label:"More",icon:Ya,active:!1,onClick:()=>{Fn.open(Nn)}}],v=[{key:"classes",label:"Classes",icon:Ut,active:t==="classes",onClick:()=>s.navigateRoot("/timetable")},{key:"events",label:"Events",icon:ha,active:t==="events",onClick:()=>s.push("/events")},...i?[f]:[],...p?[b]:[],{key:"more",label:"More",icon:Ya,active:!1,onClick:()=>{Fn.open(Nn)}}],N=[{key:"classes",label:"Classes",icon:Ut,active:t==="classes",onClick:()=>s.navigateRoot("/timetable")},{key:"events",label:"Events",icon:ha,active:t==="events",onClick:()=>s.push("/events")},...i?[f]:[],...p?[b]:[],{key:"more",label:"More",icon:Ya,active:!1,onClick:()=>{Fn.open(Nn)}}],x=h?g:d?N:v;return e.jsx("nav",{className:"member-app-bottom-nav","aria-label":"App navigation",style:{gridTemplateColumns:`repeat(${x.length}, minmax(0, 1fr))`},children:x.map(k=>e.jsxs("button",{type:"button",className:`member-app-nav-item${k.active?" is-active":""}${k.featured?` is-${k.key==="fundraisers"?"fundraiser":k.key}`:""}`,onClick:k.onClick,"aria-busy":k.key==="membership"&&l?"true":void 0,children:[e.jsx(V,{icon:k.icon}),k.key==="leads"&&n>0?e.jsx("span",{className:"member-nav-unread","aria-label":`${n} unread messages`,children:n}):null,e.jsx("span",{children:k.label})]},k.key))})}let Za=null,Ei=null;function no(){const t=ac.onboarding.getDefaultOnboardingFlows();return{enabled:t.installPromotionEnabled,copy:t.membership.adult.postSignupSteps.find(s=>s.id==="install")}}function Xh(){return Za?Promise.resolve(Za):(Ei||(Ei=ac.onboarding.getPublicOnboardingFlows().then(t=>({enabled:t.installPromotionEnabled,copy:t.membership.adult.postSignupSteps.find(s=>s.id==="install")??no().copy})).catch(()=>no()).then(t=>(Za=t,t))),Ei)}function tu(){const[t,s]=r.useState(()=>({...Za??no(),loading:Za===null}));return r.useEffect(()=>{let n=!1;return Xh().then(a=>{n||s({...a,loading:!1})}),()=>{n=!0}},[]),t}function ep(){const t=tt(),s=tu(),[n,a]=r.useState(!1),[i,o]=r.useState(()=>Fr());if(r.useEffect(()=>{const c=()=>{o(Fr()),a(s.enabled&&Ed()&&!Ad())};return c(),tc(c)},[s.enabled]),r.useEffect(()=>{n&&Md()},[n]),!n||s.loading||!s.enabled||i.installed)return null;function l(){Dd(),a(!1)}return e.jsxs("section",{className:"member-install-prompt",role:"status","aria-live":"polite",children:[e.jsxs("div",{children:[e.jsx("strong",{children:s.copy.title}),e.jsx("p",{children:s.copy.subtitle})]}),e.jsxs("div",{className:"member-install-prompt-actions",children:[i.capability==="native_prompt"?e.jsx("button",{type:"button",className:"member-btn is-solid",onClick:()=>{Ud().then(()=>a(!1))},children:"Install"}):e.jsx("button",{type:"button",className:"member-btn is-solid",onClick:()=>t.push("/install-app"),children:"View steps"}),e.jsx("button",{type:"button",className:"member-btn",onClick:l,children:"Not now"})]})]})}const Ja={DISMISSED_UNTIL_KEY:"skullsystem.member.notification_prompt_dism
2issed_until.v1",SHOWN_SESSION_KEY:"skullsystem.member.notification_prompt_shown_session.v1",THIRTY_DAYS_MS:720*60*60*1e3};function tp(t){if(!t.installed||!t.supported||t.permission==="denied"||t.permission==="unsupported"||t.subscribed||!t.platformConfigured||t.suppressed)return!1;const s=Number(t.localStorage?.getItem(Ja.DISMISSED_UNTIL_KEY)||"0");return Number.isFinite(s)&&s>t.now?!1:t.sessionStorage?.getItem(Ja.SHOWN_SESSION_KEY)!=="1"}function sp({suppressed:t=!1}){const[s,n]=r.useState(()=>Fr().installed),[a,i]=r.useState(!0),[o,l]=r.useState(!1),[c,u]=r.useState(!0),[d,h]=r.useState(!1),[m,f]=r.useState(""),[b,p]=r.useState(!1);r.useEffect(()=>tc(()=>n(Fr().installed)),[]),r.useEffect(()=>{if(!s||!T.notifications.isSupported()){u(!1);return}const j=new AbortController;return T.notifications.getSettings(j.signal).then(I=>{i(I.device.subscribed),l(I.platformConfigured)}).catch(()=>{}).finally(()=>u(!1)),()=>j.abort()},[s]);let g=null,v=null;try{g=window.localStorage,v=window.sessionStorage}catch{}const N=!c&&(b?s&&T.notifications.isSupported()&&!a&&o&&!t:tp({installed:s,supported:T.notifications.isSupported(),permission:T.notifications.permission(),subscribed:a,platformConfigured:o,suppressed:t,now:Date.now(),localStorage:g,sessionStorage:v}));if(r.useEffect(()=>{if(!(!N||b)){p(!0);try{window.sessionStorage.setItem(Ja.SHOWN_SESSION_KEY,"1")}
2catch{}}},[N,b]),!N)return null;function x(){try{window.localStorage.setItem(Ja.DISMISSED_UNTIL_KEY,String(Date.now()+Ja.THIRTY_DAYS_MS))}catch{}i(!0)}async function k(){if(!d){h(!0),f("");try{const j=await T.notifications.subscribe();i(j.device.subscribed)}catch{f(T.notifications.permission()==="denied"?"Notifications are blocked on this device. You can allow them in your phone or browser settings.":"We could not enable notifications. Please try again in Notification Settings.")}finally{h(!1)}}}return e.jsxs("section",{className:"member-install-prompt member-notification-enable-prompt",role:"status","aria-live":"polite",children:[e.jsxs("div",{children:[e.jsx("strong",{children:"Stay up to date"}),e.jsx("p",{children:"Turn on notifications for booking updates, class reminders and important account messages."}),m?e.jsx("p",{className:"member-panel-error",role:"alert",children:m}):null]}),e.jsxs("div",{className:"member-install-prompt-actions",children:[e.jsx("button",{type:"button",className:"member-btn is-solid",disabled:d,onClick:()=>{k()},children:d?"Enabling...":"Enable notifications"}),e.jsx("button",{type:"button",className:"member-btn",disabled:d,onClick:x,children:"Not now"})]})]})}function np(t,s=!1){return s||t?.readOnly!==!0?!1:t.trialStatus!=="scheduled"}function Ye({standardUI:t=!1,headerContent:s,pageClassName:n,contentClassName:a,mainClassName:i,title:o,subtitle:l,headingAction:c,hideHeading:u=!1,activeTab:d,hideBottomNav:h=!1,suppressReadOnlyNotice:m=!1,backTo:f=null,backToRoot:b=!1,hideMenu:p=!1,allowHomeNavigation:g=!0,onRefresh:v,refresherDisabled:N=!1,formsBannerState:x,suppressInstallPrompt:k=!1,children:j}){const I=tt(),S=mt(),{user:M}=Ge(),y=M?.accessPolicy,P=y?.memberExperienceMode==="booking_beta",U=np(y,m),F=S.pathname==="/timetable",A=F&&!h&&un(M),[D,R]=r.useState(null),w=Xc(),_=y?.lifecycleState==="past_member"?"Read-only access (past member)":"Read-only access",W=y?.bookingBlockedReason||"Booking is currently unavailable for this account.",H=x!==void 0?x:D,ne=r.useMemo(()=>H?Nc(H):"",[H]),K=!w&&F&&H!==null,ye=w||K,de=r.useMemo(()=>{if(!P)return"/forms";const L=`${S.pathname}${S.search}${S.hash}`;return`/forms?scope=required&next=${encodeURIComponent(L)}`},[P,S.hash,S.pathname,S.search]),O=H?kc(de,H):de;return r.useEffect(()=>{if(!A||x!==void 0){R(null);return}const L=new AbortController;return T.me.listForms({signal:L.signal}).then(Z=>{R(xm(Z,{requiredOnly:P}))}).catch(()=>{R(null)}),()=>{L.abort()}},[x,P,A]),e.jsxs(Cn,{className:`member-surface-page${n?` ${n}`:""}`,children:[e.jsx(So,{content:s,backTo:f,backToRoot:b,hideMenu:p,allowHomeNavigation:g}),e.jsxs(wn,{fullscreen:!0,forceOverscroll:!1,className:`member-surface-content${a?` ${a}`:""}`,children:[v?e.jsx(bo,{slot:"fixed",disabled:N,onIonRefresh:L=>{Promise.resolve(v()).catch(()=>{}).finally(()=>{L.detail.complete()})},children:e.jsx(fo,{})}):null,e.jsxs("main",{className:`member-surface-main${t?" member-ui":""}${ye?" has-forms-banner":""}${i?` ${i}`:""}`,children:[u?null:e.jsxs("section",{className:"member-surface-heading",children:[e.jsxs("div",{children:[e.jsx("h1",{children:o}),l?e.jsx("p",{children:l}):null]}),c??null]}),U?e.jsxs("section",{className:"member-access-notice",role:"status","aria-live":"polite",children:[e.jsx("strong",{children:_}),e.jsx("p",{children:W})]}):null,k?null:e.jsx(ep,{}),k?null:e.jsx(sp,{suppressed:U||w||K}),j]})]}),!h&&K?e.jsxs("section",{className:"member-forms-banner",role:"status","aria-live":"polite",children:[e.jsxs("div",{className:"member-forms-banner-copy",children:[e.jsx("span",{className:"member-forms-banner-eyebrow",children:"Forms"}),e.jsx("strong",{children:wc(H)}),e.jsx("p",{children:ne})]}),e.jsx("button",{type:"button",className:"member-btn is-solid member-forms-banner-action",onClick:()=>I.push(O),children:H.incompleteCount===1?"Complete form":"Complete forms"})]}):null,h?null:e.jsx(Po,{activeTab:d})]})}function Fa({links:t,title:s}){const n=tt();return t.length===0?null:e.jsxs("section",{className:"member-section",children:[e.jsx("h2",{children:s}),e.jsx("div",{className:"member-panel-list member-list--divided",children:t.map(a=>e.jsxs("button",{type:"button",className:"member-panel-row",onClick:()=>n.push(a.path),children:[e.jsxs("div",{className:"member-row-main",children:[e.jsx("strong",{children:a.label}),e.jsx(V,{icon:a.icon})]}),e.jsx("p",{children:a.description})]},a.path))})]})}function ap(){const{user:t}=Ge(),[s,n]=r.useState(null),[a,i]=r.useState(!0),[o,l]=r.useState(""),c=r.useCallback(async k=>{i(!0),l("");try{const j=await T.me.getProfile({signal:k});n(j)}catch(j){l(re(j,"Unable to load account details."))}finally{i(!1)}},[]);r.useEffect(()=>{const k=new AbortController;return c(k.signal),()=>{k.abort()}},[c]);const u=s?.member??null,d=t?.memberType==="child",h=un(t),m=Qe(t),f=ka(u),b=r.useMemo(()=>t&&`${t.firstName} ${t.lastName}`.trim()||"Member",[t]),p=h?[{label:"Profile",description:"Update your name, contact details, and emergency contact.",path:"/profile",icon:qs},{label:"Forms & Questionnaires",description:"View completed forms and fill in optional or required forms.",path:"/forms",icon:em}]:[],g=!h||d?[]:[...va(t)?[{label:"Membership",description:"Check your plan, dates, and current status.",path:"/memberships",icon:Jr}]:[],...li(t)?[{label:"Payment Methods",description:"View saved cards and securely update payment details.",path:"/payment-methods",icon:ti}]:[],...wo(t)?[{label:"Payment History",description:"Review membership payments, refunds, and payment status.",path:"/billing-history",icon:lc}
2]:[]],v=h&&f?[{label:"Household",description:"Manage linked family members and child accounts.",path:"/household",icon:As}]:[],N=m?[{label:"Staff Tools",description:"Open instructor tools and class management actions.",path:"/staff-tools",icon:nr}]:[],x=[{label:"App Settings",description:"Change theme, notifications, and device preferences.",path:"/settings",icon:ic}];return e.jsxs(Ye,{standardUI:!0,title:"Account",subtitle:h?"Profile, membership, billing, and app settings.":"App settings and staff tools.",activeTab:"account",onRefresh:c,children:[e.jsxs("section",{className:"member-section",children:[e.jsx("h2",{children:"Signed in"}),e.jsx("p",{children:b}),e.jsx("p",{children:t?.email||"Email unavailable"})]}),a?e.jsxs("div",{className:"member-panel-loading",children:[e.jsx(Te,{name:"crescent"}),e.jsx("span",{children:"Loading account details..."})]}):null,!a&&o?e.jsx("div",{className:"member-panel-error",children:o}):null,e.jsx(Fa,{title:"Your account",links:p}),e.jsx(Fa,{title:"Billing",links:g}),e.jsx(Fa,{title:"Family",links:v}),e.jsx(Fa,{title:"Work",links:N}),e.jsx(Fa,{title:"App",links:x})]})}const rp=[{id:"chatgpt",name:"ChatGPT",description:"Find classes and manage your SkullSystem bookings from ChatGPT.",manualSetupUrl:"https://chatgpt.com/plugins",manualSetupLabel:"Open ChatGPT plugins",publishedConnectionUrl:null,availabilityNote:"Manual connection is available now. Easy connection will appear after the SkullSystem plugin is published."},{id:"claude",name:"Claude",description:"Use your SkullSystem account through a Claude remote connector.",manualSetupUrl:"https://claude.ai/settings/connectors",manualSetupLabel:"Open Claude connectors",publishedConnectionUrl:null,availabilityNote:"Manual connection is available now. Easy connection will appear after the SkullSystem connector is published."},{id:"grok",name:"Grok",description:"Connect SkullSystem as a custom MCP connector in Grok.",manualSetupUrl:"https://grok.com/connectors",manualSetupLabel:"Open Grok connectors",publishedConnectionUrl:null,availabilityNote:"Manual connection is available now. Easy connection will appear if SkullSystem is accepted into the connector catalog."},{id:"gemini",name:"Gemini",description:"Connect SkullSystem as a custom app where Gemini custom MCP apps are available.",manualSetupUrl:"https://gemini.google.com",manualSetupLabel:"Open Gemini",publishedConnectionUrl:null,availabilityNote:"Gemini custom app availability currently depends on the member account, location and Gemini product access."},{id:"other",name:"Other AI",description:"Use the manual MCP address with another compatible AI assistant.",manualSetupUrl:null,manualSetupLabel:null,publishedConnectionUrl:null,availabilityNote:"The AI assistant must support remote Streamable HTTP MCP and browser based OAuth."}];function ip(t){const s=`${t??""}`.trim().toLowerCase().split(":",1)[0]??"",n=s&&s!=="localhost"&&s!=="127.0.0.1"?`https://${s}/api/v1/oauth/connections`:"https://isg.skullsystem.dev/api/v1/oauth/connections";return s==="localhost"||s==="127.0.0.1"||s.endsWith(".skullsystem.dev")?{mcpUrl:"https://mcp.skullsystem.dev/mcp",manageConnectionsUrl:n}:s.endsWith(".skullsystem.site")?{mcpUrl:"https://mcp.skullsystem.site/mcp",manageConnectionsUrl:n}:{mcpUrl:"https://mcp.skullsystem.io/mcp",manageConnectionsUrl:n}}function op({provider:t,mcpUrl:s,onCopy:n}){return e.jsxs("article",{className:"member-panel-card member-ai-provider-card",children:[e.jsxs("div",{className:"member-ai-provider-heading",children:[e.jsxs("div",{children:[e.jsx("h2",{children:t.name}),e.jsx("p",{children:t.description})]}),e.jsx("span",{className:`member-pill${t.publishedConnectionUrl?" is-accent":""}`,children:t.publishedConnectionUrl?"Easy connection available":"Manual setup"})]}),e.jsx("p",{className:"member-ai-availability",children:t.availabilityNote}),e.jsxs("div",{className:"member-ai-actions",children:[t.publishedConnectionUrl?e.jsxs("button",{type:"button",className:"member-btn is-solid",onClick:()=>Ks(t.publishedConnectionUrl||""),children:[e.jsx(V,{icon:Vs})," Connect ",t.name]}):null,t.manualSetupUrl&&t.manualSetupLabel?e.jsxs("button",{type:"button",className:"member-btn",onClick:()=>Ks(t.manualSetupUrl||""),children:[e.jsx(V,{icon:Vs})," ",t.manualSetupLabel]}):null,e.jsxs("button",{type:"button",className:"member-btn is-neutral",onClick:n,children:[e.jsx(V,{icon:kn})," Copy MCP address"]})]}),e.jsxs("details",{className:"member-ai-steps",children:[e.jsx("summary",{children:"Manual setup steps"}),e.jsxs("ol",{children:[e.jsxs("li",{children:["Open the connector or custom app settings in ",t.name==="Other AI"?"your AI assistant":t.name,"."]}),e.jsxs("li",{children:["Add a remote MCP connection and paste ",e.jsx("code",{children:s}),"."]}),e.jsx("li",{children:"Continue to SkullSystem, sign in and choose your gym."}),e.jsx("li",{children:"Review the access requested, then allow or deny the connection."})]})]})]})}function lp(){const t=r.useMemo(()=>ip(typeof window<"u"?window.location.hostname:null),[]),[s,n]=r.useState("");async function a(){const i=await Gn(t.mcpUrl);n(i?"MCP address copied.":`Copy this MCP address: ${t.mcpUrl}`)}return e.jsxs(Ye,{standardUI:!0,title:"Connect your AI",subtitle:"Use your own AI assistant with the SkullSystem access you already have.",activeTab:"settings",backTo:"/settings",suppressReadOnlyNotice:!0,children:[e.jsxs("section",{className:"member-panel-card member-ai-intro",children:[e.jsx("div",{className:"member-ai-intro-icon",children:e.jsx(V,{icon:or})}),e.jsxs("div",{children:[e.jsx("h2",{children:"Connect without passwords or API keys"}),e.jsx("p",{children:"Your AI opens the secure SkullSystem sign in page. You choose the gym and approve the requested access."})]})]}),e.jsxs("section",{className:"member-panel-card member-ai-safety",children:[e.jsx(V,{icon:cc}),e.jsxs("div",{children:[e.jsx("h2",{children:"Your normal permissions still apply"}),e.jsx("p",{children:"A member can manage their own bookings. Instructors and owners only receive the extra access already allowed on their SkullSystem account. Booking and cancellation actions still require confirmation."})]})]}),e.jsxs("section",{className:"member-panel-card member-ai-address-card",children:[e.jsx("span",{className:"member-ai-eyebrow",children:"Manual MCP address"}),e.jsx("code",{children:t.mcpUrl}),e.jsxs("button",{type:"button",className:"member-panel-action is-solid",onClick:()=>{a()},children:[e.jsx(V,{icon:kn})," Copy address"]})]}),e.jsx("div",{className:"member-ai-provider-list",children:rp.map(i=>e.jsx(op,{provider:i,mcpUrl:t.mcpUrl,onCopy:()=>{a()}},i.id))}),e.jsxs("section",{className:"member-panel-card member-ai-manage-card",children:[e.jsx(V,{icon:si}),e.jsxs("div",{children:[e.jsx("h2",{children:"Already connected?"}),e.jsx("p",{children:"Open your SkullSystem AI connections to review the connected gym, permissions and revoke access."}),e.jsx("button",{type:"button",className:"member-panel-action",onClick:()=>Ks(t.manageConnectionsUrl),children:"Manage existing connections"})]})]}),e.jsx(Dt,{isOpen:s!=="",message:s,duration:2600,onDidDismiss:()=>n("")})]})}function cp(t){return`${t.childFirstName} ${t.childLastName}`.trim()||"Child"}function up(t){if(!t)return"Date unavailable";const s=new Date(t);return Number.isNaN(s.getTime())?"Date unavailable":new Intl.DateTimeFormat(void 0,{weekday:"short",day:"numeric",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit"}).format(s)}function dp(){const[t,s]=r.useState(null),[n,a]=r.useState([]),[i,o]=r.useState("self"),[l,c]=r.useState(null),[u,d]=r.useState(!0),[h,m]=r.useState(!1),[f,b]=r.useState(""),p=r.useCallback(async(x,
2k)=>{d(!0),b("");try{const[j,I,S]=await Promise.all([T.me.getProfile({signal:k}),T.me.listDependants({signal:k}).catch(()=>[]),T.attendance.get(x==="self"?null:x,null,k)]);s(j),a(I),c(S)}catch(j){const I=re(j,"Unable to load attendance history.");I&&b(I)}finally{d(!1)}},[]);r.useEffect(()=>{const x=new AbortController;return p(i,x.signal),()=>x.abort()},[p,i]);const g=ka(t?.member??null),v=r.useMemo(()=>{const x=[{value:"self",label:"Me"}];return g&&n.forEach(k=>x.push({value:k.id,label:cp(k)})),x},[g,n]);r.useEffect(()=>{v.some(x=>x.value===i)||o("self")},[i,v]);const N=async()=>{if(!(!l?.nextCursor||h)){m(!0),b("");try{const x=await T.attendance.get(i==="self"?null:i,l.nextCursor);c(k=>k?{...k,history:[...k.history,...x.history],nextCursor:x.nextCursor}:x)}catch(x){b(re(x,"Unable to load more attendance history."))}finally{m(!1)}}};return e.jsxs(Ye,{title:"Attendance",subtitle:"Your complete class attendance record.",activeTab:"none",backTo:"/training",onRefresh:()=>p(i),children:[v.length>1?e.jsx(Hn,{value:i,className:"member-tab-switch",onIonChange:x=>{const k=`${x.detail.value??""}`;k&&o(k)},children:v.map(x=>e.jsx(Ps,{value:x.value,children:e.jsx("span",{children:x.label})},x.value))}):null,u?e.jsxs("div",{className:"member-panel-loading",children:[e.jsx(Te,{name:"crescent"}),e.jsx("span",{children:"Loading attendance history..."})]}):null,!u&&f?e.jsx("div",{className:"member-panel-error",children:f}):null,!u&&l?e.jsxs(e.Fragment,{children:[e.jsxs("section",{className:"member-panel-card",children:[e.jsxs("div",{className:"member-row-main",children:[e.jsxs("div",{children:[e.jsx("h2",{children:l.member.displayName}),e.jsx("p",{children:"All recorded attendance"})]}),e.jsx(V,{icon:uc})]}),e.jsxs("div",{className:"member-panel-list",children:[e.jsx("div",{className:"member-panel-row",children:e.jsxs("div",{className:"member-row-main",children:[e.jsx("strong",{children:"Classes attended"}),e.jsx("span",{className:"member-pill is-accent",children:l.classesAttended})]})}),l.programmes.map(x=>e.jsx("div",{className:"member-panel-row",children:e.jsxs("div",{className:"member-row-main",children:[e.jsx("strong",{children:x.programmeName}),e.jsx("span",{className:"member-pill",children:x.attendedCount})]})},x.programmeUuid??x.programmeName))]})]}),e.jsxs("section",{className:"member-panel-card",children:[e.jsx("h2",{children:"Attendance history"}),l.history.length===0?e.jsx("p",{children:"No counted attendance has been recorded yet."}):e.jsx("div",{className:"member-table-like",children:l.history.map(x=>e.jsxs("div",{className:"member-table-row",children:[e.jsxs("div",{children:[e.jsx("strong",{children:x.className}),e.jsxs("span",{children:[x.programmeName,x.locationName?` · ${x.locationName}`:""]})]}),e.jsxs("span",{children:[e.jsx(V,{icon:Ut})," ",up(x.startAt)]})]},x.attendanceUuid))}),l.nextCursor?e.jsx(vt,{expand:"block",fill:"outline",disabled:h,onClick:()=>{N()},children:h?"Loading...":"Load more"}):null,e.jsx("p",{children:"Counts include attended, checked in, and walk in classes, including attended trials. Cancelled classes, cancelled bookings, no shows, and removed records do not count."})]})]}):null]})}function mp(t){return t.source==="cash"?"Cash payment":t.paymentMethodLast4?`${gt(t.paymentMethodBrand,"Card")} ending ${t.paymentMethodLast4}`:null}function hp(){const{user:t}=Ge(),s=T.tenant.getTenantTimezone(),[n,a]=r.useState([]),[i,o]=r.useState(null),[l,c]=r.useState(!0),[u,d]=r.useState(!1),[h,m]=r.useState(""),f=t?.memberType==="child",b=r.useMemo(()=>`${t?.firstName??""} ${t?.lastName??""}`.trim().toLowerCase(),[t?.firstName,t?.lastName]),p=r.useCallback(async v=>{if(f){c(!1),a([]),o(null);return}c(!0),m("");try{const N=await T.membership.listBillingTransactions({limit:25,signal:v});a(N.items),o(N.nextCursor)}catch(N){const x=re(N,"Unable to load payment history.");x&&m(x)}finally{c(!1)}},[f]);r.useEffect(()=>{const v=new AbortController;return p(v.signal),()=>v.abort()},[p]);const g=r.useCallback(async()=>{if(!(!i||u)){d(!0),m("");try{const v=await T.membership.listBillingTransactions({cursor:i,limit:25});a(N=>{const x=new Set(N.map(k=>k.id));return[...N,...v.items.filter(k=>!x.has(k.id))]}),o(v.nextCursor)}catch(v){m(re(v,"Unable to load older payments."))}finally{d(!1)}}},[u,i]);return e.jsxs(Ye,{standardUI:!0,title:"Payment History",subtitle:"Review membership payments, refunds, and payment status.",activeTab:"account",backTo:"/account",onRefresh:p,refresherDisabled:u,children:[l?e.jsxs("div",{className:"member-panel-loading",children:[e.jsx(Te,{name:"crescent"}),e.jsx("span",{children:"Loading payment history..."})]}):null,!l&&h?e.jsx("div",{className:"member-panel-error",children:h}):null,!l&&!h?e.jsxs("section",{className:"member-section",children:[e.jsxs("div",{className:"member-row-main",children:[e.jsx("h2",{children:"Transactions"}),e.jsx(V,{icon:lc})]}),f?e.jsx("p",{children:"Payment history is managed by the person responsible for billing."}):null,!f&&n.length===0?e.jsx("p",{children:"No membership payments found."}):null,!f&&n.length>0?e.jsx("div",{className:"member-panel-list member-list--divided",children:n.map(v=>{const N=mp(v),x=`${v.memberName??""}`.trim(),k=!!x&&x.toLowerCase()!==b;return e.jsxs("div",{className:"member-panel-row",children:[e.jsxs("div",{className:"member-row-main",children:[e.jsx("strong",{children:v.description||"Membership payment"}),e.jsx("span",{className:"member-pill",children:gt(v.status)})]}),e.jsxs("p",{children:[gs(v.occurredAt,s)," · ",Vr(v.grossMinor,v.currency)]}),N?e.jsx("p",{children:N}):null,k?e.jsxs("p",{children:["Membership for ",x]}):null,v.refundedMinor>0?e.jsxs("p",{children:["Refunded: ",Vr(v.refundedMinor,v.currency)]}):null]},v.id)})}):null,!f&&i?e.jsx("div",{className:"member-list-actions member-list-actions-full",children:e.jsx("button",{type:"button",className:"member-btn is-neutral",disabled:u,onClick:()=>{g()},children:u?"Loading...":"Load older payments"})}):null]}):null]})}const su="skullsystem.member.device.preferences.v1",Bn={chatSoundEnabled:!0,chatVibrationEnabled:!0,chatPreviewTextEnabled:!0,chatClassUpdatesEnabled:!0,mutedChannelUuids:[]};function pp(t){return t&&typeof t=="object"?t:{}}function Tr(t,s){if(typeof t=="boolean")return t;if(typeof t=="number")return t===1;if(typeof t=="string"){const n=t.trim().toLowerCase();if(["1","true","yes","on"].includes(n))return!0;
2if(["0","false","no","off"].includes(n))return!1}return s}function bp(t){if(!Array.isArray(t))return[];const s=new Set;for(const n of t){if(typeof n!="string")continue;const a=n.trim().toLowerCase();a&&s.add(a)}return Array.from(s)}function nu(t){const s=pp(t);return{chatSoundEnabled:Tr(s.chatSoundEnabled,Bn.chatSoundEnabled),chatVibrationEnabled:Tr(s.chatVibrationEnabled,Bn.chatVibrationEnabled),chatPreviewTextEnabled:Tr(s.chatPreviewTextEnabled,Bn.chatPreviewTextEnabled),chatClassUpdatesEnabled:Tr(s.chatClassUpdatesEnabled,Bn.chatClassUpdatesEnabled),mutedChannelUuids:bp(s.mutedChannelUuids)}}function Xa(){if(typeof window>"u")return Bn;try{const t=window.localStorage.getItem(su);if(!t)return Bn;const s=JSON.parse(t);return nu(s)}catch{return Bn}}function au(t){const s=nu(t);if(typeof window<"u")try{window.localStorage.setItem(su,JSON.stringify(s))}catch{}return s}function ru(t,s){const n=t.trim().toLowerCase();return n?s.mutedChannelUuids.includes(n):!1}function fp(t,s,n){const a=t.trim().toLowerCase();if(!a)return n;const i=new Set(n.mutedChannelUuids);return s?i.add(a):i.delete(a),{...n,mutedChannelUuids:Array.from(i)}}function gp(t){const s=t.trim();if(!s)return"CH";const n=s.split(/\s+/).filter(Boolean),a=n[0]?.[0]||"C",i=n[1]?.[0]||n[0]?.[1]||"H";return`${a}${i}`.toUpperCase()}function xp(t){return t.length===0?null:t.reduce((s,n)=>!s||n.id>s.id?n:s,null)}function jp(t){if(!t)return"";const s=new Date(t);return Number.isNaN(s.getTime())?"":new Intl.DateTimeFormat("en-GB",{hour:"2-digit",minute:"2-digit"}).format(s)}function yp(){const t=tt(),[s,n]=r.useState([]),[a,i]=r.useState({}),[o,l]=r.useState(!0),[c,u]=r.useState(""),[d,h]=r.useState(Xa());r.useEffect(()=>{h(Xa())},[]);const m=r.useCallback(async b=>{l(!0),u(""),h(Xa());try{const p=await T.chat.listChannels({signal:b});n(p);const g=await Promise.all(p.map(async N=>{try{const x=await T.chat.listMessages(N.uuid,{signal:b}),k=xp(x.data);return[N.uuid,{messageText:k?.bodyText||N.description||"No messages yet.",createdAt:k?.createdAt??null}]}catch{return[N.uuid,{messageText:N.description||"No messages yet.",createdAt:null}]}})),v={};for(const[N,x]of g)v[N]=x;i(v)}catch(p){const g=re(p,"Unable to load messages.");g&&u(g)}finally{l(!1)}},[]);r.useEffect(()=>{const b=new AbortController;return m(b.signal),()=>{b.abort()}},[m]);const f=r.useMemo(()=>[...s].sort((b,p)=>{const g=a[b.uuid]?.createdAt||b.updatedAt||"",v=a[p.uuid]?.createdAt||p.updatedAt||"";return g===v?b.name.localeCompare(p.name):g>v?-1:1}),[s,a]);return e.jsxs(Ye,{standardUI:!0,title:"Messages",subtitle:"Conversations and class updates.",activeTab:"messages",onRefresh:m,children:[o?e.jsxs("div",{className:"member-panel-loading",children:[e.jsx(Te,{name:"crescent"}),e.jsx("span",{children:"Loading messages..."})]}):null,!o&&c?e.jsx("div",{className:"member-panel-error",children:c}):null,!o&&!c?e.jsx(e.Fragment,{children:f.length===0?e.jsxs("section",{className:"member-panel-card",children:[e.jsx("h2",{children:"No conversations yet"}),e.jsx("p",{children:"You will see message conversations here when enabled for your account."})]}):e.jsx("section",{className:"member-chat-list",children:f.map(b=>{const p=a[b.uuid],g=ru(b.uuid,d);return e.jsxs("button",{type:"button",className:"member-chat-row",onClick:()=>t.push(`/chat/${b.uuid}`),children:[e.jsx("span",{className:"member-chat-avatar",children:gp(b.name)}),e.jsxs("span",{className:"member-chat-body",children:[e.jsx("h3",{children:b.name}),e.jsx("p",{children:p?.messageText||b.description||"No messages yet."})]}),e.jsxs("span",{className:"member-chat-meta",children:[e.jsx("span",{children:jp(p?.createdAt||null)}),g?e.jsx("span",{className:"member-chat-unread",children:e.jsx(V,{icon:dc})}):b.unreadCount&&b.unreadCount>0?e.jsx("span",{className:"member-chat-unread",children:b.unreadCount}):e.jsx("span",{children:e.jsx(V,{icon:tm})})]})]},b.uuid)})})}):null]})}function Xn({pageKey:t,initialValue:s,enabled:n=!0,debounceMs:a=180,maxAgeMs:i=Qu}){const{isReady:o,user:l}=Ge(),[c,u]=r.useState(s),[d,h]=r.useState(!n),m=r.useRef(s),f=r.useRef(c),b=r.useRef(null);m.current=s,f.current=c;const p=Zu(),g=l?.id??"",v=r.useCallback(()=>{b.current!==null&&typeof window<"u"&&window.clearTimeout(b.current),b.current=null},[]),N=r.useCallback(async()=>{!n||!o||!p||!g||!d||await Ni.writePageState({tenantHost:p,userId:g,pageKey:t,value:f.current})},[n,d,o,t,p,g]),x=r.useCallback(async()=>{v(),u(m.current),!(!p||!g)&&await Ni.clearPageState({tenantHost:p,userId:g,pageKey:t})},[v,t,p,g]);return r.useEffect(()=>{if(!n){u(m.current),h(!0);return}if(!o)return;if(!p||!g){u(m.current),h(!0);return}let k=!0;return h(!1),Ni.readPageState({tenantHost:p,userId:g,pageKey:t,maxAgeMs:i}).then(j=>{k&&(u(j??m.current),h(!0))}),()=>{k=!1}},[n,o,i,t,p,g]),r.useEffect(()=>{if(!(!n||!d||!p||!g))return v(),b.current=window.setTimeout(()=>{N()},a),()=>{v()}},[v,a,n,N,d,p,g,c]),r.useEffect(()=>{if(!n||!d||!p||!g||typeof window>"u"||typeof document>"u")return;const k=()=>{document.visibilityState==="hidden"&&(v(),N())},j=()=>{v(),N()};return document.addEventListener("visibilitychange",k),window.addEventListener("pagehide",j),()=>{document.removeEventListener("visibilitychange",k),window.removeEventListener("pagehide",j)}},[v,n,N,d,p,g]),{value:c,setValue:u,isHydrated:d,clear:x,flush:N}}function vp(t){if(!t)return"";const s=new Date(t);return Number.isNaN(s.getTime())?"":new Intl.DateTimeFormat("en-GB",{day:"2-digit",month:"short",hour:"2-digit",minute:"2-digit"}).format(s)}function nl(t){return[...t].sort((s,n)=>s.id-n.id)}function Np(){const{channelUuid:t=""}=Qs(),[s,n]=r.useState(null),[a,i]=r.useState([]),o=Xn({pageKey:`chat-thread:${t}`,initialValue:{composerText:""}}),l=o.value.composerText,[c,u]=r.useState(!0),[d,h]=r.useState(!1),[m,f]=r.useState(""),[b,p]=r.useState(""),[g,v]=r.useState(()=>Xa()),N=r.useCallback(async I=>{u(!0),f("");try{const[S,M]=await Promise.all([T.chat.listChannels({signal:I}),T.chat.listMessages(t,{signal:I})]),y=S.find(P=>P.uuid.toLowerCase()===t.toLowerCase())??null;
2n(y),i(nl(M.data)),T.chat.markChannelRead(t).catch(()=>{})}catch(S){const M=re(S,"Unable to load this message conversation.");M&&f(M)}finally{u(!1)}},[t]);r.useEffect(()=>{const I=new AbortController;return N(I.signal),()=>{I.abort()}},[N]);const x=r.useMemo(()=>ru(t,g),[t,g]);async function k(){const I=l.trim();if(!(!I||d)){h(!0);try{const S=await T.chat.createMessage(t,I);S&&i(M=>nl([...M,S])),await o.clear(),T.chat.markChannelRead(t).catch(()=>{})}catch(S){p(re(S,"Unable to send message."))}finally{h(!1)}}}function j(){const I=fp(t,!x,g),S=au(I);v(S),p(x?"Conversation unmuted.":"Conversation muted on this device.")}return e.jsxs(Ye,{title:s?.name||"Conversation",subtitle:s?.description||"Message thread",activeTab:"messages",backTo:"/chat",onRefresh:N,refresherDisabled:d,headingAction:e.jsxs("button",{type:"button",className:"member-btn is-neutral",onClick:j,children:[e.jsx(V,{icon:x?sm:dc}),x?"Unmute":"Mute"]}),children:[c?e.jsxs("div",{className:"member-panel-loading",children:[e.jsx(Te,{name:"crescent"}),e.jsx("span",{children:"Loading messages..."})]}):null,!c&&m?e.jsx("div",{className:"member-panel-error",children:m}):null,!c&&!m?e.jsx("section",{className:"member-chat-thread",children:a.length===0?e.jsx("div",{className:"member-panel-empty",children:"No messages yet. Start the conversation."}):a.map(I=>e.jsx("div",{className:"member-chat-bubble-wrap",children:e.jsxs("div",{className:"member-chat-bubble",children:[e.jsx("p",{children:I.bodyText||"(message removed)"}),e.jsx("time",{children:vp(I.createdAt)})]})},I.id))}):null,!c&&!m?e.jsxs("div",{className:"member-chat-composer",children:[e.jsx("input",{className:"member-input",placeholder:"Write a message",value:l,onChange:I=>o.setValue({composerText:I.target.value}),onKeyDown:I=>{I.key==="Enter"&&(I.preventDefault(),k())}}),e.jsxs("button",{type:"button",className:"member-btn",disabled:d||l.trim()==="",onClick:()=>{k()},children:[e.jsx(V,{icon:mc}),"Send"]})]}):null,e.jsx(Dt,{isOpen:!!b,message:b,duration:2200,onDidDismiss:()=>p("")})]})}function ci({isOpen:t,title:s,actions:n,onClose:a}){return e.jsx(at,{isOpen:t,className:"member-household-sheet-modal",backdropDismiss:!0,onDidDismiss:a,keepContentsMounted:!0,children:e.jsxs("section",{className:"member-household-sheet","aria-label":s||"Member booking actions",children:[e.jsx("h2",{className:"member-household-sheet-title",children:s||"Choose member action"}),e.jsx("div",{className:"member-household-sheet-actions",children:n.map(i=>e.jsxs("button",{type:"button",className:`member-household-sheet-action ${i.mode==="cancel"?"is-cancel":i.mode==="select"?"is-select":"is-book"}${i.selected?" is-selected":""}${i.disabled?" is-disabled":""}`,disabled:i.disabled,"aria-pressed":i.mode==="select"?!!i.selected:void 0,onClick:()=>{i.disabled||(a(),i.onSelect())},children:[e.jsx("span",{children:i.label}),e.jsx(V,{icon:i.mode==="cancel"?zn:qr})]},i.key))}),e.jsxs("button",{type:"button",className:"member-household-sheet-close",onClick:a,children:[e.jsx(V,{icon:zn}),e.jsx("span",{children:"Cancel"})]})]})})}function iu(t){if(!t||!/^\/timetable(?:[/?#]|$)/.test(t)||t.includes("\\"))return"/timetable";const s=new URL(t,"https://member.invalid");return s.pathname==="/timetable"||s.pathname.startsWith("/timetable/")?`${s.pathname}${s.search}${s.hash}`:"/timetable"}function ou(t,s){if(!(t instanceof cn)||t.reason!=="profile_phone_required")return null;const a=t.payload?.error?.details?.profile_member_uuid;return typeof a!="string"||!a.trim()?null:`/profile?${new URLSearchParams({required:"phone",profile_member_uuid:a.trim(),next:iu(s)})}`}function kp(t,s,n){return t&&t===s?"self":n.includes(t)?t:null}function Dr(t){const s=`${t??""}`.trim().toLowerCase();return s==="required_forms"||s.includes("required form")||s.includes("required details")}function lu(t){return t instanceof cn&&(Dr(t.reason)||Dr(t.code)||Dr(t.message))}function cu(t,s,n){const a=new URLSearchParams({scope:"booking",next:t.startsWith("/timetable")?t:"/timetable"}),i=`${s??""}`.trim();i&&a.set("target_member_uuid",i);const o=`${n??""}`.trim();return i&&o&&a.set("target_display_name",o),`/forms?${a.toString()}`}function wp(t,s){if(!t)return"";const n=new Date(t);return Number.isNaN(n.getTime())?"":new Intl.DateTimeFormat("en-US",{timeZone:s,hour:"numeric",minute:"2-digit",hour12:!0}).format(n).replace(":00","").replace(/\s+/g,"").toLowerCase()}function uu(t,s,n){const a=`${t??""}`.trim(),i=wp(s,n);return a&&i?`${a} at ${i}`:a||(i?`your class at ${i}`:"your class")}function Cp(t){const s=t.payload&&typeof t.payload=="object"?t.payload:{},n=s.error&&typeof s.error=="object"?s.error:s;return n.details&&typeof n.details=="object"?n.details:{}}function Sp(t,s){if(typeof t!="string"||t.trim()==="")return"";const n=new Date(t);if(Number.isNaN(n.getTime()))return"";const a=new Intl.DateTimeFormat("en-GB",{timeZone:s,weekday:"long",day:"numeric",month:"long"}).format(n),i=new Intl.DateTimeFormat("en-GB",{timeZone:s,hour:"numeric",minute:"2-digit",hour12:!0}).format(n).toLowerCase();return`${a} at ${i}`}function du(t,s){if(!(t instanceof cn))return null;if(t.reason==="booking_not_released_yet"){const n=Sp(Cp(t).bookable_from,s);return{title:"Booking opens soon",message:n?`Booking is not open yet because we release places closer to the class. You can book from ${n}.`:"Booking is not open yet because we release places closer to the class. Please check again later.",color:"warning"}}return t.reason==="class_started"?{title:"Booking has closed",message:"This class has already started, so online booking is now closed. Please choose another class.",color:"warning"}:t.reason==="class_not_scheduled"||t.reason==="class_series_inactive"?{title:"Booking is not available",message:"This class is no longer on the schedule, so it cannot be booked. Please choose another class.",color:"warning"}:null}function er(t,s,n=""){const a=t.trim();return a?{title:n.trim(),message:a,color:s}:null}function mu(t){const s=uu(t.sessionTitle,t.sessionStartTime,t.timezone),n=`${t.targetName??""}`.trim();return{title:"",message:`${t.audience!=="self"&&n!==""?`${n} is booked for`:"You are booked for"} ${s}. See you soon.`,color:"success"}}function hu(t){const s=uu(t.sessionTitle,t.sessionStartTime,t.timezone),n=`${t.targetName??""}`.trim();
2return{title:"",message:t.audience!=="self"&&n!==""?`${n} has been removed from ${s}.`:`Your booking for ${s} has been cancelled.`,color:"success"}}function pu(t,s,n,a){const i=s?.bookDisabledReason??null,o=!!s?.canAttemptBooking,l=o?i:i??(n?null:a??"Booking is unavailable for this account."),c=Dr(i),u=!!s?.canBookForTarget;return{canBook:o||c||(t.targetType!=="self"||n)&&u,disabledReason:l}}function Pp(t){const s=new Map;for(const n of t)n.sessionId&&s.set(n.sessionId,n);return s}function ra(t){const s=t.trim();return s&&s.split(/\s+/)[0]||"Member"}function Rp(){const{sessionId:t=""}=Qs(),s=tt(),{user:n}=Ge(),a=Qe(n),i=n?.accessPolicy?.canBook!==!1,o=n?.accessPolicy?.bookingBlockedReason??null,l=T.tenant.getTenantTimezone(),[c,u]=r.useState(null),[d,h]=r.useState([]),[m,f]=r.useState(!0),[b,p]=r.useState(!1),[g,v]=r.useState(""),[N,x]=r.useState({open:!1,title:"",message:"",color:"medium"}),[k,j]=r.useState({open:!1,message:""}),I=r.useRef(null),[S,M]=r.useState(!1),y=r.useRef("");function P(K){K&&x({open:!0,title:K.title,message:K.message,color:K.color,actionLabel:K.actionLabel,actionUrl:K.actionUrl})}function U(K){I.current=K}function F(){const K=I.current;K&&(I.current=null,P(K))}const A=r.useCallback(async K=>{const ye=K?.silent??!1;ye||(f(!0),v(""));try{const de=await T.timetable.getTimetableSession(t);u(de);const O=de.startTime?Qa(new Date(de.startTime)):Qa(new Date),L=await T.bookingTargets.listBookingTargets({signal:K?.signal}),Z=Array.isArray(L.items)?L.items:[],[ce,me]=await Promise.all([T.bookings.listBookings({rangeStart:O,rangeEnd:O,limit:100},{signal:K?.signal}),Promise.all(Z.map(async xe=>{const G=await T.availability.listAvailability({rangeStart:O,rangeEnd:O,bookingForTargetId:xe.targetId},{signal:K?.signal});return[xe.targetId,Pp(G.items)]}))]),Ne=new Map;for(const xe of ce.data)xe.occurrenceUuid&&xe.personUuid&&Ne.set(`${xe.occurrenceUuid}:${xe.personUuid}`,xe);const ve=Z.map(xe=>{const G=de.status==="cancelled",J=me.find(([be])=>be===xe.targetId)?.[1].get(t),ke=Ne.get(`${t}:${xe.targetId}`)??null,Be=ke?.status??null,fe=Be==="booked"||Be==="checked_in",Ae=!G&&Be==="booked",lt=pu(xe,J,i,o);return{target:xe,canBook:!G&&!fe&<.canBook,isBooked:fe,canCancel:Ae,disabledReason:lt.disabledReason,bookingUuid:ke?.bookingUuid??null}});h(ve)}catch(de){const O=re(de,"We could not load this class. Please try again.");O&&v(O)}finally{ye||f(!1)}},[o,i,t]);r.useEffect(()=>{const K=new AbortController;return A({signal:K.signal}),()=>{K.abort()}},[A]),r.useEffect(()=>{if(!c?.startTime)return;const K=Qa(new Date(c.startTime)),ye=`${K}T00:00:00.000Z`,de=`${K}T23:59:59.999Z`;let O=!1;y.current="";const L=new AbortController,Z=me=>new Promise(Ne=>{window.setTimeout(Ne,me)});return(async()=>{for(;!O&&!L.signal.aborted;)try{const me=y.current.trim()!=="",Ne=await T.timetable.waitForTimetablePush({rangeStart:ye,rangeEnd:de,cursor:y.current||null,timeoutSec:20},{signal:L.signal});if(O||L.signal.aborted)return;typeof Ne.cursor=="string"&&Ne.cursor.trim()!==""&&(y.current=Ne.cursor.trim()),me&&Ne.changed&&Ne.events.some(xe=>xe.occurrenceUuid===t)&&await A({signal:L.signal,silent:!0})}catch(me){if(me instanceof DOMException&&me.name==="AbortError"||me?.name==="AbortError"||O||L.signal.aborted)return;await Z(1500)}})(),()=>{O=!0,L.abort()}},[A,c?.startTime,t]);const D=r.useMemo(()=>d.filter(K=>K.canBook||K.isBooked&&K.canCancel&&!!K.bookingUuid),[d]),R=D[0]??null,w=c?.lessonPlanUuid?.trim()||"";function _(){w&&s.push(`/staff-tools/lesson-plans?version=${encodeURIComponent(w)}`)}async function W(K,ye,de){if(!b){p(!0),j({open:!0,message:"Booking..."});try{await T.bookings.createBooking({classOccurrenceUuid:t,forMemberUuid:K}),sc(),await A({silent:!0}),U(mu({sessionTitle:c?.title??null,sessionStartTime:c?.startTime??null,timezone:l,targetName:de,audience:ye}))}catch(O){const L=ou(O,`/timetable/${encodeURIComponent(t)}`);if(L){s.push(L);return}if(lu(O)){s.push(cu(`/timetable/${encodeURIComponent(t)}`,ye==="child"?K:null,ye==="child"?d.find(me=>me.target.targetId===K)?.target.displayName??de:null));return}const Z=Cc(O),ce=du(O,l);U(Z?{title:"Programme access",message:Z.message,color:"warning",actionLabel:Z.label,actionUrl:Z.url}:ce??er(re(O,"We could not book this class. Please try again."),"danger"))}finally{j({open:!1,message:""}),p(!1)}}}async function H(K,ye,de){if(!b){p(!0),j({open:!0,message:"Cancelling..."});try{await T.bookings.cancelBooking(K),await A({silent:!0}),U(hu({sessionTitle:c?.title??null,sessionStartTime:c?.startTime??null,timezone:l,targetName:de,audience:ye}))}catch(O){U(er(re(O,"We could not cancel this booking. Please try again."),"danger"))}finally{j({open:!1,message:""}),p(!1)}}}const ne=r.useMemo(()=>D.map(K=>({key:K.target.targetId,label:ra(K.target.displayName).toUpperCase(),mode:K.isBooked?"cancel":"book",disabled:b||!K.canBook&&!K.canCancel,onSelect:()=>{if(K.isBooked&&K.bookingUuid){H(K.bookingUuid,K.target.targetType,ra(K.target.displayName));return}K.canBook&&W(K.target.targetId,K.target.targetType,ra(K.target.displayName))}})),[D,b]);return e.jsxs(Ye,{title:c?.workshop?.title||c?.title||"Class details",subtitle:c?gs(c.startTime,l):"Loading class details...",activeTab:"classes",backTo:"/timetable",backToRoot:!0,hideBottomNav:S,onRefresh:()=>A(),refresherDisabled:b,children:[m?e.jsxs("div",{className:"member-panel-loading",children:[e.jsx(Te,{name:"crescent"}),e.jsx("span",{children:"Loading class details..."})]}):null,!m&&g?e.jsx("div",{className:"member-panel-error",children:g}):null,!m&&!g&&c?e.jsxs(e.Fragment,{children:[c.status==="cancelled"?e.jsxs("section",{className:"member-panel-card member-cancelled-class-notice",role:"status",children:[e.jsx("h2",{children:"Class cancelled"}),e.jsx("p",{children:e.jsx("strong",{children:"Cancellation reason"})}),e.jsx("p",{children:c.cancellationReason||"No reason was provided."})]}):null,e.jsxs("section",{className:"member-panel-card",children:[e.jsxs("div",{className:"member-row-main",children:[e.jsx("strong",{children:ba(c.startTime,c.endTime,l)}),e.jsxs("span",{className:"member-pill is-accent",children:[c.spotsRemaining??0," spots"]})]}),e.jsxs("div",{className:"member-panel-list",children:[e.jsxs("div",{className:"member-panel-row",children:[e.jsx("div",{className:"member-row-main",children:e.jsxs("strong",{children:[e.jsx(V,{icon:Ut})," Programme"]})}),e.jsx("p",{children:c.programName||"General class"})]}),e.jsxs("div",{className:"member-panel-row",children:[e.jsx("div",{className:"member-row-main",children:e.jsxs("strong",{children:[e.jsx(V,{icon:qs})," Instructor"]})}),e.jsx("p",{children:c.instructorName||"TBC"})]}),e.jsxs("div",{className:"member-panel-row",children:[e.jsx("div",{className:"member-row-main",children:e.jsxs("strong",{children:[e.jsx(V,{icon:ni})," Location"]})}),e.jsx("p",{children:c.locationName||"Main gym floor"})]}),e.jsxs("div",{className:"member-panel-row",children:[e.jsx("div",{className:"member-row-main",children:e.jsxs("strong",{children:[e.jsx(V,{icon:oc})," Cancellation policy"]})}),e.jsx("p",{children:c.eligibilityMessage||"Cancellation rules apply based on your membership."})]})]}),c.workshop&&!a?e.jsx("div",{className:"member-list-actions",children:e.jsxs("button",{type:"button",className:"member-btn is-solid",onClick:()=>s.push(`/events/details/${encodeURIComponent(c.workshop?.slug||"")}`),children:["Register for this ",c.workshop.eventType]})}):null]}),e.jsxs("section",{className:"member-panel-card",children:[e.jsx("h2",{children:"Description"}),e.jsx("p",{children:c.description||"No class description provided yet."}),Array.isArray(c.whatToBring)&&c.whatToBring.length>0?e.jsx("div",{className:"member-panel-list",children:c.whatToBring.map(K=>e.jsx("div",{className:"member-panel-row",children:e.jsx("p",{children:K})},K))}):null]}),a&&w?e.jsxs("section",{className:"member-panel-card",children:[e.jsx("h2",{children:"Lesson plan"}),e.jsxs("div",{className:"member-row-main",children:[e.jsx("strong",{children:c.lessonPlanTitle||"Linked lesson plan version"}),e.jsx("span",{className:"member-pill is-accent",children:"Linked"})]}),e.jsx("p",{children:"This class is linked to a lesson plan version. Open it to review the blocks, curriculum, and history before closeout."}),e.jsx("div",{className:"member-list-actions",children:e.jsx("button",{type:"button",className:"member-btn is-solid",onClick:_,children:"Open lesson plan"})})]}):null,a?e.jsxs("section",{className:"member-panel-card",children:[e.jsx("h2",{children:"Instructor actions"}),e.jsxs("div",{className:"member-panel-list",children:[e.jsxs("div",{className:"member-panel-row",children:[e.jsx("div",{className:"member-row-main",children:e.jsx("strong",{children:"Roster and closeout"})}),e.jsx("p",{children:"Open the staff workspace for this class to review attendance, show conversion QR codes, and close the class."})]}),e.jsxs("div",{className:"member-panel-row",children:[e.jsx("div",{className:"member-row-main",children:e.jsx("strong",{children:"Class cancellation"})}),e.jsx("p",{children:"Use the class workspace to cancel this class and record the reason shown to members."})]})]}),e.jsx("div",{className:"member-list-actions",children:e.jsx("button",{type:"button",className:"member-btn is-solid",onClick:()=>
2s.push(`/instructor/classes?occurrence=${encodeURIComponent(t)}`),children:"Manage roster"})})]}):null,c.status!=="cancelled"?e.jsxs("section",{className:"member-panel-card",children:[e.jsx("h2",{children:"Booking status"}),d.length===0?e.jsx("p",{children:"No eligible booking targets found."}):null,d.length>0?e.jsx("div",{className:"member-panel-list",children:d.map(K=>e.jsxs("div",{className:"member-panel-row",children:[e.jsxs("div",{className:"member-row-main",children:[e.jsx("strong",{children:ra(K.target.displayName)}),e.jsx("span",{className:`member-pill${K.isBooked?" is-accent":""}`,children:K.isBooked?"Booked":"Not booked"})]}),K.disabledReason?e.jsx("p",{children:K.disabledReason}):null]},K.target.targetId))}):null,e.jsx("div",{className:"member-list-actions",children:D.length>1?e.jsx("button",{type:"button",className:"member-btn",onClick:()=>M(!0),disabled:b,children:"BOOK / CANCEL"}):R?e.jsx("button",{type:"button",className:`member-btn${R.isBooked?" is-solid":""}`,disabled:b||!R.canBook&&!R.canCancel,onClick:()=>{if(R.isBooked&&R.bookingUuid){H(R.bookingUuid,R.target.targetType,ra(R.target.displayName));return}R.canBook&&W(R.target.targetId,R.target.targetType,ra(R.target.displayName))},children:R.isBooked?e.jsxs(e.Fragment,{children:["CANCEL",e.jsx(V,{icon:zn})]}):e.jsxs(e.Fragment,{children:["BOOK",e.jsx(V,{icon:qr})]})}):null})]}):null]}):null,e.jsx(ci,{isOpen:S,title:c?.title||"Choose member action",actions:ne,onClose:()=>M(!1)}),e.jsx(Xl,{isOpen:k.open,message:k.message,spinner:"crescent",showBackdrop:!0,cssClass:"member-booking-loading",onDidDismiss:F}),e.jsx(Vn,{isOpen:N.open,header:N.title||void 0,message:N.message,cssClass:`member-status-alert member-booking-result-alert member-status-alert-${N.color}${N.title?"":" is-titleless"}`,buttons:[...N.actionUrl?[{text:N.actionLabel||"Upgrade",handler:()=>{window.location.assign(N.actionUrl||"/app/memberships")}}]:[],{text:"Close",role:"cancel"}],onDidDismiss:()=>x(K=>({...K,open:!1}))})]})}function Tp({value:t,label:s}){const[n,a]=r.useState(""),[i,o]=r.useState(!1);return r.useEffect(()=>{let l=!0;return a(""),o(!1),ir(async()=>{const{default:c}=await import("./browser-CHqGei6v.js").then(u=>u.b);return{default:c}},__vite__mapDeps([0,1,2,3,4])).then(({default:c})=>c.toDataURL(t,{width:280,margin:2,errorCorrectionLevel:"M",color:{dark:"#111827",light:"#ffffff"}})).then(c=>{l&&a(c)}).catch(()=>{l&&o(!0)}),()=>{l=!1}},[t]),i?e.jsx("p",{className:"member-panel-error",children:"QR code is unavailable right now."}):n?e.jsx("img",{className:"member-community-group-qr",src:n,alt:`QR code for ${s}`}):e.jsx("p",{className:"member-panel-help",children:"Generating QR code..."})}const _p={pageTitle:"Community groups",eligibleCount:0,groups:[],promptCandidate:null};function Mp(){const[t,s]=r.useState(_p),[n,a]=r.useState(!0),[i,o]=r.useState(""),[l,c]=r.useState(""),[u,d]=r.useState(""),h=r.useCallback(async f=>{a(!0),o("");try{s(await T.me.getCommunityGroups({signal:f}))}catch(b){const p=re(b,"Unable to load Community groups.");p&&o(p)}finally{f?.aborted||a(!1)}},[]);r.useEffect(()=>{const f=new AbortController;return h(f.signal),()=>f.abort()},[h]);async function m(f,b){const p=await Gn(b);c(p?`${f} link copied.`:"Unable to copy this link on this device.")}return e.jsxs(Ye,{title:t.pageTitle,subtitle:"Private groups available to your account.",activeTab:"none",backTo:"/events",onRefresh:h,children:[n?e.jsxs("div",{className:"member-panel-loading",children:[e.jsx(Te,{name:"crescent"}),e.jsx("span",{children:"Loading Community groups..."})]}):null,!n&&i?e.jsx("div",{className:"member-panel-error",children:i}):null,!n&&!i&&t.groups.length===0?e.jsx("section",{className:"member-panel-card",children:e.jsx("p",{children:"No community groups are available for your account."})}):null,!n&&!i&&t.groups.length>0?e.jsx("div",{className:"member-panel-list member-community-groups-list",children:t.groups.map(f=>e.jsxs("article",{className:"member-panel-row member-community-group-card",children:[e.jsxs("div",{className:"member-community-group-name",children:[e.jsx(vc,{iconKey:f.icon}),e.jsx("strong",{children:f.name})]}),f.description?e.jsx("p",{className:"member-community-group-description",children:f.description}):null,e.jsxs("div",{className:"member-list-actions member-community-group-link-actions",children:[e.jsxs("button",{type:"button",className:"member-btn",onClick:()=>Ks(f.inviteUrl),children:[e.jsx(V,{icon:Vs}),"Open"]}),e.jsxs("button",{type:"button",className:"member-btn is-neutral",onClick:()=>{m(f.name,f.inviteUrl)},children:[e.jsx(V,{icon:kn}),"Copy link"]}),e.jsxs("button",{type:"button",className:"member-btn is-neutral","aria-label":`QR Code for ${f.name}`,"aria-expanded":u===f.uuid,onClick:()=>d(b=>b===f.uuid?"":f.uuid),children:[e.jsx(V,{icon:ja}),"QR Code"]})]}),u===f.uuid?e.jsx("div",{className:"member-community-group-qr-panel",children:e.jsx(Tp,{value:f.inviteUrl,label:f.name})}):null]},f.uuid))}):null,e.jsx(Dt,{isOpen:!!l,message:l,duration:2400,onDidDismiss:()=>c("")})]})}function mr(t){return e.jsx(Cn,{className:"member-auth-route-page",children:e.jsx(Qd,{...t})})}function Up(){const t=tt(),[s,n]=r.useState(""),[a,i]=r.useState(""),[o,l]=r.useState(""),[c,u]=r.useState(""),[d,h]=r.useState(!1),m=()=>s.trim()?(i(""),!0):(i("Email or username is required."),!1),f=async b=>{if(b.preventDefault(),l(""),u(""),!!m())try{h(!0);const p=await T.auth.requestPasswordReset(s.trim());u(p)}catch(p){p instanceof cn||p instanceof Error?l(p.message):l("Unable to start password reset right now.")}finally{h(!1)}};return e.jsxs(mr,{children:[e.jsxs("form",{onSubmit:f,noValidate:!0,className:"member-login-form",children:[e.jsxs("label",{className:"member-login-field",children:[e.jsx("span",{className:"member-login-label",children:"Email"}),e.jsx("input",{type:"text",className:"member-login-input",autoComplete:"username",value:s,onChange:b=>n(b.target.value),disabled:d})]}),a?e.jsx("p",{className:"member-login-error",children:a}):null,o?e.jsx("p",{className:"member-login-error",children:o}):null,c?e.jsx("p",{className:"member-login-status",children:c}):null,e.jsx(vt,{className:"member-login-submit",expand:"block",type:"submit",disabled:d,children:d?"SENDING...":"SEND RESET LINK"})]}),e.jsx("button",{type:"button",className:"member-login-forgot",onClick:()=>t.replace("/login"),disabled:d,children:"Back to sign in"})]})}function Ep(){const t=tt(),s=mt(),{user:n}=Ge(),a=r.useMemo(()=>new URLSearchParams(s.search),[s.search]),i=`${a.get("target_member_uuid")??a.get("target")??""}`.trim(),o=`${a.get("target_display_name")??""}`.trim(),l=`${a.get("form")??""}`.trim(),c=`${a.get("next")??""}`.trim(),u=a.get("scope")==="required",d=s.pathname==="/forms",[h,m]=r.useState(null),[f,b]=r.useState(""),[p,g]=r.useState(null),[v,N]=r.useState(!0),[x,k]=r.useState(!1),[j,I]=r.useState(!1),[S,M]=r.useState(""),[y,P]=r.useState(""),[U,F]=r.useState(""),A=n?.accessPolicy?.memberExperienceMode==="booking_beta",D=r.useMemo(()=>{const L=jm(h?.items??[],{requiredOnly:u});return ym(L)},[h?.items,u]),R=r.useMemo(()=>D.filter(L=>!L.isComplete),[D]),w=r.useMemo(()=>D.filter(L=>L.isComplete),[D]),_=D.find(L=>En(L)===f)??null,W=h===null&&(v||S===""),H=r.useCallback(async L=>{let Z;if(i){const[ce,me]=await Promise.all([T.me.listForms({targetMemberUuid:i,signal:L}),T.bookingTargets.listBookingTargets({signal:L})]),Ne=new Map((me.items??[]).map(ve=>[ve.targetId,ve.displayName]));o&&Ne.set(i,o),Z=vm(ce,Ne,i)}else if(!A)Z=await T.me.listForms({signal:L});else{const ce=await T.bookingTargets.listBookingTargets({signal:L}),me=new Map((ce.items??[]).map(J=>[J.targetId,J.displayName])),Ne=[void 0,...Array.from(new Set((ce.items??[]).map(J=>
2J.targetId).filter(Boolean)))],xe=(await Promise.allSettled(Ne.map(J=>T.me.listForms({targetMemberUuid:J,signal:L})))).flatMap(J=>J.status==="fulfilled"?[J.value]:[]),G=Nm(xe,me);if(!G)throw new Error("We could not load your household forms.");Z=G}return m(Z),b(ce=>ce&&Z.items.some(me=>En(me)===ce)?ce:l&&Z.items.some(me=>En(me)===l)?l:""),Z},[A,l,o,i]),ne=r.useCallback(async L=>{const ce=(await T.me.getProfile({signal:L})).member;g(ce?{firstName:ce.firstName,lastName:ce.lastName,phone:ce.phone}:null)},[]),K=r.useCallback(async L=>{N(!0),M("");try{await Promise.all([H(L),ne(L).catch(()=>{g(null)})])}catch(Z){if(L?.aborted)return;M(re(Z,"We could not load your forms. Please try again."))}finally{L?.aborted||N(!1)}},[H,ne]);r.useEffect(()=>{if(!d)return;const L=new AbortController;return K(L.signal),()=>L.abort()},[d,K]),r.useEffect(()=>{if(!d||!l||f!==l)return;const L=new URLSearchParams(s.search);L.delete("form"),t.replace({pathname:s.pathname,search:L.toString()?`?${L.toString()}`:"",hash:s.hash})},[t,d,s.hash,s.pathname,s.search,l,f]);async function ye(L){const[Z]=await Promise.all([H(),T.auth.fetchCurrentUser().catch(()=>null)]);F(L),!Z.hasIncompleteRequiredForms&&c.startsWith("/timetable")&&t.replace(c)}async function de(L,Z){k(!0),P("");try{await T.me.submitForm(L.attachmentUuid,{targetMemberUuid:L.targetMemberUuid||h?.targetMemberUuid||i||void 0,contextUuid:Wo(L),answers:Z.answers,signerName:Z.signerName,signerRole:Fo(L),consentChecked:Z.consentChecked}),b(""),await ye("Form submitted.")}catch(ce){P(re(ce,"We could not send this form. Please try again."))}finally{k(!1)}}async function O(L,Z){I(!0),P("");try{await T.me.saveFormDraft(L.attachmentUuid,{targetMemberUuid:L.targetMemberUuid||h?.targetMemberUuid||i||void 0,contextUuid:Wo(L),answers:Z.answers,signerName:Z.signerName,signerRole:Fo(L),consentChecked:Z.consentChecked}),b(""),await ye("Draft saved.")}catch(ce){P(re(ce,"We could not save this form. Please try again."))}finally{I(!1)}}return e.jsxs(Ye,{standardUI:!0,title:"Forms & Questionnaires",subtitle:u?"Complete the required forms below before booking.":"View completed forms and fill in any optional or required forms.",activeTab:"account",suppressReadOnlyNotice:!0,backTo:c||(A?"/timetable":"/account"),onRefresh:K,refresherDisabled:x||j,formsBannerState:null,children:[W?e.jsxs("div",{className:"member-panel-loading",children:[e.jsx(Te,{name:"crescent"}),e.jsx("span",{children:"Loading forms..."})]}):null,!W&&S?e.jsx("div",{className:"member-panel-error",children:S}):null,!W&&!S&&h!==null&&D.length===0?e.jsx("div",{className:"member-panel-empty",children:u?"You have no required forms to complete. You are ready to book a class.":"No forms or questionnaires are available for your account."}):null,!W&&!S&&h!==null&&D.length>0?e.jsxs("div",{className:"member-forms-layout",children:[R.length>0?e.jsxs("section",{className:"member-forms-section",children:[e.jsx("h2",{children:"To complete"}),e.jsx("div",{className:"member-forms-card-list",children:R.map(L=>e.jsxs("article",{className:"member-form-card",children:[e.jsxs("div",{className:"member-form-card-copy",children:[e.jsx("strong",{children:L.name}),e.jsx("span",{children:`For ${Ci(L)}`}),e.jsx("span",{className:`member-form-requirement ${wm(L)}`,children:km(L)})]}),e.jsx("button",{type:"button",className:"member-form-card-action",onClick:()=>{b(En(L)),P("")},children:L.submissionStatus==="draft"?"Continue form":"Complete form"})]},En(L)))})]}):null,w.length>0?e.jsxs("section",{className:"member-forms-section",children:[e.jsx("h2",{children:"Completed"}),e.jsx("div",{className:"member-forms-card-list",children:w.map(L=>e.jsxs("article",{className:"member-form-card is-complete",children:[e.jsxs("div",{className:"member-form-card-copy",children:[e.jsx("strong",{children:L.name}),e.jsx("span",{children:`For ${Ci(L)}`}),e.jsx("span",{className:"member-form-requirement is-complete",children:"Completed"})]}),e.jsx("button",{type:"button",className:"member-form-card-action is-secondary",onClick:()=>{b(En(L)),P("")},children:"View form"})]},En(L)))})]}):null]}):null,e.jsx(at,{isOpen:!!_,onDidDismiss:()=>{b(""),P("")},children:e.jsxs("div",{className:"member-ui member-modal-sheet",children:[e.jsxs("div",{className:"member-modal-header member-form-modal-header",children:[e.jsx("h2",{children:_?.name??"Form"}),_?.description?e.jsx("p",{className:"member-form-modal-description",children:_.description}):null,_?e.jsx("p",{className:"member-form-modal-target",children:`For ${Ci(_)}`}):null]}),_?e.jsx(Om,{form:_,profileMember:p,user:n,isSubmitting:x,isSavingDraft:j,errorMessage:y,submitLabel:_.isComplete?"Update submission":"Submit form",saveDraftLabel:"Finish later",cancelLabel:"Close",onCancel:()=>{b(""),P("")},onSubmit:L=>de(_,L),onSaveDraft:_.isComplete?null:L=>O(_,L)}):null]})}),e.jsx(Dt,{isOpen:!!U,message:U,duration:2500,onDidDismiss:()=>F("")})]})}function Ap(t){return`${t.childFirstName} ${t.childLastName}`.trim()||"Child profile"}function Dp(){const t=tt(),[s,n]=r.useState(null),[a,i]=r.useState([]),[o,l]=r.useState(!0),[c,u]=r.useState(!1),[d,h]=r.useState(""),[m,f]=r.useState(""),[b,p]=r.useState(null),[g,v]=r.useState(""),[N,x]=r.useState(""),[k,j]=r.useState(""),I=s?.member??null,S=I?.household??null,M=ka(I),y=r.useCallback(async D=>{const[R,w]=await Promise.all([T.me.getProfile({signal:D}),T.me.listDependants({signal:D}).catch(()=>[])]);n(R),i(w)},[]),P=r.useCallback(async D=>{l(!0),h("");try{await y(D)}catch(R){const w=re(R,"Unable to load household data.");w&&h(w)}finally{l(!1)}},[y]);r.useEffect(()=>{const D=new AbortController;return P(D.signal),()=>{D.abort()}},[P]);const U=r.useMemo(()=>
2{if(!S)return"Not set";const D=S.members.find(R=>R.isPrimaryPayer);return D?`${D.firstName} ${D.lastName}`.trim()||"Primary payer":"Not set"},[S]);async function F(){if(!(!M||c)){if(!g.trim()||!N.trim()||!k.trim()){f("First name, last name, and date of birth are required.");return}u(!0);try{await T.me.createDependant({childFirstName:g.trim(),childLastName:N.trim(),dob:k}),v(""),x(""),j(""),await y(),f("Child profile linked to household.")}catch(D){f(re(D,"Unable to add child profile."))}finally{u(!1)}}}async function A(){if(!(!b||c)){u(!0);try{await T.me.deleteDependant(b),await y(),f("Child profile removed from household.")}catch(D){f(re(D,"Unable to remove child profile."))}finally{u(!1),p(null)}}}return e.jsxs(Ye,{standardUI:!0,title:"Household",subtitle:"Manage linked household members.",activeTab:"account",backTo:"/account",onRefresh:P,refresherDisabled:c,children:[o?e.jsxs("div",{className:"member-panel-loading",children:[e.jsx(Te,{name:"crescent"}),e.jsx("span",{children:"Loading household..."})]}):null,!o&&d?e.jsx("div",{className:"member-panel-error",children:d}):null,!o&&!d?e.jsxs(e.Fragment,{children:[e.jsxs("section",{className:"member-panel-card",children:[e.jsxs("div",{className:"member-row-main",children:[e.jsx("h2",{children:"Household summary"}),e.jsx(V,{icon:As})]}),e.jsxs("p",{children:["Primary payer: ",U]}),e.jsxs("p",{children:["Members linked: ",S?.members.length||1]}),M?null:e.jsx("p",{children:"This account is not configured as the household main payer. Household management actions are available only to the payer/parent account."})]}),e.jsxs("section",{className:"member-panel-card",children:[e.jsx("h2",{children:"Linked members"}),S&&S.members.length>0?e.jsx("div",{className:"member-panel-list member-list--divided",children:S.members.map(D=>e.jsxs("div",{className:"member-panel-row",children:[e.jsxs("div",{className:"member-row-main",children:[e.jsxs("strong",{children:[D.firstName," ",D.lastName]}),e.jsx("span",{className:`member-pill${D.isPrimaryPayer?" is-accent":""}`,children:D.isPrimaryPayer?"Primary payer":gt(D.memberType,"Member")})]}),e.jsx("p",{children:D.email}),e.jsxs("p",{children:["Status: ",gt(D.status)]})]},D.uuid))}):e.jsx("p",{children:"No linked household members found."})]}),e.jsxs("section",{className:"member-panel-card",children:[e.jsx("h2",{children:"Child memberships (high level)"}),a.length===0?e.jsx("p",{children:"No child profiles linked to this account."}):null,a.length>0?e.jsx("div",{className:"member-panel-list member-list--divided",children:a.map(D=>e.jsxs("div",{className:"member-panel-row",children:[e.jsxs("div",{className:"member-row-main",children:[e.jsx("strong",{children:Ap(D)}),e.jsx("span",{className:"member-pill",children:gt(D.membershipStatus)})]}),e.jsxs("p",{children:["Type: ",gt(D.memberType,"Child")]}),e.jsxs("p",{children:["Status: ",gt(D.status,"Active")]}),M?e.jsxs("div",{className:"member-list-actions",children:[e.jsx("button",{type:"button",className:"member-btn is-neutral",onClick:()=>t.push("/profile"),children:"Manage profile"}),e.jsx("button",{type:"button",className:"member-btn is-neutral",onClick:()=>p(D.id),children:"Remove child"})]}):null]},D.id))}):null]}),M?e.jsxs("section",{className:"member-panel-card",children:[e.jsxs("div",{className:"member-row-main",children:[e.jsx("h2",{children:"Add child"}),e.jsx(V,{icon:nm})]}),e.jsxs("div",{className:"member-input-group",children:[e.jsxs("label",{className:"member-input-label",children:[e.jsx("span",{children:"First name"}),e.jsx("input",{className:"member-input",value:g,onChange:D=>v(D.target.value)})]}),e.jsxs("label",{className:"member-input-label",children:[e.jsx("span",{children:"Last name"}),e.jsx("input",{className:"member-input",value:N,onChange:D=>x(D.target.value)})]}),e.jsxs("label",{className:"member-input-label",children:[e.jsx("span",{children:"Date of birth"}),e.jsx("input",{className:"member-input",type:"date",value:k,onChange:D=>j(D.target.value)})]})]}),e.jsx("div",{className:"member-list-actions",children:e.jsx("button",{type:"button",className:"member-btn",disabled:c,onClick:()=>{F()},children:"Add child"})})]}):null]}):null,e.jsx(Vn,{isOpen:b!==null,header:"Remove child profile",message:"This will unlink the child from your household profile.",buttons:[{text:"Cancel",role:"cancel",handler:()=>p(null)},{text:"Remove",role:"destructive",handler:()=>{A()}}],onDidDismiss:()=>p(null)}),e.jsx(Dt,{isOpen:!!m,message:m,duration:2200,onDidDismiss:()=>f("")})]})}function ui({isOpen:t,title:s,subtitle:n,onClose:a,children:i,canDismiss:o=!0}){const l=r.useId(),{appearance:c,themeMode:u,tenantName:d}=ln(),h=u==="dark"?c.headerLogoDarkUrl||c.headerLogoLightUrl:c.headerLogoLightUrl||c.headerLogoDarkUrl,m=u==="dark"?c.headerLogoDarkUrl?c.headerLogoDarkImage:c.headerLogoLightImage:c.headerLogoLightUrl?c.headerLogoLightImage:c.headerLogoDarkImage;return e.jsx(at,{isOpen:t,canDismiss:o,onWillDismiss:a,className:"member-staff-modal","aria-label":s,children:e.jsxs("div",{className:"member-modal-sheet member-staff-sheet",children:[e.jsxs("header",{className:"member-staff-modal-header",children:[e.jsx("div",{className:"member-staff-modal-brand",children:h?e.jsx(ys,{image:m,fallbackUrl:h,alt:d||"School logo",sizes:"160px",width:160,height:80}):e.jsx("span",{children:d||"SkullSystem"})}),e.jsx("button",{type:"button",className:"member-btn is-neutral member-btn-compact",disabled:!o,onClick:a,children:"Close"}),e.jsxs("div",{className:"member-modal-header",children:[e.jsx("h2",{id:l,children:s}),n?e.jsx("p",{children:n}):null]})]}),e.jsx("div",{className:"member-staff-modal-body",children:i})]})},s)}function Lp({row:t,occurrence:s,timezone:n,onClose:a,onSaved:i}){const[o,l]=r.useState([]),[c,u]=r.useState(""),[d,h]=r.useState(0),[m,f]=r.useState(0),[b,p]=r.useState(!0),[g,v]=r.useState(!1),[N,x]=r.useState(""),k=r.useRef(!1);r.useEffect(()=>{let y=!0;p(!0),l([]),u(""),x("");const P=new Date;P.setUTCDate(P.getUTCDate()+d*35);const U=new Date(P);return U.setUTCDate(U.getUTCDate()+34),T.instructor.listOccurrences({dateRange:`${P.toISOString().slice(0,10)},${U.toISOString().slice(0,10)}`,status:"scheduled"}).then(F=>{y&&l(F.filter(A=>A.occurrenceUuid!==s.occurrenceUuid&&!A.isEvent&&A.status==="scheduled"&&Date.parse(A.startAt||"")>Date.now()).sort((A,D)=>Date.parse(A.startAt||"")-Date.parse(D.startAt||"")))}).catch(F=>{y&&x(re(F,"Unable to load class times.")||"Unable to load class times.")}).finally(()=>{y&&p(!1)}),()=>{y=!1}},[d,m,s.occurrenceUuid]);const j=y=>{const P=new Intl.DateTimeFormat("en-GB",{timeZone:n,weekday:"long",day:"numeric",month:"long"}).formatToParts(new Date(y)),U=D=>P.find(R=>R.type===D)?.value||"",F=Number(U("day")),A=F%100>=11&&F%100<=13?"th":{1:"st",2:"nd",3:"rd"}[F%10]||"th";return`${U("weekday")} ${F}${A} ${U("month")}`},I=o.reduce((y,P)=>{const U=j(P.startAt||"");return(y[U]||=[]).push(P),y},{}),S=o.find(y=>y.occurrenceUuid===c);async function M(){if(!(!t.bookingUuid||!S||k.current)){k.current=!0,v(!0),x("");try{await T.instructor.moveBooking(t.bookingUuid,S.occurrenceUuid,s.occurrenceUuid)}catch(y){x(re(y,"Unable to reschedule this booking.")||"Unable to reschedule this booking."),k.current=!1,v(!1);return}i()}}return e.jsxs(ui,{isOpen:!0,canDismiss:!g,onClose:a,title:`Reschedule ${t.dis
2playName}`,subtitle:"Choose another class time, then confirm the move. Trial dates and class limits still apply.",children:[e.jsxs("p",{children:["Current class: ",s.className," · ",zs(s.startAt,n)]}),t.status==="checked_in"?e.jsx("p",{children:"This will clear the check in for the current class."}):null,e.jsxs("div",{className:"member-list-actions",children:[e.jsx("button",{type:"button",className:"member-btn is-neutral",disabled:d===0||b||g,onClick:()=>h(d-1),children:"Earlier classes"}),e.jsx("button",{type:"button",className:"member-btn is-neutral",disabled:b||g,onClick:()=>h(d+1),children:"Later classes"})]}),N?e.jsxs("div",{role:"alert",className:"member-panel-error",children:[e.jsx("p",{children:N}),e.jsx("button",{type:"button",className:"member-btn is-neutral",disabled:g,onClick:()=>f(m+1),children:"Refresh classes"})]}):null,b?e.jsxs("div",{className:"member-panel-loading",role:"status",children:[e.jsx(Te,{name:"crescent"}),e.jsx("span",{children:"Loading class times..."})]}):e.jsx("div",{className:"member-panel-list",role:"group","aria-label":"Class times",children:o.length?Object.entries(I).map(([y,P])=>e.jsxs("section",{className:"instructor-reschedule-date",children:[e.jsx("h3",{children:y}),e.jsx("div",{className:"instructor-reschedule-grid",children:P.map(U=>{const F=U.capacity>0&&U.bookedCount>=U.capacity;return e.jsxs("button",{type:"button",className:"member-panel-row instructor-reschedule-target","aria-pressed":c===U.occurrenceUuid,onClick:()=>{u(U.occurrenceUuid),x("")},disabled:g||F,children:[e.jsx("strong",{children:U.className}),e.jsx("span",{children:new Intl.DateTimeFormat("en-GB",{timeZone:n,timeStyle:"short"}).format(new Date(U.startAt||""))}),e.jsxs("small",{children:[U.locationName||"Location not set"," · ",F?"Full":U.capacity>0?`${Math.max(0,U.capacity-U.bookedCount)} places left`:"Places available"]})]},U.occurrenceUuid)})})]},y)):e.jsx("p",{children:"No matching future classes in this period. Try later classes."})}),S?e.jsxs("p",{role:"status",children:["Move to ",S.className," on ",zs(S.startAt,n),"?"]}):null,e.jsxs("div",{className:"member-list-actions",children:[e.jsx("button",{type:"button",className:"member-btn is-neutral",disabled:g,onClick:a,children:"Cancel"}),e.jsx("button",{type:"button",className:"member-btn is-solid",disabled:!S||b||g,onClick:()=>{M()},children:g?e.jsxs(e.Fragment,{children:[e.jsx(Te,{name:"crescent"})," Rescheduling..."]}):"Reschedule booking"})]})]})}function Ip(t){const s=t.trim().replace(/^PARQ submission:\s*/i,"").replace(/^Additional Health Information:\s*/i,"");return s!==""&&!/^(?:none|no|n\/?a|nil|none (?:declared|recorded|reported)|no (?:known )?medical (?:issues?|conditions?)(?: (?:declared|recorded|reported))?)[.!\s]*$/i.test(s)}function bu(t){return[...t.badges.map(s=>s.description?`${s.label}: ${s.description}`:s.label),t.medicalNotes].filter(s=>{const n=s?.trim()??"";return Ip(n)})}function $p(t,s){const n=s.trim().toLocaleLowerCase();return n.length<3?[]:t.filter(a=>[a.householdName,a.primaryPayerName,a.primaryPayerEmail].some(i=>i?.toLocaleLowerCase().includes(n)))}function Op(t){const s=/\s*Additional Health Information:\s*/i.exec(t);if(s?.index!==void 0)return{question:t.slice(0,s.index).replace(/^PARQ submission:\s*/i,"").trim(),answer:t.slice(s.index+s[0].length).trim()||"No additional information recorded."};const n=t.indexOf("?");return n>=0&&t.slice(n+1).trim()?{question:t.slice(0,n+1).replace(/^PARQ submission:\s*/i,"").trim(),answer:t.slice(n+1).trim()}:{question:null,answer:t}}const al={black:"#171717",blue:"#2563eb",brown:"#854d0e",gray:"#9ca3af",green:"#22c55e",grey:"#9ca3af",orange:"#fb923c",pink:"#ec4899",purple:"#9333ea",red:"#dc2626",white:"#ffffff",yellow:"#facc15"};function Es(t){const s=String(t||"").trim().toLowerCase();if(/^#[0-9a-f]{6}$/.test(s))return s;if(/^#[0-9a-f]{3}$/.test(s))return`#${s.slice(1).split("").map(a=>a.repeat(2)).join("")}`;const n=s.split(/[^a-z]+/).find(a=>Object.hasOwn(al,a));return n?al[n]:null}function Bp({memberUuid:t,progress:s,onChanged:n}){const[a,i]=r.useState(null),[o,l]=r.useState(""),[c,u]=r.useState("#ffffff"),[d,h]=r.useState(!1),[m,f]=r.useState(!1),[b,p]=r.useState(""),[g,v]=r.useState([]);r.useEffect(()=>{let k=!0;return s?.currentLevel?.uuid&&T.people.getStripeThemes(t,s.program.uuid,s.currentLevel.uuid).then(j=>{k&&v(j)}).catch(()=>{k&&v([])}),()=>{k=!1}},[t,s?.program.uuid,s?.currentLevel?.uuid]);function N(k){i(k),l(k.awardedOn||""),u(Es(k.colourKey)||"#ffffff"),h(!1),p("")}async function x(k=!1){if(!(!a||!s?.currentLevel||m)){if(!k&&(!/^\d{4}-\d{2}-\d{2}$/.test(o)||!/^#[0-9a-f]{6}$/i.test(c))){p("Enter the award date and a valid colour.");return}f(!0),p("");try{await T.people.correctStripeAward(t,s.program.uuid,s.currentLevel.uuid,a.uuid,k?null:{awardedOn:o,colourKey:c}),i(null),await n()}catch(j){p(j instanceof Error?j.message:"Unable to save the stripe. Please try again.")}finally{f(!1)}}}return e.jsxs(e.Fragment,{children:[e.jsxs("p",{children:[s?.program.name," ",s?.currentLevel?.label]}),b?e.jsx("p",{role:"alert",className:"member-panel-error",children:b}):null,e.jsx("ul",{className:"member-grading-history-list",children:s?.stripeAwards.map(k=>e.jsxs("li",{className:"member-roster-history-row",children:[e.jsxs("div",{className:"member-row-main",children:[e.jsxs("strong",{children:[e.jsx("span",{className:"member-stripe-swatch",style:{backgroundColor:Es(k.colourKey)||"transparent"}}),k.label]}),e.jsx("button",{type:"button",className:"member-btn is-neutral member-btn-compact",disabled:m,onClick:()=>N(k),"aria-label":`Edit ${k.label} stripe`,children:"Edit"})]}),e.jsxs("p",{children:[k.awardedOn?new Intl.DateTimeFormat("en-GB",{day:"numeric",month:"short",year:"numeric",timeZone:"UTC"}).format(new Date(k.awardedOn)):"Date not recorded"," · ",k.source==="manual"?"Added by staff":"Class attendance"]}),a?.uuid===k.uuid?e.jsxs("form",{className:"member-stripe-editor",onSubmit:j=>{j.preventDefault(),x()},children:[e.jsxs("label",{children:["Award date",e.jsx("input",{"aria-label":"Award date",type:"date",required:!0,value:o,disabled:m,onInput:j=>{l(j.currentTarget.value),p("")}})]}),e.jsxs("fieldset",{disabled:m,children:[e.jsx("legend",{children:"Stripe colour"}),e.jsx("div",{className:"member-stripe-colours",children:g.map(j=>{const I=Es(j.colourKey);return I?e.jsxs("button",{type:"button","aria-label":`${j.label} colour`,"aria-pressed":c.toLowerCase()===I,onClick:()=>{u(I),p("")},children:[e.jsx("span",{className:"member-stripe-swatch",style:{backgroundColor:I}}),j.label]},j.index):null})}),e.jsxs("div",{className:"member-stripe-custom-colour",children:[e.jsx("input",{"aria-label":"Choose custom stripe colour",type:"color",value:/^#[0-9a-f]{6}$/i.test(c)?c:"#ffffff",onChange:j=>{u(j.target.value),p("")}}),e.jsx("input",{"aria-label":"Custom stripe colour",placeholder:"#ffffff",value:c,onChange:j=>{u(j.target.value),p("")}})]})]}),d?e.jsxs("div",{className:"member-stripe-remove",role:"alert",children:[e.jsx("p",{children:"Remove this stripe? The recorded total will decrease by one."}),e.jsxs("div",{className:"member-stripe-editor-actions",children:[e.jsx("button",{type:"button",className:"member-btn is-neutral",disabled:m,onClick:()=>h(!1),children:"Keep stripe"}),e.jsx("button",{type:"button",className:"member-btn is-danger",disabled:m,onClick:()=>{x(!0)},children:m?"Removing...":"Confirm removal"})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"member-stripe-editor-actions",children:[e.jsx("button",{type:"button",className:"member-btn is-neutral",disabled:m,onClick:()=>{i(null),p("")},children:"Cancel"}),e.jsx("button",{type:"submit",className:"member-btn is-solid",disabled:m,children:m?"Saving...":"Save changes"})]}),e.jsx("button",{type:"button",className:"member-btn is-danger",disabled:m,onClick:()=>h(!0),children:"Remove stripe"})]})]}):null]},k.uuid))}),s?.stripeAwards.length?null:e.jsx("p",{children:"No stripe awards recorded for this level."})]})}function fu({messages:t}){return e.jsx("div",{className:"member-safety-notes",children:t.map((s,n)=>{const{question:a,answer:i}=Op(s);return e.jsxs("div",{className:"member-safety-note",children:[a?e.jsx("p",{className:"member-safety-question",children:a}):null,e.jsx("p",{className:"member-safety-answer",children:i})]},n)})})}function Fp({target:t,onClose:s,onChanged:n}){const[a,i]=r.useState(0),[o,l]=r.useState(null),[c,u]=r.useState(""),[d,h]=r.useState(!1);r.useEffect(()=>{let b=!0;if(l(null),u(""),!!t)return h(!0),T.people.getMemberDetail(t.uuid).then(p=>{b&&l(p)}).catch(p=>{b&&u(re(p,"Unable to load member notes."))}).finally(()=>{b&&h(!1)}),()=>{b=!1}},[t,a]);const m=o?.trainingProgress?.find(b=>b.program.uuid===t?.programUuid),f=o?bu(o):[];return e.jsx(ui,{isOpen:!!t,onClose:s,title:t?.mode==="safety"?"Safety notes":"Stripe history",subtitle:t?.name,children:d?e.jsxs("div",{role:"status",children:[e.jsx(Te,{})," Loading notes..."]}):c?e.jsx("p",{role:"alert",children:c}):o?t?.mode==="safety"?f.length?e.jsx(fu,{messages:f}):e.jsx("p",{children:"No safety notes recorded."}):e.jsx(Bp,{memberUuid:t?.uuid||"",progress:m,onChanged:async()=>{i(b=>b+1),await n?.()}},`${t?.uuid}:${t?.programUuid}`):null})}function Wp({row:t,programUuid:s,onProfile:n,onNotes:a}){const i=Es(t.grading?.colourKey)||Es(t.grading?.levelLabel)||"#52525b";return e.jsxs("div",{className:"instructor-roster-shortcuts",children:[t.personUuid?e.jsx("button",{type:"button",className:"instructor-roster-name-button",onClick:()=>n(t.personUuid),children:t.displayName}):e.jsx("strong",{children:t.displayName}),e.jsxs("div",{className:"instructor-roster-badges",children:[t.grading?e.jsx("button",{type:"button",className:"instructor-grading-pill",style:{backgroundColor:i,
2color:Kl(i)},disabled:!t.personUuid||t.grading.displayType==="patch","aria-label":`${t.grading.levelLabel}${t.grading.displayType==="belt"?`, ${t.grading.stripeCount} stripes. Open stripe history`:""}`,onClick:()=>t.personUuid&&a({uuid:t.personUuid,name:t.displayName,mode:"grading",programUuid:t.grading?.programUuid||s}),children:e.jsxs("span",{children:[t.grading.levelLabel.toUpperCase(),t.grading.displayType==="belt"?` · ${t.grading.stripeCount}`:""]})}):null,t.hasSafetyFlag?e.jsxs("button",{type:"button",className:"instructor-safety-flag","aria-label":`Open safety notes for ${t.displayName}`,title:t.safetyLabels?.join(", ")||"Open safety notes",disabled:!t.personUuid,onClick:()=>t.personUuid&&a({uuid:t.personUuid,name:t.displayName,mode:"safety",programUuid:null}),children:[e.jsx(V,{icon:hc}),e.jsx("span",{children:t.safetyLabels?.length?`${t.safetyLabels.slice(0,2).join(" · ")}${t.safetyLabels.length>2?` +${t.safetyLabels.length-2}`:""}`:"Safety"})]}):null]})]})}function qp(t,s="duration"){if(!t)return null;const n=/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/.test(t)?`${t.replace(" ","T")}Z`:t,a=new Date(n);if(Number.isNaN(a.getTime()))return null;if(s==="class_count")return`Trial class must be used by ${new Date(a.getTime()-864e5).toLocaleDateString("en-GB",{day:"numeric",month:"short",year:"numeric",timeZone:"UTC"})}`;const i=Math.ceil((a.getTime()-Date.now())/864e5);return i<0?"Trial has ended":i===0?"Trial ends today. Good time to discuss membership.":i<=3?`Trial ends in ${i} day${i===1?"":"s"}. Good time to discuss membership.`:`Trial ends ${a.toLocaleDateString("en-GB",{day:"numeric",month:"short",year:"numeric"})}`}class Hp{constructor(s){this.transport=s}programmes(){return this.transport("class-plans/programmes","GET")}moveAssignment(s){return this.transport("class-plans/move-assignment","POST",s)}curriculum(s,n=""){return this.transport(`curriculum/items?${new URLSearchParams({program_uuid:s,q:n,node_type:"item",limit:"100"})}`,"GET")}list(s,n="",a=0){return this.transport(`class-plans/resources?${new URLSearchParams({kind:s,q:n,cursor:String(a)})}`,"GET")}async read(s){return(await this.transport(`class-plans/plan?uuid=${encodeURIComponent(s)}`,"GET")).plan}async save(s){return(await this.transport("class-plans/plan","POST",s)).plan}activities(s="",n=0){return this.transport(`class-plans/activities?${new URLSearchParams({q:s,cursor:String(n)})}`,"GET")}saveActivity(s){return this.transport("class-plans/activities","POST",s)}chat(s,n,a){return this.transport("class-plans/conversation","POST",{draft:s,mode:n,messages:a.slice(-20)})}assignments(s){return this.transport(`class-plans/assignments?occurrences=${encodeURIComponent(s.join(","))}`,"GET")}moveSection(s){return this.transport("class-plans/move-section","POST",s)}assign(s,n,a){return this.transport("class-plans/assign","POST",{plan_uuid:s,occurrence_uuid:n,expected_plan_uuid:a})}classes(s){return this.transport(`class-plans/classes?programme_uuid=${encodeURIComponent(s)}`,"GET")}}const Vp=["free_text","exercise_list","rounds","amrap","emom","intervals","strength_sets","table_ladder"],gu=(t="Teaching notes")=>({uuid:crypto.randomUUID(),title:t,type:"other",notes:"",minutes:null,format:"free_text",structure:{},activities:[],staff_notes:"",member_instructions:"",member_visible:!1,public_visible:!1}),rl=(t="",s="plan")=>({title:"",programme_uuid:t,resource_kind:s,description:"",objective:"",status:"draft",curriculum_item_uuids:[],sections:[gu()],can_edit:!0});function zp(t,s="plan"){const n=JSON.parse(JSON.stringify(t));return delete n.uuid,delete n.revision,delete n.updated_at,delete n.planned_date,delete n.location_uuid,n.snapshot=!1,n.can_edit=!0,n.status="draft",n.resource_kind=s,n.title=`${t.title} copy`,n.sections.forEach(a=>{a.uuid=crypto.randomUUID()}),n}function il(t,s,n){const a=s+n;if(a<0||a>=t.sections.length)return t;const i=[...t.sections];return[i[s],i[a]]=[i[a],i[s]],{...t,sections:i}}const Gp=t=>t.replaceAll("_"," ").replace(/^./,s=>s.toUpperCase()),ds=new Hp((t,s,n)=>Ju.request(`/api/v1/${t}`,{method:s,body:n,withAuth:!0}));function Kp({occurrenceUuid:t,timezone:s}){const n=tt(),[a,i]=r.useState(!1),[o,l]=r.useState(null),[c,u]=r.useState(!1),[d,h]=r.useState(""),m=r.useRef(null);r.useEffect(()=>()=>m.current?.abort(),[]);function f(){m.current?.abort(),i(!1),u(!1),l(null),h("")}function b(g){f(),n.push(g)}async function p(){if(m.current&&!m.current.signal.aborted)return;const g=new AbortController;m.current=g,i(!0),u(!0),l(null),h("");
2try{const v=await T.instructor.getCornerBriefing(t,g.signal);g.signal.aborted||l(v)}catch(v){g.signal.aborted||h(v instanceof Error?v.message:"Unable to prepare Corner briefing. Try again.")}finally{g.signal.aborted||u(!1),g.abort()}}return e.jsxs("div",{className:"corner-class-briefing",children:[e.jsxs("button",{type:"button",className:"member-btn is-solid corner-class-briefing-button",onClick:()=>{p()},disabled:c,"aria-haspopup":"dialog","aria-expanded":a,children:[c?e.jsx(Te,{name:"crescent"}):e.jsx(V,{icon:or,"aria-hidden":"true"}),c?"Preparing Corner briefing":"Corner briefing"]}),e.jsxs(ui,{isOpen:a,onClose:f,title:"Corner briefing",children:[c?e.jsx("p",{role:"status",children:"Reading the latest class records..."}):null,d?e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"member-panel-error",role:"alert",children:d}),e.jsx("button",{type:"button",className:"member-btn is-solid",onClick:()=>{p()},children:"Try again"})]}):null,o?e.jsxs("section",{className:"corner-briefing-records","aria-label":"Class records",children:[e.jsx("p",{children:e.jsx("strong",{children:o.headline})}),e.jsxs("div",{className:"corner-briefing-overview","aria-label":"Before class",children:[e.jsx("h3",{children:"Before class"}),o.records.filter(g=>g.summary).map(g=>e.jsxs("div",{className:"corner-briefing-summary",children:[e.jsx("p",{children:e.jsx("strong",{children:g.name||g.title})}),g.date?e.jsxs("p",{className:"corner-briefing-meta",children:["Recorded ",zs(g.date,s)]}):null,e.jsx("p",{children:g.summary})]},g.id)),o.records.length>0&&!o.records.some(g=>g.summary)?e.jsx("p",{children:"The records need a closer review. Open the original wording below."}):null]}),o.records.length>0?e.jsx("h3",{className:"corner-briefing-section-title",children:"Full records"}):null,e.jsx("div",{className:"member-panel-list",children:o.records.map(g=>e.jsxs("article",{className:"member-panel-row",children:[e.jsxs("strong",{children:[g.name?`${g.name}: `:"",g.title]}),g.date?e.jsxs("p",{children:["Recorded ",zs(g.date,s)]}):null,e.jsxs("details",{className:"corner-briefing-disclosure",children:[e.jsxs("summary",{children:[e.jsxs("span",{children:["Original wording",g.truncated?" excerpt":""]}),e.jsx(V,{icon:Xr,"aria-hidden":"true"})]}),e.jsx("p",{className:"corner-briefing-original",children:g.text})]}),g.member_uuid?e.jsx("button",{type:"button",className:"member-btn is-neutral member-btn-compact",onClick:()=>b(`/people/members/${encodeURIComponent(g.member_uuid)}`),children:"Open member record"}):null,g.occurrence_uuid?e.jsx("button",{type:"button",className:"member-btn is-neutral member-btn-compact",onClick:()=>b(`/instructor/classes?occurrence=${encodeURIComponent(g.occurrence_uuid)}`),children:"Open class record"}):null]},g.id))}),o.records.length===0?e.jsx("p",{children:"No health reports, staff notes or class incidents were found in the records checked."}):null,e.jsxs("div",{className:"corner-briefing-coverage",children:[e.jsxs("p",{children:["Records checked ",zs(o.generated_at,s),". ",o.source==="records"?"Showing a short extract of the reported information.":"Summaries prepared by Corner. Any other records use their reported wording."]}),o.warnings.map(g=>e.jsx("p",{role:"status",children:g},g)),e.jsx("p",{children:o.notice})]})]}):null]})]})}function Ro(t,s){const n=[];return t&&t>0&&n.push({wpUserId:t,role:"lead"}),Array.from(new Set(s)).filter(a=>a>0&&a!==t).forEach(a=>n.push({wpUserId:a,role:"assistant"})),n}function Yp(t,s,n){const a=Array.from(new Set(t.assistantWpUserIds)).filter(i=>i>0&&i!==s);return n==="unassigned"?{leadWpUserId:t.leadWpUserId===s?null:t.leadWpUserId,assistantWpUserIds:a}:n==="assistant"?{leadWpUserId:t.leadWpUserId===s?null:t.leadWpUserId,assistantWpUserIds:[...a,s]}:t.leadWpUserId!==null&&t.leadWpUserId!==s?t:{leadWpUserId:s,assistantWpUserIds:a}}function Qp(t,s){return t.leadWpUserId===s?"lead":t.assistantWpUserIds.includes(s)?"assistant":"unassigned"}function Zp(t,s){const n=new Map(s.map(a=>[a.wpUserId,a.status]));return t.map(a=>({...a,availabilityStatus:n.get(a.wpUserId)??"not_set"})).sort((a,i)=>{const o=+(i.availabilityStatus==="available")-+(a.availabilityStatus==="available");return o!==0?o:a.displayName.localeCompare(i.displayName,"en",{sensitivity:"base"})})}function Jp(){return["cancelled","no_show","checked_in"]}function Xp(t){return t==="available"?"Available":t==="not_available"?"Not available":"Not set"}
2function To({contextLabel:t,directory:s,availability:n,draft:a,loading:i,saving:o,onChange:l,onCancel:c,onSave:u}){const d=r.useMemo(()=>Zp(s,n),[n,s]),h=(m,f)=>{l(Yp(a,m,f))};return e.jsxs("div",{className:"member-modal-sheet instructor-rota-sheet",children:[e.jsxs("nav",{className:"member-modal-nav","aria-label":"Assignment navigation",children:[e.jsx("button",{type:"button","aria-label":"Go back",onClick:c,disabled:o,children:e.jsx(V,{icon:Hs})}),e.jsx("button",{type:"button","aria-label":"Open menu",onClick:()=>{Fn.toggle(Nn)},children:e.jsx(V,{icon:jo})})]}),e.jsxs("div",{className:"member-modal-header",children:[e.jsx("h2",{children:"Assign instructors"}),e.jsx("p",{children:"Choose one lead instructor and any assistants for this class."}),t?e.jsx("strong",{className:"instructor-rota-context",children:t}):null]}),i?e.jsxs("div",{className:"member-panel-loading",children:[e.jsx(Te,{name:"crescent"}),e.jsx("span",{children:"Loading rota..."})]}):d.length===0?e.jsxs("div",{className:"member-panel-row",children:[e.jsx("strong",{children:"No instructors available"}),e.jsx("p",{children:"No assignable instructors were returned for this class."})]}):e.jsx("div",{className:"member-panel-list instructor-rota-list",children:d.map(m=>{const f=Qp(a,m.wpUserId),b=m.availabilityStatus.replace("_","-"),p=a.leadWpUserId!==null&&a.leadWpUserId!==m.wpUserId,g=f==="unassigned"?"Not set":f==="lead"?"Lead":"Assistant";return e.jsxs("div",{className:`member-panel-row instructor-rota-row is-${b}`,children:[e.jsxs("div",{className:"member-row-main",children:[e.jsx("strong",{children:m.displayName}),e.jsx("span",{className:`member-pill instructor-assignment-pill is-${f}`,children:g})]}),e.jsxs("div",{className:"instructor-rota-role-buttons",role:"group","aria-label":`Assignment for ${m.displayName}`,children:[e.jsx("button",{type:"button",className:`instructor-rota-role-btn${f==="lead"?" is-selected":""}`,"aria-pressed":f==="lead",disabled:o||p,title:p?"Another lead instructor is already assigned":f==="lead"?"Clear lead assignment":"Assign as lead instructor",onClick:()=>h(m.wpUserId,f==="lead"?"unassigned":"lead"),children:"Lead"}),e.jsx("button",{type:"button",className:`instructor-rota-role-btn${f==="assistant"?" is-selected":""}`,"aria-pressed":f==="assistant",disabled:o,title:f==="assistant"?"Clear assistant assignment":"Assign as assistant instructor",onClick:()=>h(m.wpUserId,f==="assistant"?"unassigned":"assistant"),children:"Assistant"})]}),e.jsxs("span",{className:`instructor-rota-availability is-${b}`,children:["Availability: ",Xp(m.availabilityStatus)]})]},m.wpUserId)})}),e.jsxs("div",{className:"instructor-rota-footer",children:[e.jsx("button",{type:"button",className:"member-btn is-neutral",onClick:c,disabled:o,children:"Cancel"}),e.jsx("button",{type:"button",className:"member-btn is-solid",onClick:u,disabled:i||o,children:o?"Saving...":"Save rota"})]})]})}function eb(t){const s=Array.isArray(t)?t[0]:t;return s?s.slice(0,s.includes("T")?16:10):""}function tb(t,s){const n=/^(\d{4})-(\d{2})-(\d{2})(?:T(\d{2}):(\d{2}))?/.exec(t);if(!n)return s==="date"?"Choose date":"Choose date and time";const a=new Date(Date.UTC(Number(n[1]),Number(n[2])-1,Number(n[3]))),i=new Intl.DateTimeFormat("en-GB",{day:"numeric",month:"short",year:"numeric",timeZone:"UTC"}).format(a);return s==="date"||!n[4]||!n[5]?i:`${i} at ${n[4]}:${n[5]}`}function ao({id:t,label:s,value:n,onChange:a,presentation:i,min:o,max:l,disabled:c=!1}){const[u,d]=r.useState(!1),[h,m]=r.useState(n);r.useEffect(()=>{u||m(n)},[u,n]);function f(){m(n),d(!0)}function b(){h&&a(h),d(!1)}return e.jsxs("div",{className:"member-input-label member-date-time-field",children:[e.jsx("span",{children:s}),e.jsx("button",{type:"button",className:"member-input member-date-time-field-trigger",disabled:c,"aria-haspopup":"dialog","aria-expanded":u,onClick:f,children:tb(n,i)}),e.jsx(at,{isOpen:u,className:"member-picker-modal",onDidDismiss:()=>d(!1),children:e.jsxs("div",{className:"member-picker-modal-content",role:"dialog","aria-modal":"true","aria-labelledby":`${t}-title`,children:[e.jsxs("div",{className:"member-picker-modal-header",children:[e.jsx("h2",{id:`${t}-title`,children:s}),e.jsx("p",{children:i==="date"?"Choose the month, year and date.":"Choose the date and time."})]}),e.jsx(Zr,{id:t,color:"primary",mode:"md",locale:"en-GB",firstDayOfWeek:1,presentation:i,showDefaultButtons:!1,value:h||void 0,min:o,max:l,onIonChange:p=>m(eb(p.detail.value))}),e.jsxs("div",{className:"member-picker-modal-actions",children:[e.jsx("button",{type:"button",className:"member-btn is-neutral",onClick:()=>d(!1),children:"Cancel"}),e.jsx("button",{type:"button",className:"member-btn is-solid",onClick:b,disabled:!h,children:"Done"})]})]})})]})}function rn(t,s){return Number.isFinite(t)&&t>0?t:s}function _o(t){return Number.isFinite(t)?Math.min(3,Math.max(1,t)):1}
2function sb(t,s,n){const a=rn(s,1),i=rn(t.width,1),o=rn(t.height,1),l=Math.max(a/i,a/o),c=_o(n);return{x:Math.max(0,(i*l*c-a)/2),y:Math.max(0,(o*l*c-a)/2)}}function ro(t,s,n,a){const i=sb(s,n,a);return{x:Math.min(i.x,Math.max(-i.x,Number.isFinite(t.x)?t.x:0)),y:Math.min(i.y,Math.max(-i.y,Number.isFinite(t.y)?t.y:0))}}function xu(t,s,n,a){const i=rn(s,1),o=rn(t.width,1),l=rn(t.height,1),c=Math.max(i/o,i/l),u=_o(n),d=o*c*u,h=l*c*u,m=ro(a,t,i,u);return{displayedWidth:d,displayedHeight:h,left:(i-d)/2+m.x,top:(i-h)/2+m.y}}function nb(t,s,n,a){const i=xu(t,s,n,a),o=rn(t.width,1)/i.displayedWidth,l=s*o;return{x:Math.max(0,-i.left*o),y:Math.max(0,-i.top*o),size:Math.min(rn(t.width,1),rn(t.height,1),l)}}const ia=600;function ab(t,s){return new Promise((n,a)=>{t.toBlob(i=>{if(!i){a(new Error("Unable to crop this photo."));return}n(new File([i],s,{type:"image/jpeg",lastModified:Date.now()}))},"image/jpeg",.88)})}function rb({file:t,memberName:s,saving:n,onCancel:a,onError:i,onSave:o}){const l=r.useRef(null),c=r.useRef(null),u=r.useRef(null),[d,h]=r.useState({width:1,height:1}),[m,f]=r.useState(300),[b,p]=r.useState(1),[g,v]=r.useState({x:0,y:0}),[N,x]=r.useState(!1),[k,j]=r.useState("");r.useEffect(()=>{const F=URL.createObjectURL(t);return h({width:1,height:1}),p(1),v({x:0,y:0}),j(F),()=>URL.revokeObjectURL(F)},[t]),r.useEffect(()=>{const F=l.current;if(!F)return;const A=()=>f(Math.max(1,F.clientWidth));A();const D=typeof ResizeObserver>"u"?null:new ResizeObserver(A);return D?.observe(F),window.addEventListener("resize",A),()=>{D?.disconnect(),window.removeEventListener("resize",A)}},[]),r.useEffect(()=>{v(F=>ro(F,d,m,b))},[d,m,b]);const I=xu(d,m,b,g),S=n||N,M=F=>{S||(F.currentTarget.setPointerCapture(F.pointerId),u.current={pointerId:F.pointerId,clientX:F.clientX,clientY:F.clientY,pan:g})},y=F=>{const A=u.current;!A||A.pointerId!==F.pointerId||S||v(ro({x:A.pan.x+F.clientX-A.clientX,y:A.pan.y+F.clientY-A.clientY},d,m,b))},P=F=>{u.current?.pointerId===F.pointerId&&(u.current=null)},U=async()=>{const F=c.current;if(!(!F||d.width<=1||d.height<=1||S)){x(!0);try{const A=nb(d,m,b,g),D=document.createElement("canvas");D.width=ia,D.height=ia;const R=D.getContext("2d");if(!R)throw new Error("Unable to crop this photo.");R.fillStyle="#ffffff",R.fillRect(0,0,ia,ia),R.drawImage(F,A.x,A.y,A.size,A.size,0,0,ia,ia);const w=await ab(D,`member-photo-${Date.now()}.jpg`);await o(w)}catch(A){i(A instanceof Error&&A.message?A.message:"Unable to crop this photo.")}finally{x(!1)}}};return e.jsxs("div",{className:"member-modal-sheet instructor-photo-crop-sheet",children:[e.jsxs("div",{className:"member-modal-header",children:[e.jsx("h2",{children:"Crop photo"}),e.jsxs("p",{children:["Move and zoom the photo for ",s,"."]})]}),e.jsxs("div",{ref:l,className:"instructor-photo-crop-stage",onPointerDown:M,onPointerMove:y,onPointerUp:P,onPointerCancel:P,children:[k?e.jsx("img",{ref:c,src:k,alt:`Crop preview for ${s}`,draggable:!1,onLoad:F=>{h({width:Math.max(1,F.currentTarget.naturalWidth),height:Math.max(1,F.currentTarget.naturalHeight)}),v({x:0,y:0})},onError:()=>i("Unable to read this photo. Take another photo and try again."),style:{width:`${I.displayedWidth}px`,height:`${I.displayedHeight}px`,left:`${I.left}px`,top:`${I.top}px`}}):e.jsx(Te,{name:"crescent"}),e.jsx("div",{className:"instructor-photo-crop-guide","aria-hidden":"true"})]}),e.jsxs("label",{className:"instructor-photo-zoom",children:[e.jsx("span",{children:"Zoom"}),e.jsx("input",{type:"range",min:"1",max:"3",step:"0.01",value:b,disabled:S,onChange:F=>p(_o(Number(F.target.value)))})]}),e.jsxs("div",{className:"member-list-actions",children:[e.jsx("button",{type:"button",className:"member-btn is-neutral",onClick:a,disabled:S,children:"Cancel"}),e.jsx("button",{type:"button",className:"member-btn is-solid",onClick:()=>{U()},disabled:S||d.width<=1,children:S?e.jsxs(e.Fragment,{children:[e.jsx(Te,{name:"crescent"})," Saving photo"]}):"Use photo"})]})]})}class ib{active=null;blockedUntil=0;movementThreshold;blockDurationMs;now;constructor(s=10,n=350,a=()=>Date.now()){this.movementThreshold=s,this.blockDurationMs=n,this.now=a}begin(s,n,a){this.active={id:s,x:n,y:a,moved:!1}}move(s,n,a){if(!this.active||this.active.id!==s||this.active.moved)return;Math.hypot(n-this.active.x,a-this.active.y)>=this.movementThreshold&&(this.active.moved=!0,this.blockedUntil=this.now()+this.blockDurationMs)}end(s){!this.active||this.active.id!==s||(this.active.moved&&(this.blockedUntil=this.now()+this.blockDurationMs),this.active=null)}cancel(s){!this.active||this.active.id!==s||(this.blockedUntil=this.now()+this.blockDurationMs,this.active=null)}allowsActivation(s=!1){return s||this.now()>=this.blockedUntil}}function ju(){const t=r.useRef(null);
2t.current===null&&(t.current=new ib);const s=r.useCallback(l=>{l.isPrimary&&t.current?.begin(l.pointerId,l.clientX,l.clientY)},[]),n=r.useCallback(l=>{t.current?.move(l.pointerId,l.clientX,l.clientY)},[]),a=r.useCallback(l=>{t.current?.end(l.pointerId)},[]),i=r.useCallback(l=>{t.current?.cancel(l.pointerId)},[]),o=r.useCallback(l=>t.current?.allowsActivation(l.detail===0)??!0,[]);return r.useMemo(()=>({handlers:{onPointerDownCapture:s,onPointerMoveCapture:n,onPointerUpCapture:a,onPointerCancelCapture:i},allowsClick:o}),[o,i,s,n,a])}function ob({hasSelectedOccurrence:t,isOccurrenceListLoading:s,isRosterLoading:n}){return t?n:s}const lb=new Set(["members","trials","cancelled"]);function cb(t){const s=new URLSearchParams(t).get("roster")?.trim().toLowerCase()??"";return lb.has(s)?s:"members"}function yu(t,s="members"){return`/instructor/classes?${new URLSearchParams({occurrence:t.trim(),roster:s}).toString()}`}function ub(t){return`/instructor/classes?${new URLSearchParams({occurrence:t.trim(),roster:"members",view:"rota"}).toString()}`}function db(t){const s=t.trim().toLowerCase();return s==="checked_in"||s==="no_show"||s==="cancelled"?s:"unset"}function mb(t,s){const n={checked_in:"clear_checked_in",no_show:"clear_no_show",cancelled:"restore_cancelled"};if(t===s)return[n[s]];const a=[];return t!=="unset"&&a.push(n[t]),a.push(`set_${s}`),a}function ol(t,s){const n=new Date(t.getTime());return n.setDate(n.getDate()+s),n}function ll(t){return t.toLowerCase()==="closed"?"Completed":t.replace("_"," ").replace(/\b\w/g,s=>s.toUpperCase())}function cl(t,s){return new Intl.NumberFormat("en-GB",{style:"currency",currency:s||"GBP"}).format(t/100)}function hb(){const t=new Date;return{start:Qa(ol(t,-7)),end:Qa(ol(t,1))}}function ul(t,s){if(!t)return"";const n=new Date(t);if(Number.isNaN(n.getTime()))return"";const a=new Intl.DateTimeFormat("en-CA",{timeZone:s,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",hourCycle:"h23"}).formatToParts(n),i=o=>a.find(l=>l.type===o)?.value??"";return`${i("year")}-${i("month")}-${i("day")}T${i("hour")}:${i("minute")}`}function dl(t,s){if(!t)return"";const n=new Date(t);if(Number.isNaN(n.getTime()))return"";const a=new Intl.DateTimeFormat("en-CA",{timeZone:s,year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(n),i=o=>a.find(l=>l.type===o)?.value??"";return`${i("year")}-${i("month")}-${i("day")}`}function ml(t="",s=""){return{occurrenceUuid:t,closeoutProgramUuid:s,lessonPlanUuid:"",closeoutTermUuid:"",closeoutCycleUuid:"",closeoutCycleNumber:"",closeoutWeekNumber:"",closeoutCurriculumItemUuids:[],closeoutPressureElementUuids:[],closeoutNotes:"",incidentSummary:"",incidentNotes:"",requiresManagerReview:!1,stripeAwardSkips:{}}}function oa(t){return t.status.trim().toLowerCase()==="cancelled"}function pb(t){return["checked_in","no_show","cancelled"].includes(t.status.trim().toLowerCase())}function hl(t,s){const n=t.status.trim().toLowerCase();return n==="cancelled"?t.isEventAttendee?"Event registration cancelled":"Booking cancelled":n==="no_show"?"Marked as no show":n==="checked_in"&&t.checkedInAt?`Checked in ${zs(t.checkedInAt,s)}`:""}function bb(t){const s=t.status.trim().toLowerCase();return s==="checked_in"?" is-attended":s==="no_show"?" is-no-show":s==="cancelled"?" is-cancelled":""}function pl(t){return t.missingContactDetails?t.missingEmail&&t.missingPhone?"Email and phone missing":t.missingEmail?"Email missing":t.missingPhone?"Phone missing":null:null}function vu({item:t,childrenByParent:s,selectedUuids:n,searchActive:a,onToggle:i}){const o=s.get(t.uuid)??[],l=["item","variation"].includes(t.nodeType),c=`${t.code?`${t.code} . `:""}${t.title||t.uuid}`;return l&&o.length===0?e.jsxs("label",{className:"instructor-curriculum-leaf",children:[e.jsx("input",{type:"checkbox",checked:n.includes(t.uuid),onChange:u=>i(t.uuid,u.target.checked)}),e.jsx("span",{children:c})]}):e.jsxs("details",{className:"instructor-curriculum-branch",open:a||t.nodeType==="level",children:[e.jsxs("summary",{children:[e.jsx("span",{children:c}),l?e.jsx("input",{type:"checkbox","aria-label":`Select ${c}`,checked:n.includes(t.uuid),onClick:u=>u.stopPropagation(),onChange:u=>i(t.uuid,u.target.checked)}):null]}),e.jsx("div",{className:"instructor-curriculum-children",children:o.map(u=>e.jsx(vu,{item:u,childrenByParent:s,selectedUuids:n,searchActive:a,onToggle:i},u.uuid))})]})}function fb(){const t=T.tenant.getTenantTimezone(),s=tt(),n=mt(),{hasRole:a,user:i}=Ge(),o=ju(),l=a("instructor","admin","owner"),c=ii(i),u=r.useMemo(()=>new URLSearchParams(n.search).get("occurrence")?.trim()||"",[n.search]),d=r.useMemo(()=>cb(n.search),[n.search]),h=r.useMemo(()=>
2new URLSearchParams(n.search).get("view")==="debrief",[n.search]),m=r.useMemo(()=>new URLSearchParams(n.search).get("view")==="edit-class",[n.search]),f=r.useMemo(()=>new URLSearchParams(n.search).get("view")==="rota",[n.search]),b=r.useMemo(()=>hb(),[]),[p]=r.useState(b.start),[g]=r.useState(b.end),[v]=r.useState("all"),[N]=r.useState("all"),[x,k]=r.useState([]),[j,I]=r.useState(""),[S,M]=r.useState(null),[y,P]=r.useState([]),[U,F]=r.useState([]),[,A]=r.useState([]),[,D]=r.useState([]),{value:R,setValue:w,isHydrated:_,clear:W}=Xn({pageKey:`instructor-closeout:${u||"none"}`,initialValue:ml(u),enabled:!!u}),H=R.closeoutProgramUuid,ne=R.lessonPlanUuid,K=R.closeoutTermUuid,ye=R.closeoutCycleUuid,de=R.closeoutCycleNumber,O=R.closeoutWeekNumber,L=R.closeoutCurriculumItemUuids,Z=R.closeoutPressureElementUuids,ce=R.closeoutNotes,me=R.incidentSummary,Ne=R.incidentNotes,ve=R.requiresManagerReview,xe=R.stripeAwardSkips||{},[G,J]=r.useState(!0),[ke,Be]=r.useState(!1),[fe,Ae]=r.useState(""),[lt,be]=r.useState(""),[We,Fe]=r.useState(""),[Ke,ue]=r.useState(null),[Se,pe]=r.useState(null),[ae,ge]=r.useState(!1),[qe,Me]=r.useState(""),[Ie,ie]=r.useState(d),[Xe,ct]=r.useState(!1),[st,xt]=r.useState(""),[Et,q]=r.useState([]),[te,B]=r.useState(!1),[Y,oe]=r.useState(null),[Ue,_e]=r.useState(null),[He,kt]=r.useState(null),[rt,Lt]=r.useState(!1),[Ft,Pt]=r.useState(!1),[Rs,es]=r.useState(null),[ht,vs]=r.useState(null),[jt,Kt]=r.useState(""),[Rt,Wt]=r.useState(null),[Yt,Ts]=r.useState(""),[At,is]=r.useState(""),[ts,os]=r.useState(""),[Zs,bt]=r.useState(""),[hs,Js]=r.useState(""),[ps,Qt]=r.useState(!1),[ls,qt]=r.useState(!1),[$,le]=r.useState(!1),[Ve,ot]=r.useState(""),[_t,Ns]=r.useState(""),[Xs,Ls]=r.useState(""),[Ht,Q]=r.useState(!0),[je,we]=r.useState(""),[Oe,ut]=r.useState(""),[Ze,Nt]=r.useState([]),[wt,Vt]=r.useState(!1),[ks,bs]=r.useState(""),[pr,fs]=r.useState(!1),[Pa,Sn]=r.useState(""),[ss,ea]=r.useState(!0),[dn,en]=r.useState(!1),[mn,Pn]=r.useState(null),[hn,_s]=r.useState([]),[hi,pn]=r.useState([]),[pi,br]=r.useState([]),bn=r.useRef(0),Ra=r.useRef(""),Rn=r.useRef(""),Ta=r.useRef(null),_a=r.useRef(null);r.useEffect(()=>{ie(d)},[d]);const Ce=r.useMemo(()=>S??x.find(C=>C.occurrenceUuid===j)??null,[j,x,S]),zt=!!Ce?.isEvent||y.some(C=>C.isEventAttendee),[tn,Ma]=r.useState(null),[Tn,_n]=r.useState("");r.useEffect(()=>{let C=!0;return Ma(null),_n(""),Ce?.status==="closed"&&T.instructor.getCloseout(Ce.occurrenceUuid).then(z=>{C&&Ma(z)}).catch(()=>{C&&_n("Unable to load the saved class record. Reload to try again.")}),()=>{C=!1}},[Ce?.occurrenceUuid,Ce?.status]);const Is=r.useCallback(async()=>{if(!(!j||zt)){Qt(!0),en(!0),Fe("");try{const C=await T.instructor.getInstructorRota(j);pn(C.assignableInstructors),br(C.availability),Pn(C.instructors.find(z=>z.role==="lead")?.wpUserId??null),_s(C.instructors.filter(z=>z.role==="assistant").map(z=>z.wpUserId))}catch(C){Fe(re(C,"Unable to load the instructor rota.")),Qt(!1)}finally{en(!1)}}},[j,zt]);r.useEffect(()=>{!c||!f||!u||j!==u||Ra.current===u||(Ra.current=u,Is(),s.replace(yu(u)))},[j,c,s,f,u,Is]);const bi=r.useCallback(async()=>{if(j){Ae("save-instructor-rota");try{await T.instructor.saveInstructorRota(j,Ro(mn,hn)),be("Instructor rota saved."),Qt(!1)}catch(C){Fe(re(C,"Unable to save the instructor rota."))}finally{Ae("")}}},[j,hn,mn]),$s=r.useCallback(async C=>{if(C){qt(!1),le(!0),Fe("");try{const z=await T.instructor.getInstructorRota(C);ot(ul(z.startAt,t)),Ns(ul(z.endAt,t)),Ls(z.capacity>0?String(z.capacity):""),Q(z.trialBookingAvailable),we(z.locationUuid||""),ut(z.locationName||""),Nt(z.moveableAreas)}catch(z){Fe(re(z,"Unable to load the class details."))}finally{le(!1)}}},[t]),fi=r.useCallback(()=>{j&&(qt(!1),s.push(`/instructor/classes?occurrence=${encodeURIComponent(j)}&view=edit-class`))},[j,s]);r.useEffect(()=>{m&&u&&$s(u)},[m,$s,u]);const ta=ob({hasSelectedOccurrence:!!u,isOccurrenceListLoading:G,isRosterLoading:ke}),ws=r.useMemo(()=>y.filter(C=>!pb(C)).length,[y]),Cs=Se?.url??"",fr=r.useMemo(()=>Cs?ya(Cs):"",[Cs]),gr=r.useMemo(()=>y.filter(C=>!C.isTrialAttendee&&!oa(C)),[y]),xr=r.useMemo(()=>y.filter(C=>C.isTrialAttendee&&!oa(C)),[y]),fn=r.useMemo(()=>y.filter(C=>oa(C)),[y]),Ua=r.useMemo(()=>y.filter(C=>!oa(C)),[y]),jr=r.useMemo(()=>new Set(y.map(C=>
2C.personUuid?.trim().toLowerCase()??"").filter(Boolean)),[y]),Mn=zt?Ie==="cancelled"?fn:Ua:Ie==="trials"?xr:Ie==="cancelled"?fn:gr,Ms=r.useMemo(()=>{const C=hs.trim().toLowerCase();if(!C)return U;const z=new Set(U.filter(Le=>`${Le.code} ${Le.title} ${Le.levelLabel||""}`.toLowerCase().includes(C)).map(Le=>Le.uuid)),Re=new Map(U.map(Le=>[Le.uuid,Le]));for(const Le of Array.from(z)){let Je=Re.get(Le)?.parentUuid??null;for(;Je;)z.add(Je),Je=Re.get(Je)?.parentUuid??null}return U.filter(Le=>z.has(Le.uuid))},[U,hs]),yr=r.useMemo(()=>{const C=new Set(Ms.map(Re=>Re.uuid)),z=new Map;return Ms.forEach(Re=>{const Le=Re.parentUuid&&C.has(Re.parentUuid)?Re.parentUuid:"root",Je=z.get(Le)??[];Je.push(Re),z.set(Le,Je)}),z},[Ms]),gi=yr.get("root")??[],[vr,Ea]=r.useState(null),Nr=r.useCallback(C=>{const z=encodeURIComponent(`${n.pathname}${n.search}`);oe(null),s.push(`/people/members/${C}?returnTo=${z}`)},[s,n.pathname,n.search]),It=r.useCallback(C=>{w(z=>({...z,...C}))},[w]),[E,X]=r.useState(null);r.useEffect(()=>{let C=!0;X(null);const z=new URLSearchParams(n.search).get("classPlan");if(!(!z||!Ce?.programUuid||!l))return ds.read(z).then(Re=>{C&&Re.programme_uuid===Ce.programUuid&&Re.status==="published"&&X(Re)}).catch(()=>{C&&be("The plan could not be loaded. Reopen it in Class Plans.")}),()=>{C=!1}},[n.search,Ce?.programUuid,l]);const ee=r.useCallback(C=>{const z=C?.trim()||"";z&&s.push(`/staff-tools/lesson-plans?version=${encodeURIComponent(z)}`)},[s]),Pe=r.useCallback(async()=>{if(!l||u){J(!1);return}J(!0),Fe("");try{const C=await T.instructor.listOccurrences({dateRange:`${p},${g}`,status:v,programUuid:N!=="all"?N:void 0});k(C),C.length===0?(I(""),P([])):C.some(z=>z.occurrenceUuid===j)||I(C[0].occurrenceUuid)}catch(C){const z=re(C,"Unable to load instructor classes.");z&&Fe(z),k([]),I(""),P([])}finally{J(!1)}},[j,l,u,N,g,p,v]),De=r.useCallback(async(C,z)=>{if(!C||!l)return;const Re=z?.silent===!0;Re||Be(!0);try{const Le=await T.instructor.getRoster(C);M(Le.occurrence),P(Le.rows)}catch(Le){if(!Re){const Je=re(Le,"Unable to load class roster.");Je&&be(Je),M(null),P([])}}finally{Re||Be(!1)}},[l]);r.useEffect(()=>{if(!l||n.pathname!=="/instructor/classes")return;let C=!1;Rn.current="";const z=new AbortController,Re=Je=>new Promise(Mt=>window.setTimeout(Mt,Je));return(async()=>{for(;!C&&!z.signal.aborted;)try{const Je=Rn.current!=="",Mt=await T.timetable.waitForTimetablePush({rangeStart:`${p}T00:00:00.000Z`,rangeEnd:`${g}T23:59:59.999Z`,cursor:Rn.current||null,timeoutSec:20},{signal:z.signal});if(C||z.signal.aborted)return;if(Mt.cursor&&(Rn.current=Mt.cursor),!Je||!Mt.changed||Mt.events.length===0)continue;const it=j?Mt.events.filter(Bs=>Bs.occurrenceUuid===j):[],Us=Mt.events.some(Bs=>Bs.eventType==="class_changed"||Bs.eventType==="instructors_changed"||Bs.eventType==="availability_changed"),ns=[];it.length>0&&ns.push(De(j,{silent:!0})),Us&&ns.push(Pe()),ps&&it.some(Bs=>Bs.eventType==="instructors_changed"||Bs.eventType==="availability_changed")&&ns.push(Is()),ns.length>0&&await Promise.allSettled(ns)}catch(Je){if(Je instanceof DOMException&&Je.name==="AbortError"||Je?.name==="AbortError"||C||z.signal.aborted)return;await Re(1500)}})(),()=>{C=!0,z.abort()}},[j,l,ps,Pe,De,n.pathname,Is,g,p]);const $e=r.useCallback(async()=>{const C=j||u;if(!C)return;const z=Do(Ve,t),Re=Do(_t,t),Le=Number(Xs);if(!z||!Re||new Date(Re).getTime()<=new Date(z).getTime()){be("Enter a valid start and end time.");return}if(!Number.isInteger(Le)||Le<=0){be("Capacity must be a whole number greater than zero.");return}Ae("edit-class");try{const Je=await T.instructor.updateOccurrence(C,{startAt:z,endAt:Re,capacity:Le});await T.instructor.updateTrialAvailability(C,Ht),k(Mt=>Mt.map(it=>it.occurrenceUuid===C?{...it,startAt:Je.startAt,endAt:Je.endAt,capacity:Je.capacity}:it)),M(Mt=>Mt&&{...Mt,startAt:Je.startAt,endAt:Je.endAt}),be("Class updated."),s.replace(`/instructor/classes?occurrence=${encodeURIComponent(C)}`),await De(C)}catch(Je){be(re(Je,"Unable to update the class."))}finally{Ae("")}},[j,Xs,_t,Ve,Ht,s,De,u,t]),dt=r.useCallback(async()=>{const C=j||u;if(!(!C||!je||!ks)){Ae("move-area");try{await T.instructor.moveOccurrenceArea(C,je,ks);const z=Ze.find(Re=>Re.uuid===ks);we(ks),ut(z?.name||""),Vt(!1),be("Class area updated."),await $s(C)}catch(z){be(re(z,"Unable to move the class area."))}finally{Ae("")}}},[j,ks,Ze,je,s,$s,u]),ze=r.useCallback(async C=>
2{if(!j)return;if(!C.personUuid){const Re=await T.instructor.getRoster(j);M(Re.occurrence),P(Re.rows);return}const z=await T.instructor.getRosterMember(j,C.personUuid);P(Re=>{const Le=it=>C.bookingUuid&&it.bookingUuid===C.bookingUuid||C.attendanceUuid&&it.attendanceUuid===C.attendanceUuid||C.personUuid&&it.personUuid===C.personUuid;if(!z)return Re.filter(it=>!Le(it));let Je=!1;const Mt=Re.map(it=>Le(it)?(Je=!0,z):it);return Je?Mt:[...Mt,z]})},[j]),et=r.useCallback(C=>{C.cashCollection&&(vs(C),Kt((C.cashCollection.amountMinor/100).toFixed(2)),os(""),bt(`roster-${j}-${C.personUuid}-${Date.now()}`))},[j]),Ct=r.useCallback(C=>{!C.personUuid||Ft||(_e(C),kt(null),Lt(!0))},[Ft]),Gt=r.useCallback(C=>{Lt(!1),C&&(C.value="",C.click())},[]),cs=r.useCallback(C=>{C&&C.type.startsWith("image/")?kt(C):(C&&be("Choose a photo from your phone."),_e(null))},[]),sa=r.useCallback(()=>{Ft||(kt(null),_e(null))},[Ft]),sn=r.useCallback(async C=>{if(!(!j||!Ue?.personUuid)){Pt(!0);try{const z=await T.instructor.updateRosterMemberPhoto(j,Ue.personUuid,C);if(!z)throw new Error("The saved member photo could not be loaded.");P(Re=>Re.map(Le=>Le.personUuid===z.personUuid?z:Le)),kt(null),_e(null),be(`Photo saved for ${z.displayName}.`)}catch(z){be(re(z,"Unable to save this member photo.")||"Unable to save this member photo.")}finally{Pt(!1)}}},[j,Ue]),Tt=r.useCallback(async()=>{if(!ht?.personUuid||!ht.cashCollection||!j)return;const C=Number(jt);if(!Number.isFinite(C)||C<=0){be("Enter the cash amount collected.");return}Ae(`cash:${ht.personUuid}`);try{await T.instructor.recordRosterCashCollection(j,ht.personUuid,{amount:C,locationNote:ts.trim()||void 0,idempotencyKey:Zs||`roster-${j}-${ht.personUuid}-${Date.now()}`}),vs(null),Kt(""),os(""),bt(""),await De(j),be(`${cl(Math.round(C*100),ht.cashCollection.currency)} cash recorded for ${ht.displayName}.`)}catch(z){be(re(z,"Unable to record this cash collection.")||"Unable to record this cash collection.")}finally{Ae("")}},[j,jt,Zs,ts,ht,De]),Ot=r.useCallback(()=>{bn.current+=1,xt(""),q([]),B(!1)},[]),xi=r.useCallback(()=>{Ot(),ct(!0)},[Ot]),Aa=r.useCallback(()=>{ct(!1),Ot()},[Ot]),gn=r.useCallback(async C=>{if(!C){F([]),A([]),D([]),It({closeoutTermUuid:"",closeoutCycleUuid:"",lessonPlanUuid:""});return}try{const[z,Re,Le]=await Promise.all([T.instructor.listCurriculumItems(C),T.instructor.listCurriculumTerms(C).catch(()=>[]),T.instructor.listProgramCycles(C).catch(()=>[])]);F(z),A(Re),D(Le),Re.length===0?It({closeoutTermUuid:""}):Re.some(Je=>Je.uuid===K)||It({closeoutTermUuid:Re[0]?.uuid??""}),Le.length===0?It({closeoutCycleUuid:""}):Le.some(Je=>Je.uuid===ye)||It({closeoutCycleUuid:Le[0]?.uuid??""})}catch(z){F([]),A([]),D([]),be(re(z,"Unable to load the programme curriculum. Refresh before confirming delivery.")||"Unable to load curriculum."),It({closeoutTermUuid:"",closeoutCycleUuid:"",lessonPlanUuid:""})}},[ye,K,It]),ji=r.useCallback(async()=>{u?await De(u):(await Pe(),j&&await De(j));const C=H||Ce?.programUuid||"";C&&await gn(C)},[Ce?.programUuid,j,H,gn,Pe,De,u]);r.useEffect(()=>{if(u){I(u),De(u);return}M(null),Pe()},[Pe,De,u]),r.useEffect(()=>{!j||u||De(j)},[j,De,u]),r.useEffect(()=>{gn(H)},[H,gn]),r.useEffect(()=>{if(!Xe)return;const C=st.trim();if(C.length<3){q([]),B(!1);return}const z=bn.current+1;bn.current=z,B(!0);const Re=window.setTimeout(()=>{T.people.listBookingCandidates(j,C).then(Le=>{bn.current===z&&q(Le)}).catch(Le=>{bn.current===z&&(be(re(Le,"Unable to search members and instructors.")||"Unable to search members and instructors."),q([]))}).finally(()=>{bn.current===z&&B(!1)})},300);return()=>window.clearTimeout(Re)},[j,Xe,st]),r.useEffect(()=>{if(!Ce?.programUuid||!_)return;const C=S?.lessonPlanUuid||Ce.lessonPlanUuid||"";w(z=>z.occurrenceUuid===Ce.occurrenceUuid?z.closeoutProgramUuid&&z.lessonPlanUuid===C?z:{...z,closeoutProgramUuid:Ce.programUuid??"",lessonPlanUuid:z.lessonPlanUuid||C}:{...ml(Ce.occurrenceUuid,Ce.programUuid??""),lessonPlanUuid:C})},[Ce?.lessonPlanUuid,Ce?.occurrenceUuid,Ce?.programUuid,_,S?.lessonPlanUuid,w]);async function Da(C,z){if(!j)return;const Re=C.bookingUuid||C.eventRegistrationUuid||C.attendanceUuid||C.personUuid||C.displayName,Le=`roster-state:${z}:${Re}`,Je=db(C.status);if(C.eventRegistrationUuid){if(z==="cancelled"){be("Event registrations must be cancelled by authorised staff in Admin.");return}
2if(z==="checked_in"&&C.formsDue&&Je!==z){be("Required forms must be completed before check in.");return}Ae(Le);try{const Us=Je===z?"undo":z==="checked_in"?"check_in":"no_show";await T.instructor.setEventRegistrationAttendance(j,C.eventRegistrationUuid,Us),be(Us==="undo"?`${C.displayName}'s attendance is ready to review.`:z==="checked_in"?`${C.displayName} checked in.`:`${C.displayName} marked as no show.`),await ze(C)}catch(Us){be(re(Us,"Unable to update event attendance.")||"Unable to update event attendance.")}finally{Ae("")}return}const Mt=mb(Je,z);let it=C;Ae(Le);try{for(const ns of Mt)if(ns==="clear_checked_in"){if(!it.bookingUuid)throw new Error("This check-in cannot be changed.");await T.instructor.undoCheckInBooking(it.bookingUuid)}else if(ns==="clear_no_show"){if(!it.bookingUuid)throw new Error("This no show cannot be changed.");await T.instructor.undoBookingNoShow(it.bookingUuid)}else if(ns==="restore_cancelled"){if(!it.personUuid)throw new Error("This cancelled booking cannot be restored.");await T.instructor.restoreBooking(j,it.personUuid),it=await T.instructor.getRosterMember(j,it.personUuid)??it}else if(ns==="set_checked_in")if(it.bookingUuid)await T.instructor.checkInBooking(it.bookingUuid);else if(it.personUuid)await T.instructor.checkInOccurrenceMember(j,it.personUuid);else throw new Error("This member cannot be checked in.");else if(ns==="set_no_show"){if(!it.bookingUuid)throw new Error("This booking cannot be marked as no show.");await T.instructor.markBookingNoShow(it.bookingUuid)}else if(ns==="set_cancelled")if(it.isWalkIn&&it.attendanceUuid&&!it.bookingUuid)await T.instructor.removeWalkIn(j,it.attendanceUuid);else if(it.bookingUuid)await T.instructor.removeBooking(it.bookingUuid);else throw new Error("This booking cannot be cancelled.");be(Je===z?z==="cancelled"?`${C.displayName} restored to this class.`:`${C.displayName}'s attendance is ready to review.`:z==="checked_in"?`${C.displayName} checked in.`:z==="no_show"?`${C.displayName} marked as no show.`:`${C.displayName} removed from this class.`),await ze(C)}catch(Us){be(re(Us,"Unable to update this booking.")||"Unable to update this booking.")}finally{Ae("")}}function xn(C){!C.bookingUuid||C.isEventAttendee||!["booked","checked_in"].includes(C.status)||(oe(null),es(C))}function La(C){oe(null),Wt(C),Ts(C.email||""),is(C.phone||"")}async function Ia(){if(!(!j||!Rt?.personUuid)){Ae(`contact:${Rt.personUuid}`);try{const C=await T.instructor.updateDrowTrialContact(j,Rt.personUuid,{email:Yt,phone:At});C&&P(z=>z.map(Re=>Re.personUuid===C.personUuid?C:Re)),be(`Contact details saved for ${Rt.displayName}.`),Wt(null)}catch(C){be(re(C,"Unable to save contact details.")||"Unable to save contact details.")}finally{Ae("")}}}async function yi(C){if(j){if(jr.has(C.uuid.trim().toLowerCase())){be(`${C.fullName} is already booked in this class.`);return}Ae(`add:${C.uuid}`);try{await T.instructor.addMemberToOccurrence(j,C.uuid),be(`${C.fullName} added to this class.`),ct(!1),xt(""),q([]);const z=await T.instructor.getRosterMember(j,C.uuid);z&&P(Re=>[...Re,z])}catch(z){be(re(z,"Unable to add this person.")||"Unable to add this person.")}finally{Ae("")}}}async function nn(){if(!j||!H){be("Select a program before completing the class.");return}const C={program_uuid:H,term_uuid:K||void 0,program_cycle_uuid:ye||void 0,curriculum_item_uuids:L,pressure_element_uuids:Z,debrief_notes:ce.trim()||void 0,requires_manager_review:ve,lesson_plan_uuid:ne||void 0,cycle_number:de.trim()!==""&&Number.isInteger(Number(de))&&Number(de)>0?Number(de):void 0,week_number:O.trim()!==""&&Number.isInteger(Number(O))&&Number(O)>0?Number(O):void 0,stripe_award_overrides:Object.entries(xe).map(([z,Re])=>({member_uuid:z,skip:!0,reason:Re.trim()||void 0}))};(me.trim()||Ne.trim())&&(C.incident_report={summary:me.trim()||void 0,notes:Ne.trim()||void 0}),Ae("close-class");try{const z=await T.instructor.closeOccurrence(j,C);be(z.closeout?.deliveryRecorded===!1?"Class completed.":`Class completed. ${z.closeout?.deliveryCount||0} curriculum points recorded.`),await W(),s.replace(`/instructor/classes?occurrence=${encodeURIComponent(j)}`),await De(j)}catch(z){const Re=re(z,"Unable to complete class.");Re&&be(Re)}finally{Ae("")}}async function ft(){if(j){Ae("reopen-class");try{const C=await T.instructor.reopenOccurrence(j);be(C.closeout?.retractedDeliveryCount&&C.closeout.retractedDeliveryCount>0?`Class reopened. ${C.closeout.retractedDeliveryCount} curriculum records retracted.`:"Class reopened."),await Pe(),await De(j)}catch(C){const z=re(C,"Unable to reopen class.");z&&be(z)}finally{Ae("")}}}function Ao(){Sn(""),ea((Ce?.bookedCount??0)>0),fs(!0)}async function kr(){const C=Pa.trim();if(!j||!C){be("Enter a cancellation reason.");return}Ae("cancel-class");try{const z=await T.instructor.cancelOccurrence(j,{reason:C,notifyBookedMembers:ss});fs(!1),M(Re=>Re&&{...Re,status:"cancelled",cancellationReason:z.cancellationReason||C}),k(Re=>Re.map(Le=>Le.occurrenceUuid===j?{...Le,status:"cancelled",cancellationReason:z.cancellationReason||C}:Le)),be(z.notifiedCount>0?`Class cancelled. ${z.notifiedCount} booked ${z.notifiedCount===1?"person was":"people were"} notified.`:"Class cancelled."),await Pe(),await De(j)}catch(z){const Re=re(z,"Unable to cancel class.");Re&&be(Re)}finally{Ae("")}}async function vi(){if(Cs)try{await navigator.clipboard.writeText(Cs),be("Conversion link copied.")}catch{be("Unable to copy the conversion link on this device.")}}const Os=r.useCallback(async(C,z)=>{const Re=C.conversionCta?.trialAccessUuid??"";
2if(Re){if(!z?.forceRefresh&&Ke?.conversionCta?.trialAccessUuid===Re&&Se?.url){ue(C);return}ue(C),pe(null),Me(""),ge(!0);try{const Le=await T.trials.createConversionLink(Re);pe(Le),Me("")}catch(Le){const Je=re(Le,"Unable to prepare the conversion QR right now.");Me(Je||"Unable to prepare the conversion QR right now.")}finally{ge(!1)}}},[Se?.url,Ke?.conversionCta?.trialAccessUuid]);if(!l)return e.jsx(Ye,{title:"Manage Classes",subtitle:"Instructor closeout is available to instructor and staff accounts.",activeTab:"none",backTo:"/staff-tools",children:e.jsx("div",{className:"member-panel-error",children:"This account cannot manage class closeout."})});if(m&&u){const C=`/instructor/classes?occurrence=${encodeURIComponent(u)}`;return e.jsxs(Ye,{title:"Edit class",subtitle:"Change the date, time or capacity for this class only.",activeTab:"classes",backTo:C,onRefresh:()=>$s(u),refresherDisabled:$||fe==="edit-class",children:[$?e.jsxs("div",{className:"member-panel-loading",children:[e.jsx(Te,{name:"crescent"}),e.jsx("span",{children:"Loading class..."})]}):e.jsxs("section",{className:"member-panel-card instructor-class-edit-page",children:[We?e.jsx("div",{className:"member-panel-error",role:"alert",children:We}):null,e.jsxs("div",{className:"instructor-class-edit-details",children:[e.jsx("strong",{children:Ce?.className||"Class"}),e.jsx("span",{children:Oe||Ce?.locationName||"Area not set"})]}),e.jsx(ao,{id:"instructor-class-edit-start",label:"Starts",presentation:"date-time",value:Ve,onChange:ot,disabled:fe==="edit-class"}),e.jsx(ao,{id:"instructor-class-edit-end",label:"Ends",presentation:"date-time",value:_t,min:Ve||void 0,onChange:Ns,disabled:fe==="edit-class"}),e.jsxs("label",{className:"member-input-label",children:["Capacity",e.jsx(Ds,{className:"member-input",type:"number",inputMode:"numeric",min:"1",step:"1",value:Xs,disabled:fe==="edit-class",onChange:z=>Ls(z.target.value)})]}),e.jsxs("label",{className:"member-input-label instructor-class-edit-switch-row",children:["Trial bookings",e.jsxs("span",{className:"instructor-class-edit-switch-control",children:[e.jsx("input",{type:"checkbox",checked:Ht,disabled:fe==="edit-class",onChange:z=>Q(z.target.checked)}),"Allow trials to book this class"]})]}),Ze.length>1?e.jsxs("div",{className:"instructor-class-edit-area-row",children:[e.jsxs("div",{children:[e.jsx("span",{className:"member-input-label",children:"Area"}),e.jsx("span",{children:Oe||"Current area"})]}),e.jsxs("button",{type:"button",className:"member-btn is-neutral",onClick:()=>{bs(Ze.find(z=>z.uuid!==je)?.uuid||""),Vt(!0)},disabled:fe!=="",children:[e.jsx(V,{icon:ni})," Move area"]})]}):null]}),e.jsxs("div",{className:"member-list-actions instructor-class-edit-actions",children:[e.jsx("button",{type:"button",className:"member-btn is-neutral",onClick:()=>s.push(C),disabled:fe==="edit-class",children:"Back"}),e.jsx("button",{type:"button",className:"member-btn is-solid",onClick:()=>{$e()},disabled:$||fe==="edit-class",children:fe==="edit-class"?e.jsxs(e.Fragment,{children:[e.jsx(Te,{name:"crescent"})," Saving"]}):"Save changes"})]}),e.jsx(Dt,{isOpen:!!lt,message:lt,duration:3e3,onDidDismiss:()=>be("")}),e.jsx(at,{isOpen:wt,onDidDismiss:()=>Vt(!1),children:e.jsxs("div",{className:"member-modal-sheet",children:[e.jsxs("div",{className:"member-modal-header",children:[e.jsx("h2",{children:"Move class area"}),e.jsx("p",{children:"This changes this class only."})]}),e.jsxs("label",{className:"member-input-label",children:["New area",e.jsx("select",{className:"member-input",value:ks,onChange:z=>bs(z.target.value),children:Ze.filter(z=>z.uuid!==je).map(z=>e.jsx("option",{value:z.uuid,children:z.name},z.uuid))})]}),e.jsxs("div",{className:"member-list-actions",children:[e.jsx("button",{type:"button",className:"member-btn is-neutral",onClick:()=>Vt(!1),disabled:fe==="move-area",children:"Cancel"}),e.jsx("button",{type:"button",className:"member-btn is-solid",onClick:()=>{dt()},disabled:!ks||fe==="move-area",children:fe==="move-area"?"Moving...":"Move area"})]})]})})]})}return e.jsxs(Ye,{title:h?"Class Debrief":"Class Management",subtitle:h?"Record what was covered, note any incidents, then close the class.":u?"Review attendance and help members before the class is completed.":"Open this workspace from a class details page in the timetable.",activeTab:"none",backTo:h&&j?`/instru
2ctor/classes?occurrence=${encodeURIComponent(j)}`:Ce?`/timetable?date=${encodeURIComponent(dl(Ce.startAt,t))}`:"/timetable",backToRoot:!h,hideHeading:!!u,onRefresh:ji,refresherDisabled:fe!=="",headingAction:u?void 0:e.jsx("button",{type:"button",className:"member-btn is-neutral",onClick:()=>{Pe()},disabled:G||fe!=="",children:"Refresh"}),children:[u?null:e.jsxs("section",{className:"member-panel-card",children:[e.jsx("h2",{children:"Open from timetable"}),e.jsx("p",{children:"Select a class from the timetable first, then use the instructor actions on the class details page."}),e.jsx("div",{className:"member-list-actions",children:e.jsx("button",{type:"button",className:"member-btn is-solid",onClick:()=>s.push("/timetable"),children:"Go to timetable"})})]}),ta?e.jsxs("div",{className:"member-panel-loading",children:[e.jsx(Te,{name:"crescent"}),e.jsx("span",{children:"Loading classes..."})]}):null,!ta&&We?e.jsx("div",{className:"member-panel-error",children:We}):null,!ta&&!We?e.jsxs(e.Fragment,{children:[!h&&Ce?e.jsxs("section",{className:"member-panel-card",children:[e.jsxs("div",{className:"member-row-main",children:[e.jsx("h2",{children:Ce.className}),e.jsx("span",{className:"member-pill is-accent",children:ll(Ce.status)})]}),e.jsxs("p",{children:[dl(Ce.startAt,t)," ."," ",ba(Ce.startAt,Ce.endAt,t)," ."," ",Ce.locationName||"Location not set"]}),Ce.status==="cancelled"?e.jsxs("div",{className:"instructor-cancelled-class-reason",role:"status",children:[e.jsx("strong",{children:"Class cancelled"}),e.jsx("span",{children:Ce.cancellationReason||"No cancellation reason was provided."})]}):null,Ce.status==="closed"?e.jsx("div",{className:"member-list-actions",children:e.jsx("button",{type:"button",className:"member-btn is-neutral",onClick:()=>{ft()},disabled:fe!=="",children:fe==="reopen-class"?"Reopening...":"Reopen class"})}):null,Ce.lessonPlanUuid||S?.lessonPlanUuid?e.jsxs("div",{className:"member-panel-list",children:[e.jsxs("div",{className:"member-panel-row",children:[e.jsxs("div",{className:"member-row-main",children:[e.jsx("strong",{children:"Linked lesson plan"}),e.jsx("span",{className:"member-pill is-accent",children:Ce.lessonPlanTitle||S?.lessonPlanTitle||"Linked"})]}),e.jsx("p",{children:Ce.lessonPlanUuid||S?.lessonPlanUuid})]}),e.jsx("div",{className:"member-list-actions",children:e.jsx("button",{type:"button",className:"member-btn is-solid",onClick:()=>ee(Ce.lessonPlanUuid||S?.lessonPlanUuid),children:"Open lesson plan"})})]}):null]}):null,!h&&Ce&&Ce.status!=="cancelled"?e.jsx(Kp,{occurrenceUuid:Ce.occurrenceUuid,timezone:t},Ce.occurrenceUuid):null,!h&&Ce?.status!=="cancelled"?e.jsxs("section",{className:"member-panel-card",children:[e.jsxs("div",{className:"member-row-main",children:[e.jsx("h2",{children:"Attendance"}),e.jsx("button",{type:"button",className:"member-btn is-neutral member-btn-compact",onClick:xi,children:"Add person"})]}),e.jsx("div",{className:`instructor-roster-tabs${zt?" is-event":""}`,role:"tablist","aria-label":"Attendance groups",children:zt?e.jsxs(e.Fragment,{children:[e.jsxs("button",{type:"button",className:Ie!=="cancelled"?"is-active":"",onClick:()=>ie("members"),children:["Attendees ",e.jsx("span",{children:Ua.length})]}),e.jsxs("button",{type:"button",className:Ie==="cancelled"?"is-active":"",onClick:()=>ie("cancelled"),children:["Cancelled ",e.jsx("span",{children:fn.length})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("button",{type:"button",className:Ie==="members"?"is-active":"",onClick:()=>ie("members"),children:["Members ",e.jsx("span",{children:gr.length})]}),e.jsxs("button",{type:"button",className:Ie==="trials"?"is-active":"",onClick:()=>ie("trials"),children:["Trials ",e.jsx("span",{children:xr.length})]}),e.jsxs("button",{type:"button",className:`is-cancelled-tab${Ie==="cancelled"?" is-active":""}`,onClick:()=>ie("cancelled"),"aria-label":`${fn.length} cancelled bookings`,title:"Cancelled bookings",children:[e.jsx(V,{icon:pa}),e.jsx("span",{children:fn.length})]})]})}),ke?e.jsxs("div",{className:"member-panel-loading",children:[e.jsx(Te,{name:"crescent"}),e.jsx("span",{children:"Loading roster..."})]}):Mn.length===0?e.jsx("p",{children:zt?Ie==="cancelled"?"No cancelled attendees.":"No attendees in this event."
2:Ie==="trials"?"No trial attendees in this class.":Ie==="cancelled"?"No cancelled bookings.":"No regular members in this class."}):e.jsx("div",{className:"member-panel-list instructor-roster-list",children:Mn.map(C=>e.jsxs("div",{className:`member-panel-row instructor-roster-row${bb(C)}${C.isFirstProgrammeClass?" is-first-class":""}`,children:[e.jsxs("div",{className:"instructor-roster-person",children:[e.jsx("button",{type:"button",className:"instructor-roster-avatar-btn","aria-label":`Add profile photo for ${C.displayName}`,title:C.personUuid?"Add or replace profile photo":"Profile photo is unavailable",onClick:()=>Ct(C),disabled:!C.personUuid||Ft,children:C.avatarUrl?e.jsx("img",{src:C.avatarUrl,alt:""}):e.jsx("span",{children:C.displayName.charAt(0).toUpperCase()})}),e.jsxs("div",{className:"instructor-roster-identity",children:[e.jsxs("div",{className:"instructor-roster-name-row",children:[e.jsx(Wp,{row:C,programUuid:Ce?.programUuid||null,onProfile:Nr,onNotes:Ea}),C.isTrialAttendee?e.jsx("span",{className:"instructor-drow-trial-badge",children:C.trialBadge||(C.isDrowTrial?"DROW":"TRIAL")}):null,C.isEventAttendee?e.jsx("span",{className:"instructor-first-class-badge",children:"EVENT"}):null,C.formsDue?e.jsx("span",{className:"instructor-drow-trial-badge",children:"FORMS DUE"}):null,C.isFirstProgrammeClass?e.jsx("span",{className:"instructor-first-class-badge",children:"FIRST CLASS"}):null]}),e.jsxs("small",{children:[C.isEventAttendee?`Event . ${[C.eventTitle,C.ticketName].filter(Boolean).join(" . ")}`:C.isTrialAttendee?`Trial . Class ${C.programmeVisitNumber}`:C.isWalkIn&&!C.personUuid?"Walk in":`Member . Class ${C.programmeVisitNumber}`,!C.grading&&C.levelLabel?` . ${C.levelLabel}`:"",C.stripeAward.decision==="awarded"?" . Stripe awarded":"",C.stripeAward.decision==="skipped"?" . Stripe skipped":""]})]}),e.jsx("button",{type:"button",className:"instructor-more-menu-btn","aria-label":`More actions for ${C.displayName}`,title:"More actions",onClick:()=>oe(C),children:e.jsx(V,{icon:Ya})})]}),C.isDrowTrial&&pl(C)?e.jsxs("button",{type:"button",className:"instructor-contact-warning",onClick:()=>La(C),children:[pl(C),". Add details"]}):null,hl(C,t)?e.jsx("p",{children:hl(C,t)}):null,C.isTrialAttendee&&C.conversionCta?.enabled?e.jsxs("div",{className:"instructor-trial-summary",children:[e.jsx("p",{children:qp(C.conversionCta.endsAt,C.conversionCta.offerMode)||`Trial ${ll(C.conversionCta.status||"active")}`}),e.jsxs("button",{type:"button",onClick:()=>{Os(C)},children:[e.jsx(V,{icon:ja})," Trial QR"]})]}):null,C.cashCollection?e.jsxs("div",{className:`instructor-cash-due${C.cashCollection.status==="overdue"?" is-overdue":""}`,children:[e.jsxs("div",{children:[e.jsx("strong",{children:C.cashCollection.status==="overdue"?"Cash overdue":"Cash due today"}),e.jsxs("small",{children:[cl(C.cashCollection.amountMinor,C.cashCollection.currency)," for ",C.cashCollection.membershipName||"membership"]})]}),e.jsx("button",{type:"button",onClick:()=>et(C),disabled:fe!=="",children:"Record cash"})]}):null,(C.bookingUuid||C.eventRegistrationUuid||C.attendanceUuid||C.personUuid)&&!(C.isEventAttendee&&oa(C))?e.jsx("div",{className:"instructor-roster-actions instructor-attendance-switch",role:"group","aria-label":`Attendance for ${C.displayName}`,...o.handlers,children:Jp().filter(z=>!C.isEventAttendee||z!=="cancelled").map(z=>{const Re=C.bookingUuid||C.eventRegistrationUuid||C.attendanceUuid||C.personUuid||C.displayName,Le=`roster-state:${z}:${Re}`,Je=fe.startsWith("roster-state:")&&fe.endsWith(`:${Re}`),Mt=C.status.toLowerCase()===z,it=z==="checked_in"?si:z==="no_show"?Hr:pa,Us=z==="checked_in"?"is-attended-action":z==="no_show"?"is-no-show-action":"is-cancel-action",ns=z==="checked_in"?"Check in":z==="no_show"?"No show":"Cancel booking",Bs=z==="checked_in"?"CHECK IN":z==="no_show"?"NO SHOW":"CANCEL";return e.jsxs("button",{type:"button",className:`instructor-roster-icon-btn ${Us}${Mt?" is-active":""}`,"aria-label":`${Mt?"Undo ":""}${ns.toLowerCase()} for ${C.displayName}`,title:Mt?`Undo ${ns.toLowerCase()}`:ns,onClick:qu=>{o.allowsClick(qu)&&Da(C,z)}
2,disabled:Je||z==="checked_in"&&C.formsDue||z!=="cancelled"&&!C.personUuid&&!C.bookingUuid&&!C.eventRegistrationUuid,children:[fe===Le?e.jsx(Te,{name:"crescent"}):e.jsx(V,{icon:it,"aria-hidden":"true"}),e.jsx("span",{className:"instructor-roster-action-label",children:Bs})]},z)})}):null]},`${C.bookingUuid||C.eventRegistrationUuid||C.attendanceUuid||C.displayName}`))})]}):null,!h&&Ce?.status==="scheduled"?e.jsxs("section",{className:"instructor-close-class-panel",children:[e.jsxs("button",{type:"button",className:"member-btn instructor-close-class-btn",onClick:()=>s.push(`/instructor/classes?occurrence=${encodeURIComponent(j)}&view=debrief`),disabled:ws>0,children:[e.jsx(V,{icon:qo})," Complete class"]}),e.jsx("p",{children:ws>0?`Record attendance for ${ws} ${ws===1?"person":"people"} before completing this class.`:"Attendance is complete. You can now review and complete the class."}),e.jsxs("button",{type:"button",className:"member-btn instructor-class-more-btn",onClick:()=>qt(!0),disabled:fe!=="",children:[e.jsx(V,{icon:Ya})," More"]})]}):null,h&&Ce?.status==="closed"?e.jsxs("section",{className:"member-panel-card",children:[e.jsx("h2",{children:"Class completed"}),e.jsx("p",{children:Ce.className}),Tn?e.jsx("p",{role:"alert",children:Tn}):tn?e.jsxs(e.Fragment,{children:[e.jsx("h3",{children:"Class notes"}),e.jsx("p",{children:tn.payload.debrief?.notes||"No notes recorded."}),e.jsx("h3",{children:"Curriculum delivered"}),(tn.payload.delivery?.curriculum_item_uuids||[]).map(C=>e.jsx("p",{children:U.find(z=>z.uuid===C)?.title||"Recorded curriculum point"},C)),tn.payload.incident_report?e.jsxs("p",{children:[tn.payload.incident_report.summary," ",tn.payload.incident_report.notes]}):null]}):e.jsx("p",{children:"Loading saved class recordâ¦"}),e.jsx("button",{type:"button",className:"member-btn is-neutral",onClick:()=>s.replace(`/instructor/classes?occurrence=${encodeURIComponent(Ce.occurrenceUuid)}`),children:"Back to class"})]}):null,h&&Ce&&Ce.status!=="closed"?e.jsxs(e.Fragment,{children:[e.jsxs("section",{className:"member-panel-card instructor-debrief-summary",children:[e.jsx("h2",{children:Ce.className}),e.jsxs("p",{children:[ba(Ce.startAt,Ce.endAt,t)," . ",Ce.locationName||"Location not set"]}),e.jsxs("div",{className:`instructor-attendance-gate${ws>0?" is-pending":""}`,children:[e.jsx(V,{icon:ws>0?am:rm}),e.jsxs("span",{children:[e.jsx("strong",{children:ws>0?`${ws} attendance records pending`:"Attendance complete"}),e.jsx("small",{children:ws>0?"Go back and resolve every booking before completing the class.":"Every booking has been resolved."})]})]})]}),e.jsxs("section",{className:"member-panel-card instructor-debrief-form",children:[Gs(i)?e.jsx("button",{type:"button",className:"member-btn is-neutral",onClick:()=>s.push(`/staff-tools/lesson-plans?mode=record&programme_uuid=${encodeURIComponent(Ce.programUuid||"")}&occurrence_uuid=${encodeURIComponent(Ce.occurrenceUuid)}`),children:"Describe this class with Corner"}):null,E?e.jsxs("div",{className:"member-input-group",children:[e.jsxs("p",{children:["Plan from Class Plans: ",E.title]}),e.jsx("button",{type:"button",className:"member-btn is-neutral",onClick:()=>It({lessonPlanUuid:E.uuid}),children:ne===E.uuid?"Plan selected for this closeout":"Use this plan for closeout"}),e.jsx("p",{children:"Check the delivered curriculum below. Selecting a plan does not confirm delivery."})]}):null,y.some(C=>C.stripeAward.eligible)?e.jsxs("div",{className:"instructor-stripe-awards",children:[e.jsx("div",{className:"member-row-main",children:e.jsx("h2",{children:"Attendance stripes"})}),e.jsx("p",{children:"Everyone listed will receive this stripe when you complete the class. Select someone only if they should not receive it."}),y.filter(C=>C.stripeAward.eligible&&C.personUuid).map(C=>{const z=C.personUuid||"",Re=Object.prototype.hasOwnProperty.call(xe,z);return e.jsxs("div",{className:"instructor-stripe-award-row",children:[e.jsxs("label",{className:"instructor-review-checkbox",children:[e.jsx("input",{type:"checkbox",checked:Re,onChange:Le=>It({stripeAwardSkips:Le.target.checked?{...xe,[z]:""}:Object.fromEntries(Object.entries(xe).filter(([Je])=>Je!==z))})}),e.jsxs("span",{children:[e.jsx("strong",{children:C.displayName}),e.jsx("small",{children:Re?`Do not award ${C.stripeAward.stripeLabel||"attendance stripe"}
2`:`Will receive ${C.stripeAward.stripeLabel||"attendance stripe"}`})]})]}),Re?e.jsx("input",{className:"member-input",maxLength:500,value:xe[z]||"",onChange:Le=>It({stripeAwardSkips:{...xe,[z]:Le.target.value}}),placeholder:"Optional reason"}):null]},z)})]}):null,U.length?e.jsxs("div",{className:"instructor-curriculum-browser",children:[e.jsxs("div",{className:"member-row-main",children:[e.jsx("h2",{children:"Curriculum covered"}),e.jsxs("span",{className:"member-pill",children:[L.length," selected"]})]}),e.jsxs("p",{children:["Only curriculum assigned to ",Ce.programName||"this programme"," is shown."]}),e.jsxs("div",{className:"instructor-curriculum-tools",children:[e.jsx("input",{className:"member-input",value:hs,onChange:C=>Js(C.target.value),placeholder:"Search this programme's curriculum"}),e.jsx("button",{type:"button",className:"instructor-curriculum-clear",onClick:()=>It({closeoutCurriculumItemUuids:[]}),disabled:L.length===0,children:"Clear"})]}),e.jsx("div",{className:"instructor-curriculum-tree",children:gi.map(C=>e.jsx(vu,{item:C,childrenByParent:yr,selectedUuids:L,searchActive:hs.trim()!=="",onToggle:(z,Re)=>It({closeoutCurriculumItemUuids:Re?[...L,z]:L.filter(Le=>Le!==z)})},C.uuid))})]}):null,e.jsxs("label",{className:"member-input-label",children:["Class notes",e.jsx("textarea",{className:"member-input member-textarea",value:ce,onChange:C=>It({closeoutNotes:C.target.value}),placeholder:"What was covered and anything the next instructor should know."})]}),e.jsxs("div",{className:"instructor-incident-fields",children:[e.jsx("h2",{children:"Accident or incident"}),e.jsxs("label",{className:"member-input-label",children:["Summary",e.jsx("input",{className:"member-input",value:me,onChange:C=>It({incidentSummary:C.target.value}),placeholder:"Optional short summary"})]}),e.jsxs("label",{className:"member-input-label",children:["Details",e.jsx("textarea",{className:"member-input member-textarea",value:Ne,onChange:C=>It({incidentNotes:C.target.value}),placeholder:"Optional details and action taken"})]}),e.jsxs("label",{className:"instructor-review-checkbox",children:[e.jsx("input",{type:"checkbox",checked:ve,onChange:C=>It({requiresManagerReview:C.target.checked})}),e.jsxs("span",{children:[e.jsx("strong",{children:"Manager follow up needed"}),e.jsx("small",{children:"Use this for a safety issue, complaint or anything that needs review."})]})]})]})]}),e.jsx("button",{type:"button",className:"member-btn instructor-final-close-btn",onClick:()=>{nn()},disabled:fe!==""||ws>0,children:fe==="close-class"?e.jsxs(e.Fragment,{children:[e.jsx(Te,{name:"crescent"})," Completing class"]}):e.jsxs(e.Fragment,{children:[e.jsx(V,{icon:qo})," Complete class"]})}),ws>0?e.jsx("p",{className:"instructor-close-blocked-copy",children:"Cannot complete this class until attendance is complete."}):null]}):null]}):null,e.jsx(Fp,{target:vr,onClose:()=>Ea(null),onChanged:async()=>{j&&await De(j,{silent:!0})}}),e.jsx(at,{isOpen:ps,onDidDismiss:()=>Qt(!1),children:e.jsx(To,{contextLabel:Ce?`${Ce.className} · ${ba(Ce.startAt,Ce.endAt,t)}`:void 0,directory:hi,availability:pi,draft:{leadWpUserId:mn,assistantWpUserIds:hn},loading:dn,saving:fe==="save-instructor-rota",onChange:C=>{Pn(C.leadWpUserId),_s(C.assistantWpUserIds)},onCancel:()=>Qt(!1),onSave:()=>{bi()}})}),e.jsx(at,{isOpen:ls,onDidDismiss:()=>qt(!1),children:e.jsxs("div",{className:"member-modal-sheet instructor-class-actions-sheet",children:[e.jsxs("div",{className:"member-modal-header",children:[e.jsx("h2",{children:"Class actions"}),e.jsx("p",{children:Ce?.className||"Choose an action for this class."})]}),e.jsxs("div",{className:"instructor-action-menu",children:[e.jsxs("button",{type:"button",className:"member-btn is-neutral",onClick:()=>{fi()},children:[e.jsx(V,{icon:ai})," Edit class"]}),c&&!zt?e.jsx("button",{type:"button",className:"member-btn is-neutral",onClick:()=>{qt(!1),Is()},children:"Assign instructors"}):null,e.jsxs("button",{type:"button",className:"member-btn is-danger",onClick:()=>{qt(!1),Ao()},children:[e.jsx(V,{icon:pa})," Cancel class"]})]}),e.jsx("button",{type:"button",className:"member-btn is-neutral",onClick:()=>qt(!1),children:"Close"})]})}),e.jsx(ec,{isOpen:rt,header:Ue?`Add photo for ${Ue.displayName}
2`:"Add member photo",onDidDismiss:C=>{Lt(!1),(C.detail.role==="cancel"||C.detail.role==="backdrop")&&_e(null)},buttons:[{text:"Take photo",icon:yo,handler:()=>Gt(Ta.current)},{text:"Choose from library",icon:im,handler:()=>Gt(_a.current)},{text:"Cancel",role:"cancel"}]}),e.jsx("input",{ref:Ta,className:"instructor-photo-capture-input",type:"file",accept:"image/*",capture:"environment","aria-hidden":"true",tabIndex:-1,onChange:C=>{cs(C.currentTarget.files?.[0]??null),C.currentTarget.value=""}}),e.jsx("input",{ref:_a,className:"instructor-photo-capture-input",type:"file",accept:"image/*","aria-hidden":"true",tabIndex:-1,onChange:C=>{cs(C.currentTarget.files?.[0]??null),C.currentTarget.value=""}}),e.jsx(at,{isOpen:!!(Ue&&He),canDismiss:!Ft,onDidDismiss:sa,children:Ue&&He?e.jsx(rb,{file:He,memberName:Ue.displayName,saving:Ft,onCancel:sa,onError:be,onSave:sn}):null}),e.jsx(at,{isOpen:pr,onDidDismiss:()=>fs(!1),children:e.jsxs("div",{className:"member-modal-sheet instructor-cancel-class-sheet",children:[e.jsxs("div",{className:"member-modal-header",children:[e.jsx("h2",{children:"Cancel class"}),e.jsx("p",{children:"Cancel this class only. The reason will be shown to members."})]}),e.jsxs("label",{className:"member-input-label",children:["Cancellation reason",e.jsx("textarea",{className:"member-input member-textarea",value:Pa,onChange:C=>Sn(C.target.value),maxLength:2e3,placeholder:"Tell members why this class is cancelled"})]}),(Ce?.bookedCount??0)>0?e.jsxs("label",{className:"instructor-review-checkbox",children:[e.jsx("input",{type:"checkbox",checked:ss,onChange:C=>ea(C.target.checked)}),e.jsxs("span",{children:[e.jsx("strong",{children:"Notify booked members"}),e.jsx("small",{children:"Send the class cancellation message with this reason."})]})]}):null,e.jsxs("div",{className:"member-list-actions",children:[e.jsx("button",{type:"button",className:"member-btn is-neutral",onClick:()=>fs(!1),disabled:fe==="cancel-class",children:"Back"}),e.jsx("button",{type:"button",className:"member-btn is-danger",onClick:()=>{kr()},disabled:fe==="cancel-class"||Pa.trim()==="",children:fe==="cancel-class"?e.jsxs(e.Fragment,{children:[e.jsx(Te,{name:"crescent"})," Cancelling"]}):"Cancel class"})]})]})}),e.jsx(at,{isOpen:!!Y,onDidDismiss:()=>oe(null),children:e.jsxs("div",{className:"member-modal-sheet instructor-more-actions-sheet",children:[e.jsxs("div",{className:"member-modal-header",children:[e.jsx("h2",{children:Y?.displayName||"Member actions"}),e.jsx("p",{children:"Choose what you need to do for this booking."})]}),e.jsxs("div",{className:"instructor-action-menu",children:[e.jsx("button",{type:"button",className:"member-btn is-neutral",disabled:!Y?.personUuid,onClick:()=>{Y?.personUuid&&Nr(Y.personUuid)},children:"View full profile"}),Y?.isDrowTrial?e.jsx("button",{type:"button",className:"member-btn is-neutral",onClick:()=>La(Y),children:"Update contact details"}):null,e.jsx("button",{type:"button",className:"member-btn is-neutral",disabled:!Y?.bookingUuid||Y.isEventAttendee||!["booked","checked_in"].includes(Y.status),onClick:()=>Y&&xn(Y),children:"Reschedule"}),Y?.conversionCta?.enabled?e.jsx("button",{type:"button",className:"member-btn is-neutral",onClick:()=>{const C=Y;oe(null),Os(C)},children:"Trial QR"}):null,Y?.isEventAttendee?null:Y&&oa(Y)?e.jsx("button",{type:"button",className:"member-btn is-neutral",disabled:fe.startsWith("roster-state:"),onClick:()=>{const C=Y;oe(null),Da(C,"cancelled")},children:"Restore booking"}):e.jsx("button",{type:"button",className:"member-btn is-danger",disabled:!Y||fe.startsWith("roster-state:"),onClick:()=>{const C=Y;C&&(oe(null),Da(C,"cancelled"))},children:"Cancel booking"})]}),e.jsx("button",{type:"button",className:"member-btn is-neutral",onClick:()=>oe(null),children:"Close"})]})}),e.jsx(at,{isOpen:!!Rt,onDidDismiss:()=>Wt(null),children:e.jsxs("div",{className:"member-modal-sheet instructor-contact-edit-sheet",children:[e.jsxs("div",{className:"member-modal-header",children:[e.jsxs("h2",{children:["Contact details for ",Rt?.displayName||"DROW trial"]}),e.jsx("p",{children:"Ask for the details at the gym. Attendance can still be recorded without them."})]}),e.jsxs("label",{className:"member-input-label",children:["Email",e.jsx("input",{className:"member-input",type:"email",inputMode:"email",autoComplete:"email",value:Yt,onChange:C=>Ts(C.target.value),placeholder:"Email address"})]}),e.jsxs("label",{className:"member-input-label",children:["Phone",e.jsx("input",{className:"member-input",type:"tel",inputMode:"tel",autoComplete:"tel",value:At,onChange:C=>is(C.target.value),placeholder:"Phone number",maxLength:50})]}),e.jsxs("div",{className:"member-list-actions",children:[e.jsx("button",{type:"button",className:"member-btn is-neutral",onClick:()=>Wt(null),disabled:fe.startsWith("contact:"),children:"Cancel"}),e.jsx("button",{type:"button",className:"member-btn is-solid",onClick:()=>{Ia()},disabled:fe.startsWith("contact:")||Yt.trim()===""&&At.trim()==="",children:fe.startsWith("contact:")?e.jsxs(e.Fragment,{children:[e.jsx(Te,{name:"crescent"})," Saving"]}):"Save details"})]})]})}),Rs&&Ce?e.jsx(Lp,{row:Rs,occurrence:Ce,timezone:t,onClose:()=>es(null),onSaved:()=>{es(null),be("Booking rescheduled."),De(j),Pe()}},Rs.bookingUuid):null,e.jsx(at,{isOpen:!!ht,onDidDismiss:()=>{vs(null),Kt(""),os(""),bt("")},children:e.jsxs("div",{className:"member-modal-sheet instructor-cash-collection-sheet",children:[e.jsxs("div",{className:"member-modal-header",children:[e.jsxs("h2",{children:["Record cash from ",ht?.displayName||"member"]}),e.jsx("p",{children:"This records who collected the money and removes it from the cash due list."})]}),e.jsxs("label",{className:"member-input-label",children:["Amount collected",e.jsx(Ds,{className:"member-input",type:"number",min:"0.01",step:"0.01",inputMode:"decimal",value:jt,onChange:C=>Kt(C.target.value)})]}),e.jsxs("label",{className:"member-input-label",children:["Cash location",e.jsx("input",{className:"member-input",type:"text",maxLength:255,value:ts,onChange:C=>os(C.target.value),placeholder:"For example, office safe"}),e.jsx("small",{children:"Enter where the cash was left, such as the office safe. Leave blank if it was handed straight to the owner."})]}),e.jsxs("div",{className:"member-list-actions staff-cash-actions",children:[e.jsx("button",{type:"button",className:"member-btn is-neutral",onClick:()=>{vs(null),os("")},disabled:fe.startsWith("cash:"),children:"Cancel"}),e.jsx("button",{type:"button",className:"member-btn is-solid",onClick:()=>{Tt()},disabled:fe.startsWith("cash:"),children:fe.startsWith("cash:")?e.jsxs(e.Fragment,{children:[e.jsx(Te,{name:"crescent"})," Saving"]}):"Confirm cash collected"})]})]})}),e.jsx(at,{isOpen:Xe,onDidDismiss:Aa,children:e.jsxs("div",{className:"member-modal-sheet instructor-add-member-sheet",children:[e.jsxs("div",{className:"member-modal-header",children:[e.jsx("h2",{children:"Add person to class"}),e.jsx("p",{children:"Search members, trials, and eligible instructors, then add the correct person."})]}),e.jsxs("div",{className:"instructor-member-search",children:[e.jsx("input",{className:"member-input",value:st,onInput:C=>xt(C.currentTarget.value),placeholder:"Name or email",autoComplete:"off",enterKeyHint:"search"}),e.jsx("span",{className:`instructor-member-search-status${te?" is-loading":""}`,"aria-hidden":"true",children:e.jsx("span",{className:`member-search-loader${te?" is-loading":""}`})})]}),st.trim().length>0&&st.trim().length<3?e.jsx("p",{className:"member-panel-help",children:"Type at least 3 letters."}):null,!te&&st.trim().length>=3&&Et.length===0?e.jsx("p",{className:"member-panel-help",children:"No matching people found."}):null,e.jsx("div",{className:"member-panel-list",children:Et.map(C=>{const z=jr.has(C.uuid.trim().toLowerCase());return e.jsxs("div",{className:`member-panel-row instructor-search-result${z?" is-already-booked":""}`,children:[e.jsxs("div",{className:"member-row-main",children:[e.jsx("strong",{children:C.fullName}),e.jsx("span",{className:`member-pill${C.isTrialCandidate||C.isInstructorCandidate?" is-accent":""}`,children:C.isInstructorCandidate?"Instructor":C.isTrialCandidate?"Trial":C.memberType})]}),e.jsx("p",{children:C.email||C.memberIdDisplay}),C.membershipName?e.jsx("small",{children:C.membershipName}):null,e.jsx("button",{type:"button",className:`member-btn${z?" is-booked":" is-accent-outline"}`,onClick:()=>{yi(C)},disabled:z||fe===`add:${C.uuid}`,children:z?"Already booked":fe===`add:${C.uuid}`?"Adding":"Add to class"})]},C.uuid)})}),e.jsx("button",{type:"button",className:"member-btn is-neutral",onClick:Aa,children:"Close"})]})}),e.jsx(at,{isOpen:!!Ke,onDidDismiss:()=>{ue(null),pe(null),Me(""),ge(!1)},keepContentsMounted:!0,children:e.jsxs("div",{className:"member-modal-sheet member-conversion-share-sheet",children:[e.jsxs("div",{className:"member-modal-header",children:[e.jsx("h2",{children:Ke?`Share conversion QR for ${Ke.displayName}`:"Share conversion QR"}),e.jsx("p",{children:"Show this QR to the member so they land directly in the matching trial-to-membership conversion flow."})]}),ae?e.jsxs("div",{className:"member-conversion-share-loading",children:[e.jsx(Te,{name:"crescent"}),e.jsx("span",{children:"Preparing conversion QR..."})]}):qe?e.jsxs("div",{className:"member-conversion-share-error",role:"alert",children:[e.jsxs("section",{className:"member-panel-card",children:[e.jsx("h2",{children:"QR code could not be prepared"}),e.jsx("p",{children:qe})]}),e.jsxs("div",{className:"member-list-actions",children:[e.jsx("button",{type:"button",className:"member-btn is-
2primary",onClick:()=>{Ke&&Os(Ke,{forceRefresh:!0})},disabled:!Ke,children:"Try again"}),e.jsx("button",{type:"button",className:"member-btn is-neutral",onClick:()=>{ue(null),pe(null),Me(""),ge(!1)},children:"Close"})]})]}):e.jsxs("div",{className:"member-conversion-share-content",children:[e.jsxs("section",{className:"member-panel-card",children:[e.jsx("h2",{children:"Conversion link"}),e.jsx("div",{className:"member-input-group",children:e.jsxs("label",{className:"member-input-label",children:["Share link",e.jsx("input",{className:"member-input",value:Cs,readOnly:!0})]})}),e.jsx("div",{className:"member-list-actions",children:e.jsx("button",{type:"button",className:"member-btn is-neutral",onClick:()=>{vi()},disabled:!Cs,children:"Copy link"})})]}),e.jsxs("section",{className:"member-panel-card member-conversion-share-qr-card",children:[e.jsx("h2",{children:"QR code"}),fr?e.jsx("img",{src:fr,alt:"Conversion QR code",className:"member-conversion-share-qr-image"}):e.jsx("p",{children:"QR preview unavailable right now."}),e.jsx("p",{className:"member-conversion-share-note",children:"Scanning this code opens the secure conversion flow and starts with membership plan choice."})]}),e.jsxs("div",{className:"member-list-actions",children:[e.jsx("button",{type:"button",className:"member-btn is-neutral",onClick:()=>{Ke&&Os(Ke,{forceRefresh:!0})},disabled:!Ke,children:"Refresh QR"}),e.jsx("button",{type:"button",className:"member-btn is-neutral",onClick:()=>{ue(null),pe(null),Me(""),ge(!1)},children:"Close"})]})]})]})}),e.jsx(Dt,{isOpen:!!lt,message:lt,duration:2500,position:"top",onDidDismiss:()=>be("")})]})}function gb({timezone:t="UTC"}){const{requests:s,loading:n,error:a,reload:i}=Jc(),[o,l]=r.useState(!1),[c,u]=r.useState(""),d=r.useRef(!1),[h,m]=r.useState([]),f=(s?.rows||[]).filter(p=>!h.includes(p.occurrenceUuid)&&Date.parse(p.startAt)>Date.now()),b=async(p,g)=>{if(!(d.current||p.length===0)){d.current=!0,l(!0),u("");try{await T.instructor.setRequestedAvailability(p,g),m(v=>[...v,...p]),Zc(),await i()&&m([])}catch(v){u(v instanceof Error?v.message:"Unable to save. Please try again."),await i()}finally{d.current=!1,l(!1)}}};return e.jsxs("section",{className:"member-timetable-cards","aria-label":"Availability requests",onPointerDown:p=>p.stopPropagation(),children:[e.jsx("h2",{children:"Availability requests"}),n?e.jsx("p",{role:"status",children:"Loading requests..."}):null,a||c?e.jsxs("p",{role:"alert",children:[c||a," ",e.jsx("button",{className:"member-btn is-neutral",onClick:()=>{i()},children:"Refresh"})]}):null,!n&&!a&&f.length===0?e.jsx("p",{children:"No classes need your answer."}):null,f.length>0?e.jsx("button",{className:"member-btn is-solid",disabled:o,onClick:()=>{b(f.map(p=>p.occurrenceUuid),"available")},children:o?"Saving...":"Available for all"}):null,s&&s.totalCount>s.rows.length?e.jsxs("p",{children:["Showing the next ",s.rows.length," requests. More will appear as you answer."]}):null,f.map(p=>e.jsxs("article",{className:"member-session-card",children:[e.jsx("h3",{className:"member-session-title",children:p.className}),e.jsx("p",{className:"member-session-time",children:new Date(p.startAt).toLocaleString("en-GB",{timeZone:t,weekday:"long",day:"numeric",month:"long",hour:"2-digit",minute:"2-digit"})}),e.jsx("p",{children:p.locationName}),e.jsxs("div",{className:"member-forms-banner-actions",children:[e.jsx("button",{className:"member-btn is-solid",disabled:o,onClick:()=>{b([p.occurrenceUuid],"available")},children:"Available"}),e.jsx("button",{className:"member-btn is-neutral",disabled:o,onClick:()=>{b([p.occurrenceUuid],"not_available")},children:"Unavailable"})]})]},p.requestId))]})}const xb="--member-calendar-track-offset";function ga(t,s,n=xb){let a=0,i=null,o=null;const l=h=>{h?.style.setProperty(n,`${a}px`)},c=()=>{i!==null&&(s(i),i=null),o=null};return{cancel:c,flush:(h,m=a)=>{a=m,c(),l(h)},getOffset:()=>a,queue:(h,m)=>{a=m,o=h,i===null&&(i=t(()=>{i=null;const f=o;o=null,l(f)}))}}}function Gr(t,s,n){let a=!1,i=null,o=null,l=null;const c=()=>{a=!1,i=null,o=null,l!==null&&(s(l),l=null)},u=()=>{if(!a||i===null||o===null)return!1;const h=i,m=o;return c(),m(h),!0};return{cancel:c,complete:u,isActive:()=>a,start:(h,m)=>a?!1:(a=!0,i=h,o=m,l=t(u,n),!0)}}function xs(t){const s=t?.getBoundingClientRect().width??0;return Number.isFinite(s)&&s>0?s:null}function Nu(t,s,n,a,i=8){const o=Math.max(-1,Math.min(1,-s/Math.max(1,n))),l=(a+i)/7,c=t===6&&o>0||t===0&&o<0;return{selectionOffset:o*(c?a-6*l:l),weekOffset:c?-o*a:0}}async function ku(t){t&&await t.scrollToTop(0)}const jb=14,yb=8,vb=350,bl=1.1;function Kr(t,s,n){const a=Math.abs(t),i=Math.abs(s),o=n>=vb?yb:jb;return Math.max(a,i)<o?null:a>=i*bl?"x":i>=a*bl?"y":null}const Nb=["MON","TUE","WED","THU","FRI","SAT","SUN"];function Ca(t){const s=/^(\d{4})-(\d{2})-(\d{2})$/.exec(t.trim());return s?{year:Number(s[1]),month:Number(s[2]),day:Number(s[3])}:null}function kb(t){const s=t.getUTCFullYear(),n=`${t.getUTCMonth()+1}`.padStart(2,"0"),a=`${t.getUTCDate()}`.padStart(2,"0");return`${s}-${n}-${a}`}function Jt(t,s){const n=Ca(t);if(!n)return t;const a=new Date(Date.UTC(n.year,n.month-1,n.day+s));return kb(a)}function Ai(t){const s=Ca(t);if(!s)return t;const i=(new Date(Date.UTC(s.year,s.month-1,s.day)).getUTCDay()+6)%7;return Jt(t,-i)}function wb(t){const n=(new URLSearchParams(t).get("date")??"").trim();return n&&Ca(n)?n:null}function la(t){return Array.from({length:7},(s,n)=>Jt(t,n))}function fl(t,s){if(!t)return null;const n=new Date(t);if(Number.isNaN(n.getTime()))return null;const a=new Intl.DateTimeFormat("en-CA",{timeZone:s,year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(n),i=l=>a.find(c=>c.type===l)?.value??"",o=`${i("year")}-${i("month")}-${i("day")}`;return Ca(o)?o:null}function Cb(t){const s=t%100;if(s>=11&&s<=13)return`${t}th`;switch(t%10){case 1:return`${t}st`;case 2:return`${t}nd`;case 3:return`${t}rd`;default:return`${t}th`}}function gl(t){const s=Ca(t);if(!s)return t;const n=["January","February","March","April","May","June","July","August","September","October","November","December"];return`${Cb(s.day)} ${n[s.month-1]} ${s.year}`}function Sb(t){const s=new Intl.DateTimeFormat("en-GB",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(new Date),n=s.find(o=>o.type==="year")?.value??"1970",a=s.find(o=>o.type==="month")?.value??"01",i=s.find(o=>o.type==="day")?.value??"01";return`${n}-${a}
2-${i}`}function wu(t){if(Array.isArray(t))return wu(t[0]);const s=(t??"").trim();if(!s)return null;const n=/^(\d{4}-\d{2}-\d{2})$/.exec(s);if(n)return n[1];const a=/^(\d{4}-\d{2}-\d{2})T/.exec(s);if(a)return a[1];const i=new Date(s);return Number.isNaN(i.getTime())?null:i.toISOString().slice(0,10)}function yn(t){return t.map(s=>({...s,availabilityCounts:{...s.availabilityCounts},availabilityPreview:s.availabilityPreview.map(n=>({...n}))}))}function Pb(t,s,n){const a={available:t.availabilityCounts.available,notAvailable:t.availabilityCounts.notAvailable,notSet:t.availabilityCounts.notSet},i=l=>{if(l==="available"){a.available=Math.max(0,a.available-1);return}if(l==="not_available"){a.notAvailable=Math.max(0,a.notAvailable-1);return}a.notSet=Math.max(0,a.notSet-1)},o=l=>{if(l==="available"){a.available+=1;return}if(l==="not_available"){a.notAvailable+=1;return}a.notSet+=1};return i(s),o(n),a}function Rb(t,s){return t.targetStatus===s?t:{...t,targetStatus:s,availabilityCounts:Pb(t,t.targetStatus,s)}}function Tb(){const t=tt(),s=mt(),{hasRole:n}=Ge(),a=ju(),i=T.tenant.getTenantTimezone(),o=r.useMemo(()=>Sb(i),[i]),l=new URLSearchParams(s.search).get("view")==="requests",c=r.useMemo(()=>wb(s.search),[s.search]),u=s.pathname==="/staff-tools/availability",d=n("instructor","admin","owner"),h=r.useRef(null),m=r.useRef(null),f=r.useRef(null),b=r.useRef(null),p=r.useRef(null),g=r.useRef(null),v=r.useRef(new Set),N=r.useRef(new Map),x=r.useRef(c??o),k=r.useRef(u),j=r.useRef(""),I=r.useMemo(()=>ga(Q=>window.requestAnimationFrame(Q),Q=>window.cancelAnimationFrame(Q)),[]),S=r.useMemo(()=>ga(Q=>window.requestAnimationFrame(Q),Q=>window.cancelAnimationFrame(Q),"--member-calendar-selection-offset"),[]),M=r.useMemo(()=>ga(Q=>window.requestAnimationFrame(Q),Q=>window.cancelAnimationFrame(Q)),[]),y=r.useMemo(()=>Gr((Q,je)=>window.setTimeout(Q,je),Q=>window.clearTimeout(Q),320),[]),P=r.useMemo(()=>Gr((Q,je)=>window.setTimeout(Q,je),Q=>window.clearTimeout(Q),320),[]),[U,F]=r.useState(()=>c??o),[A,D]=r.useState([]),[R,w]=r.useState(0),[_,W]=r.useState(!1),[H,ne]=r.useState(!0),[K,ye]=r.useState(!1),[de,O]=r.useState(""),[L,Z]=r.useState(""),[ce,me]=r.useState(""),[Ne,ve]=r.useState(""),[xe,G]=r.useState(""),[J,ke]=r.useState(""),[Be,fe]=r.useState(!1),[Ae,lt]=r.useState(!1),[be,We]=r.useState(null),[Fe,Ke]=r.useState([]),[ue,Se]=r.useState([]),[pe,ae]=r.useState([]),[ge,qe]=r.useState(null),Me=r.useRef(null),Ie=r.useRef(0),ie=r.useRef(null),[Xe,ct]=r.useState(0),[st,xt]=r.useState(!1),[Et,q]=r.useState(0),[te,B]=r.useState(null),[Y,oe]=r.useState(null),Ue=r.useRef(0),_e=r.useRef(null),[He,kt]=r.useState(null),[rt,Lt]=r.useState(0),[Ft,Pt]=r.useState(!1),[Rs,es]=r.useState(0);r.useEffect(()=>{x.current=U},[U]),r.useEffect(()=>{ku(b.current)},[U]),r.useEffect(()=>{k.current=u},[u]),r.useEffect(()=>{if(!u||!U||c===U)return;const Q=new URLSearchParams(s.search);Q.set("date",U),t.replace({pathname:s.pathname,search:`?${Q.toString()}`})},[t,u,s.pathname,s.search,c,U]);const ht=r.useCallback(async(Q,je={})=>{if(!k.current)return;if(!d){D([]),O(""),ne(!1);return}const we=x.current===Q;if(je.preferCache){const Oe=N.current.get(Q);if(Oe){we&&(D(yn(Oe)),O(""),ye(!1),ne(!1));return}}we&&!je.silent&&(ye(!0),O(""));try{const Oe=await T.instructor.listAvailability({from:Q,to:Q}),ut=yn(Oe.rows);if(!k.current)return;N.current.set(Q,ut),w(Ze=>Ze+1),x.current===Q&&(D(yn(ut)),O(""))}catch(Oe){if(x.current===Q&&!je.silent){const ut=re(Oe,"Unable to load instructor availability.");D([]),O(ut||"Unable to load instructor availability.")}}finally{x.current===Q&&!je.silent&&(ye(!1),ne(!1))}},[d]);r.useEffect(()=>{u&&ht(U,{preferCache:!0})},[u,ht,U]),r.useEffect(()=>{if(!u||H||!d)return;const Q=Ai(U),je=[Jt(U,-2),Jt(U,-1),Jt(U,1),Jt(U,2)],we=[...la(Jt(Q,-7)),...la(Q),...la(Jt(Q,7))].filter(Oe=>Oe!==U&&!je.includes(Oe));Promise.all(je.map(Oe=>ht(Oe,{preferCache:!0}))).then(()=>Promise.all(we.map(Oe=>ht(Oe,{preferCache:!0})))).catch(()=>{})},[d,u,H,ht,U]),r.useEffect(()=>{if(!u||H||!d)return;const Q=Ai(U),je=Jt(Q,6);let we=!1;j.current="";const Oe=new AbortController,ut=Nt=>new Promise(wt=>window.setTimeout(wt,Nt));return(async()=>{for(;!we&&!Oe.signal.aborted;)try{const Nt=j.current!=="",wt=await T.timetable.waitForTimetablePush({rangeStart:`${Q}T00:00:00.000Z`,rangeEnd:`${je}T23:59:59.999Z`,cursor:j.current||null,timeoutSec:20},{signal:Oe.signal});if(we||Oe.signal.aborted)return;if(wt.cursor&&(j.current=wt.cursor),!Nt||!wt.changed)continue;const Vt=Array.from(new Set(wt.events.filter(bs=>bs.eventType==="availability_changed"||bs.eventType==="instructors_changed"||bs.eventType==="class_changed").map(bs=>fl(bs.startAt,i)).filter(bs=>!!bs))),ks=x.current;Vt.forEach(bs=>N.current.delete(bs)),Vt.includes(ks)&&await ht(ks,{preferCache:!1,silent:!0})}catch(Nt){if(Nt instanceof DOMException&&Nt.name==="AbortError"||Nt?.name==="AbortError"||we||Oe.signal.aborted)return;await ut(1500)}})(),()=>{we=!0,Oe.abort()}},[d,u,H,ht,U,i]);const vs=r.useCallback(async()=>{N.current.delete(x.current),await ht(x.current,{preferCache:!1})},[ht]),jt=r.useCallback((Q,je)=>
2{N.current.set(Q,yn(je)),w(we=>we+1),x.current===Q&&D(yn(je))},[]),Kt=r.useCallback(async(Q,je)=>{const we=x.current,Oe=N.current.get(we)??A,ut=yn(Oe),Ze=ut.find(wt=>wt.occurrenceUuid===Q)??null;if(!Ze||Ze.targetStatus===je)return;const Nt=ut.map(wt=>wt.occurrenceUuid===Q?Rb(wt,je):wt);jt(we,Nt),me(Q);try{await T.instructor.setAvailability({occurrenceUuid:Q,status:je}),N.current.delete(we),await ht(we,{preferCache:!1,silent:!0})}catch(wt){jt(we,ut);const Vt=re(wt,"Unable to save availability.");Vt&&Z(Vt)}finally{me("")}},[ht,jt,A]),Rt=r.useMemo(()=>Ai(U),[U]),Wt=r.useMemo(()=>la(Jt(Rt,-7)),[Rt]),Yt=r.useMemo(()=>la(Rt),[Rt]),Ts=r.useMemo(()=>la(Jt(Rt,7)),[Rt]),At=r.useMemo(()=>Jt(U,-1),[U]),is=r.useMemo(()=>Jt(U,1),[U]),ts=r.useMemo(()=>N.current.get(At)??null,[R,At]),os=r.useMemo(()=>N.current.get(is)??null,[R,is]),Zs=r.useCallback((Q,je)=>{if(y.isActive()||P.isActive())return;const we=xs(h.current);we!==null&&(ct(we),qe(Q),Me.current=je,Ie.current=Date.now(),ie.current=null,I.flush(h.current,0))},[P,I,y]),bt=r.useCallback(Q=>{if(ge===null||Me.current===null)return;const je=Q.clientX-ge,we=Q.clientY-Me.current,Oe=ie.current??Kr(je,we,Date.now()-Ie.current);if(ie.current===null&&Oe!==null&&(ie.current=Oe),Oe!=="x")return;Q.currentTarget.hasPointerCapture(Q.pointerId)||Q.currentTarget.setPointerCapture(Q.pointerId);const ut=Math.max(120,Xe*.95),Ze=Math.max(-ut,Math.min(ut,je));I.queue(h.current,Ze)},[ge,I,Xe]),hs=r.useCallback(Q=>{if(Q===0){h.current?.classList.remove("is-animating"),I.flush(h.current,0),xt(!1);return}const je=Jt(x.current,Q*7),we=N.current.get(je);xa.flushSync(()=>{we?(D(yn(we)),O(""),ye(!1)):(O(""),ye(!0)),x.current=je,F(je),xt(!1)}),h.current?.classList.remove("is-animating"),I.flush(h.current,0)},[I]),Js=r.useCallback((Q=!1)=>{if(ge===null)return;const je=xs(h.current)??0,we=I.getOffset(),Oe=Math.max(36,Math.min(84,je*.18)),ut=ie.current;let Ze=0,Nt=0;!Q&&je>0&&ut==="x"&&Math.abs(we)>=Oe?(Ze=we<0?1:-1,Nt=Ze===1?-je:je,q(Date.now()+220)):ut==="x"&&q(Date.now()+180),qe(null),Me.current=null,ie.current=null;const wt=ut==="x"&&(Math.abs(we)>0||Ze!==0);if(xt(wt),!wt){I.flush(h.current,0);return}if(!y.start(Ze,hs)){I.flush(h.current,0),xt(!1);return}h.current?.classList.add("is-animating"),I.flush(h.current,Nt)},[hs,ge,I,y]),ps=r.useCallback(Q=>{Q.target!==Q.currentTarget||Q.propertyName!=="transform"||y.complete()},[y]),Qt=r.useCallback((Q,je=!1)=>{const we=(new Date(`${x.current}T12:00:00`).getDay()+6)%7,Oe=Nu(we,Q,je?xs(m.current)??rt:rt,je?xs(h.current)??Xe:Xe);f.current?.classList.toggle("is-selection-animating",je),h.current?.classList.toggle("is-animating",je),je?(S.flush(f.current,Oe.selectionOffset),I.flush(h.current,Oe.weekOffset)):(S.queue(f.current,Oe.selectionOffset),I.queue(h.current,Oe.weekOffset))},[rt,S,I,Xe]),ls=r.useCallback(()=>{f.current?.classList.remove("is-selection-animating"),h.current?.classList.remove("is-animating"),S.flush(f.current,0),I.flush(h.current,0)},[S,I]),qt=r.useCallback(Q=>{v.current.has(Q)||(v.current.add(Q),ht(Q,{preferCache:!0,silent:!0}))},[ht]),$=r.useCallback(Q=>{if(P.isActive()||y.isActive()||H||K||Q.pointerType==="mouse"&&Q.button!==0)return;const je=Q.target;if(!je||je.closest(".member-timetable-sticky-panel")||je.closest("button")||je.closest("ion-segment")||je.closest("a"))return;const we=xs(m.current),Oe=xs(h.current);we===null||Oe===null||(Lt(we),ct(Oe),v.current.clear(),B(Q.clientX),oe(Q.clientY),Ue.current=Date.now(),_e.current=null,kt(null),M.flush(m.current,0))},[M,P,H,K,y]),le=r.useCallback(Q=>{if(te===null||Y===null)return;const je=Q.clientX-te,we=Q.clientY-Y,Oe=_e.current??Kr(je,we,Date.now()-Ue.current);if(_e.current===null&&Oe!==null&&(_e.current=Oe,kt(Oe)),Oe!=="x")return;Q.currentTarget.hasPointerCapture(Q.pointerId)||Q.currentTarget.setPointerCapture(Q.pointerId);const ut=Math.max(120,rt*.95);let Ze=Math.max(-ut,Math.min(ut,je));const Nt=Jt(x.current,Ze<0?1:-1);Ze!==0&&!N.current.has(Nt)&&(qt(Nt),Ze=0),Qt(Ze),M.queue(m.current,Ze)},[qt,Qt,M,rt,te,Y]),Ve=r.useCallback(Q=>{if(Q===0){m.current?.classList.remove("is-animating"),M.flush(m.current,0),ls(),Pt(!1);return}const je=Jt(x.current,Q),we=N.current.get(je);if(!we){m.current?.classList.remove("is-animating"),M.flush(m.current,0),ls(),Pt(!1),ht(je,{preferCache:!0,silent:!0});return}xa.flushSync(()=>{D(yn(we)),O(""),ye(!1),x.current=je,F(je),Pt(!1)}),m.current?.classList.remove("is-animating"),M.flush(m.current,0),ls()},[ht,ls,M]),ot=r.useCallback(Q=>{if(Q?.currentTarget.hasPointerCapture(Q.pointerId)&&Q.currentTarget.releasePointerCapture(Q.pointerId),te===null)return;const je=_e.current==="x";je&&es(Date.now()+260);const we=xs(m.current)??0,Oe=M.getOffset(),ut=Math.max(42,Math.min(96,we*.18));let Ze=0,Nt=0;if(Q?.type!=="pointercancel"&&we>0&&je&&Math.abs(Oe)>=ut&&(Ze=Oe<0?1:-1,Nt=Ze===1?-we:we),Ze!==0){const Vt=Jt(x.current,Ze);N.current.has(Vt)||(qt(Vt),Ze=0,Nt=0)}B(null),oe(null),_e.current=null,kt(null);const wt=je&&(Math.abs(Oe)>0||Ze!==0);if(Pt(wt),!wt){M.flush(m.current,0),ls();return}if(!P.start(Ze,Ve)){M.flush(m.current,0),ls(),Pt(!1);return}Qt(Nt,!0),m.current?.classList.add("is-animating"),M.flush(m.current,Nt)},[qt,Qt,ls,M,P,Ve,te]),_t=r.useCallback(Q=>{Q.target!==Q.currentTarget||Q.propertyName!=="transform"||P.complete()},[P]);r.useEffect(()=>()=>{S.cancel(),I.cancel(),M.cancel(),y.cancel(),P.cancel()},[S,M,P,I,y]);const Ns=r.useCallback(()=>{ke(""),ve(""),G(""),Se([]),ae([]),We(null),Ke([])},[]),Xs=r.useCallback(async Q=>{ve(Q.className),G(ba(Q.startAt,Q.endAt,i)),ke(Q.occurrenceUuid),Se([]),ae([]),We(null),Ke([]),fe(!0),O("");try{const je=await T.instructor.getInstructorRota(Q.occurrenceUuid);Se(je.assignableInstructors),ae(je.availability),We(je.instructors.find(we=>we.role==="lead")?.wpUserId??null),Ke(je.instructors.filter(we=>we.role==="assistant").map(we=>we.wpUserId))}catch(je){O(re(je,"Unable to load the instructor rota.")),Ns()}finally{fe(!1)}},[Ns,i]),Ls=r.useCallback(async()=>
2{if(J){lt(!0),O("");try{await T.instructor.saveInstructorRota(J,Ro(be,Fe)),Z("Instructor rota saved."),Ns()}catch(Q){O(re(Q,"Unable to save the instructor rota."))}finally{lt(!1)}}},[Ns,J,Fe,be]),Ht=r.useCallback((Q,je)=>Q.map(we=>e.jsxs("article",{className:`member-session-card member-availability-card is-${we.targetStatus.replace("_","-")}`,"aria-label":`${we.className} availability`,children:[e.jsxs("div",{className:"member-session-top",children:[e.jsxs("div",{children:[e.jsxs("p",{className:"member-session-time",children:[gl(fl(we.startAt,i)||U)," · ",ba(we.startAt,we.endAt,i)]}),e.jsx("h3",{className:"member-session-title",children:we.className})]}),e.jsx("button",{type:"button",className:"member-availability-preview-btn","aria-label":"See other instructor availability for this class",onClick:()=>{Date.now()<Rs||He==="x"||Ft||Xs(we)},children:e.jsx(V,{icon:ar})})]}),e.jsx("div",{role:"group","aria-label":`Set availability for ${we.className}`,className:"member-availability-card-segment",...a.handlers,children:[["available",si,"Available"],["not_available",pa,"Not available"],["not_set",om,"Not set"]].map(([Oe,ut,Ze])=>e.jsxs("button",{type:"button",className:we.targetStatus===Oe?"is-selected":"","aria-pressed":we.targetStatus===Oe,"aria-label":`${Ze} for ${we.className}`,disabled:ce===we.occurrenceUuid||we.status==="cancelled",onClick:Nt=>{a.allowsClick(Nt)&&Kt(we.occurrenceUuid,Oe)},children:[e.jsx(V,{icon:ut,"aria-hidden":"true"}),e.jsx("span",{className:"sr-only",children:Ze})]},Oe))})]},`${je}:${we.occurrenceUuid}`)),[a,Rs,ce,He,Kt,Ft,Xs,U,i]);return e.jsxs(Cn,{className:"member-timetable-page",children:[e.jsx(So,{}),e.jsxs(wn,{ref:b,fullscreen:!0,forceOverscroll:!1,className:"member-timetable-content",children:[e.jsx(bo,{slot:"fixed",onIonRefresh:Q=>{vs().catch(()=>{}).finally(()=>{Q.detail.complete()})},children:e.jsx(fo,{})}),e.jsxs("main",{ref:p,className:"member-timetable-main",onPointerDown:$,onPointerMove:le,onPointerUp:ot,onPointerCancel:ot,children:[e.jsxs("nav",{className:"member-forms-banner-actions","aria-label":"Availability view",onPointerDown:Q=>Q.stopPropagation(),children:[e.jsx("button",{className:`member-btn ${l?"is-neutral":"is-solid"}`,"aria-pressed":!l,onClick:()=>t.replace(`/staff-tools/availability?date=${U}`),children:"Calendar"}),e.jsx("button",{className:`member-btn ${l?"is-solid":"is-neutral"}`,"aria-pressed":l,onClick:()=>t.replace(`/staff-tools/availability?date=${U}&view=requests`),children:"Requests"})]}),l?e.jsx(gb,{timezone:i}):e.jsxs(e.Fragment,{children:[e.jsxs("section",{className:"member-timetable-sticky-panel",children:[e.jsxs("button",{type:"button",className:"member-btn is-neutral instructor-availability-view-rota",onPointerDown:Q=>Q.stopPropagation(),onClick:Q=>{Q.stopPropagation(),t.push("/staff-tools/rota")},children:[e.jsx(V,{icon:ar}),"View rota"]}),e.jsxs("button",{type:"button",className:"member-timetable-date-row",onPointerDown:Q=>Q.stopPropagation(),onClick:Q=>{Q.stopPropagation(),W(!0)},"aria-label":"Select date",children:[e.jsx("span",{children:gl(U)}),e.jsx(V,{icon:Ut})]}),e.jsxs("div",{ref:f,style:{"--member-calendar-selected-index":Yt.indexOf(U)},className:`member-timetable-week-strip-viewport has-moving-selection${ge!==null?" is-dragging":""}`,onPointerDown:Q=>{Q.pointerType==="mouse"&&Q.button!==0||Zs(Q.clientX,Q.clientY)},onPointerMove:bt,onPointerUp:Q=>{Q.currentTarget.hasPointerCapture(Q.pointerId)&&Q.currentTarget.releasePointerCapture(Q.pointerId),Js()},onPointerCancel:Q=>{Q.currentTarget.hasPointerCapture(Q.pointerId)&&Q.currentTarget.releasePointerCapture(Q.pointerId),Js(!0)},children:[[-1,0,1].map(Q=>e.jsx("span",{"aria-hidden":"true",className:"member-timetable-selection",style:{"--member-calendar-selection-copy":Q}},Q)),e.jsx("div",{ref:h,className:`member-timetable-week-strip member-timetable-gesture-track${st?" is-animating":""}`,onTransitionEnd:ps,children:[Wt,Yt,Ts].map((Q,je)=>e.jsx("div",{className:"member-timetable-week-page",children:Q.map((we,Oe)=>{const ut=Ca(we),Ze=we===U;return e.jsxs("button",{type:"button",className:`member-timetable-day-pill${Ze?" is-active":""}`,"aria-pressed":Ze,onClick:()=>{Date.now()<Et||st||Ft||Math.abs(I.getOffset())>8||F(we)},children:[e.jsx("span",{className:"member-timetable-day-label",children:Nb[Oe]}),e.jsx("span",{className:"member-timetable-day-number",children:ut?.day??"--"})]},we)})},`week-page-${je}`))})]})]}),e.jsx("div",{ref:g,className:`member-timetable-cards-viewport${te!==null?" is-dragging":""}`,children:e.jsxs("div",{ref:m,className:`member-timetable-cards-track member-timetable-gesture-track${Ft?" is-animating":""}`,onTransitionEnd:_t,children:[e.jsx("section",{className:"member-timetable-cards-page is-side","aria-hidden":"true",children:e.jsx("section",{className:"member-timetable-cards",children:ts?ts.length===0?e.jsx("div",{className:"member-timetable-empty",children:"No classes available for this day."}):Ht(ts,At):e.jsxs("div",{className:"member-timetable-loader",children:[e.jsx(Te,{name:"crescent"}),e.jsx("span",{children:"Loading classes..."})]})})}),e.jsx("section",{className:"member-timetable-cards-page is-current",children:e.jsxs("section",{className:"member-timetable-cards",children:[H||K?e.jsxs("div",{className:"member-timetable-loader",children:[e.jsx(Te,{name:"crescent"}),e.jsx("span",{children:"Loading classes..."})]}):null,!H&&!K&&!d?e.jsx("div",{className:"member-timetable-empty",children:"Staff access is required to manage instructor availability."}):null,!H&&!K&&d&&de?e.jsx("div",{className:"member-timetable-empty",children:de}):null,!H&&!K&&d&&!de&&A.length===0?e.jsx("div",{className:"member-timetable-empty",children:"No classes available for this day."}):null,!H&&!K&&d&&!de?Ht(A,U):null]})}),e.jsx("section",{className:"member-timetable-cards-page is-side","aria-hidden":"true",children:e.jsx("section",{className:"member-timetable-cards",children:os?os.length===0?e.jsx("div",{className:"member-timetable-empty",children:"No classes available for this day."}):Ht(os,is):e.jsxs("div",{className:"member-timetable-loader",children:[e.jsx(Te,{name:"crescent"}),e.jsx("span",{children:"Loading classes..."})]})})})]})})]})]}),e.jsx(at,{isOpen:_,className:"member-date-modal",keepContentsMounted:!0,onDidDismiss:()=>W(!1),children:e.jsx("div",{className:"member-date-modal-content",children:e.jsx(Zr,{presentation:"date",locale:"en-GB",firstDayOfWeek:1,showDefaultButtons:!0,doneText:"Cho
2ose date",cancelText:"Cancel",value:U,onIonChange:Q=>{const je=wu(Q.detail.value);je&&F(je)}})})}),e.jsx(at,{isOpen:J!=="",onDidDismiss:Ns,children:e.jsx(To,{contextLabel:[Ne,xe].filter(Boolean).join(" · "),directory:ue,availability:pe,draft:{leadWpUserId:be,assistantWpUserIds:Fe},loading:Be,saving:Ae,onChange:Q=>{We(Q.leadWpUserId),Ke(Q.assistantWpUserIds)},onCancel:Ns,onSave:()=>{Ls()}})}),e.jsx(Dt,{isOpen:L!=="",message:L,duration:2400,onDidDismiss:()=>Z("")})]}),e.jsx(Po,{activeTab:"availability"})]})}let io="";const oo=new Set;function _b(){return typeof window>"u"?"":window.location.origin}function Mb(t){const s=String(t||"").trim().replace(/\/+$/,""),n=/^https?:\/\/[^/]+$/i.test(s)?s:"";n!==io&&(io=n,oo.forEach(a=>a()))}function Cu(){return io||_b()}function Ub(){return r.useSyncExternalStore(t=>(oo.add(t),()=>oo.delete(t)),Cu,()=>"")}function Su(t){const s=Cu();return s?new URL(t,s).toString():t}function Ga(t){return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}-${String(t.getDate()).padStart(2,"0")}`}function Eb(t){const s=new Date(t.getFullYear(),t.getMonth(),t.getDate());return s.setDate(s.getDate()-(s.getDay()+6)%7),s}function Ab(t){const s=new Date(Date.UTC(t.getFullYear(),t.getMonth(),t.getDate())),n=s.getUTCDay()||7;s.setUTCDate(s.getUTCDate()+4-n);const a=new Date(Date.UTC(s.getUTCFullYear(),0,1));return Math.ceil(((s.getTime()-a.getTime())/864e5+1)/7)}function xl(t){const[s,n,a]=t.split("-").map(Number);return new Date(s,n-1,a,12,0,0)}function jl(t,s){const n=xl(t),a=xl(s),i=n.getFullYear()===a.getFullYear(),o=i&&n.getMonth()===a.getMonth(),l=(c,u)=>c.toLocaleDateString("en-GB",{day:"numeric",month:"short",...u?{year:"numeric"}:{}}).replace("Sept","Sep");return o?`${n.getDate()} to ${l(a,!0)}`:i?`${l(n,!1)} to ${l(a,!0)}`:`${l(n,!0)} to ${l(a,!0)}`}function Db(t){return t.toLocaleDateString("en-GB",{month:"long",year:"numeric"})}function Lb(t,s){if(s==="month")return{from:Ga(new Date(t.getFullYear(),t.getMonth(),1)),to:Ga(new Date(t.getFullYear(),t.getMonth()+1,0))};const n=Eb(t),a=new Date(n);return a.setDate(a.getDate()+6),{from:Ga(n),to:Ga(a)}}function yl(t,s,n){if(s==="month")return new Date(t.getFullYear(),t.getMonth()+n,1);const a=new Date(t);return a.setDate(a.getDate()+n*7),a}function Ib(t,s,n){return s==="whole"?t:t.filter(a=>a.instructors.some(i=>i.wpUserId===n))}function $b(t){const s=t.filter(a=>a.status==="scheduled"),n=s.filter(a=>a.instructors.length>0).length;return{scheduled:s.length,assigned:n,unassigned:s.length-n}}function Ob(t){const s=new Map;return t.filter(n=>n.status==="scheduled").forEach(n=>{n.instructors.forEach(a=>s.set(a.wpUserId,a.displayName))}),Array.from(s,([n,a])=>({wpUserId:n,displayName:a})).sort((n,a)=>n.displayName.localeCompare(a.displayName))}function Bb(t,s){const n=new Intl.DateTimeFormat("en-GB",{timeZone:s,year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(t),a=Object.fromEntries(n.map(i=>[i.type,i.value]));return`${a.year}-${a.month}-${a.day}`}function Fb(t,s=rr()){const n=new Map;return t.forEach(a=>{const i=new Date(a.startAt);if(Number.isNaN(i.getTime()))return;const o=Bb(i,s);n.set(o,[...n.get(o)??[],a])}),Array.from(n,([a,i])=>({dateKey:a,rows:i})).sort((a,i)=>a.dateKey.localeCompare(i.dateKey))}function _r(t,s){const n=new Date(t);return Number.isNaN(n.getTime())?"":n.toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit",timeZone:s})}function Wb(t){const s=Array.isArray(t)?t[0]:t;if(!s)return null;const n=s.slice(0,10).length===10?s.slice(0,10):`${s.slice(0,7)}-01`,a=new Date(`${n}T12:00:00`);return Number.isNaN(a.getTime())?null:a}function qb(){const{user:t}=Ge(),[s,n]=r.useState("week"),[a,i]=r.useState("mine"),[o,l]=r.useState(()=>new Date),[c,u]=r.useState(!1),d=r.useRef(null),h=r.useRef(""),[m,f]=r.useState([]),[b,p]=r.useState(!0),[g,v]=r.useState(!1),[N,x]=r.useState("mine"),k=r.useRef(0),[j,I]=r.useState(null),[S,M]=r.useState(!0),[y,P]=r.useState(!1),[U,F]=r.useState(""),[A,D]=r.useState(null),[R,w]=r.useState(!1),[_,W]=r.useState(!1),[H,ne]=r.useState(null),[K,ye]=r.useState([]),[de,O]=r.useState([]),[L,Z]=r.useState(null),[ce,me]=r.useState([]),[Ne,ve]=r.useState(!1),[xe,G]=r.useState(!1),[J,ke]=r.useState(""),[Be,fe]=r.useState(""),Ae=r.useMemo(()=>Lb(o,s),[o,s]),lt=t?.wpUserId??0,be=Ys(t,"schedule_email_instructors"),We=ii(t),Fe=rr(),Ke=r.useCallback(async()=>{p(!0),fe("");try{f(await T.instructor.listRotaOverview(Ae))}catch(q){f([]),fe(re(q,"Unable to load the rota."))}finally{p(!1)}},[Ae]),ue=r.useCallback(async()=>{const q=++k.current;M(!0),F("");try{const te=await T.instructor.getRotaCalendarSettings(N);if(q!==k.current)return;I(te)}catch(te){if(q!==k.current)return;I(null),F(re(te,"Unable to load calendar sync."))}finally{q===k.current&&M(!1)}},[N]);r.useEffect(()=>{Ke()},[Ke]),r.useEffect(()=>{ue()},[ue]);const Se=r.useMemo(()=>Ib(m,a,lt),[m,a,lt]),pe=r.useMemo(()=>Fb(Se,Fe),[Fe,Se]),ae=r.useMemo(()=>$b(m),[m]),ge=r.useMemo(()=>Ob(m),[m]),qe=r.useCallback(()=>{xe||(ne(null),ye([]),O([]),Z(null),me([]))},[xe]),Me=r.useCallback(async q=>{ne(q),ye([]),O([]),Z(null),me([]),ve(!0),fe("");try{const te=await T.instructor.getInstructorRota(q.occurrenceUuid);ye(te.assignableInstructors),O(te.availability),Z(te.instructors.find(B=>
2B.role==="lead")?.wpUserId??null),me(te.instructors.filter(B=>B.role==="assistant").map(B=>B.wpUserId))}catch(te){ne(null),fe(re(te,"Unable to load the instructor rota."))}finally{ve(!1)}},[]);r.useEffect(()=>{let q=!1;h.current="";const te=new AbortController,B=oe=>new Promise(Ue=>window.setTimeout(Ue,oe));return(async()=>{for(;!q&&!te.signal.aborted;)try{const oe=h.current!=="",Ue=await T.timetable.waitForTimetablePush({rangeStart:`${Ae.from}T00:00:00.000Z`,rangeEnd:`${Ae.to}T23:59:59.999Z`,cursor:h.current||null,timeoutSec:20},{signal:te.signal});if(q||te.signal.aborted)return;if(Ue.cursor&&(h.current=Ue.cursor),!oe||!Ue.changed)continue;const _e=Ue.events.filter(He=>He.eventType==="class_changed"||He.eventType==="instructors_changed"||He.eventType==="availability_changed");if(_e.length===0)continue;await Ke(),H&&_e.some(He=>He.occurrenceUuid===H.occurrenceUuid)&&await Me(H)}catch(oe){if(oe instanceof DOMException&&oe.name==="AbortError"||oe?.name==="AbortError"||q||te.signal.aborted)return;await B(1500)}})(),()=>{q=!0,te.abort()}},[H,Ke,Me,Ae.from,Ae.to]);const Ie=r.useCallback(async()=>{if(H){G(!0),fe("");try{const q=await T.instructor.saveInstructorRota(H.occurrenceUuid,Ro(L,ce));f(te=>te.map(B=>B.occurrenceUuid===H.occurrenceUuid?{...B,instructors:q}:B)),ke("Instructor rota saved."),ne(null),ye([]),O([]),Z(null),me([])}catch(q){fe(re(q,"Unable to save the instructor rota."))}finally{G(!1)}}},[ce,L,H]),ie=r.useCallback(async()=>{v(!0);try{const q=await T.instructor.emailRotaWeek(Ae);w(!1),W(!1),ke(`Rota emails sent: ${q.sentCount}. Skipped: ${q.skippedCount}.`)}catch(q){fe(re(q,"Unable to email the rota."))}finally{v(!1)}},[Ae]),Xe=r.useCallback(async()=>{P(!0),F("");try{I(await T.instructor.enableRotaCalendar(N)),ke("Private calendar link created.")}catch(q){F(re(q,"Unable to create the private calendar link."))}finally{P(!1)}},[N]),ct=r.useCallback(async()=>{if(!j?.feedPath)return;const q=await Gn(Su(j.feedPath));ke(q?"Private calendar link copied.":"Unable to copy the private calendar link.")},[j]),st=r.useCallback(async q=>{P(!0),F("");try{const te=q==="reset"?await T.instructor.resetRotaCalendar(N):await T.instructor.disableRotaCalendar(N);I(te),ke(q==="reset"?"Private calendar link reset.":"Calendar sync turned off.")}catch(te){F(re(te,q==="reset"?"Unable to reset the private calendar link.":"Unable to turn off calendar sync."))}finally{P(!1),D(null)}},[N]),xt=s==="week"?`Week ${Ab(o)}`:Db(o),Et=s==="week"?jl(Ae.from,Ae.to):"";return e.jsxs(Ye,{title:"Instructor Rota",subtitle:"View teaching assignments.",activeTab:"none",backTo:"/staff-tools",onRefresh:Ke,refresherDisabled:b,children:[e.jsxs("section",{className:"member-panel-card instructor-rota-overview-controls",children:[e.jsxs("div",{className:"member-rota-toggle-row","aria-label":"Rota scope",children:[e.jsx("button",{type:"button",className:`member-btn ${a==="mine"?"is-solid":"is-neutral"}`,onClick:()=>i("mine"),children:"My Rota"}),e.jsx("button",{type:"button",className:`member-btn ${a==="whole"?"is-solid":"is-neutral"}`,onClick:()=>i("whole"),children:"Whole Rota"})]}),e.jsxs("div",{className:"member-rota-toggle-row","aria-label":"Rota period",children:[e.jsx("button",{type:"button",className:`member-btn ${s==="week"?"is-solid":"is-neutral"}`,onClick:()=>n("week"),children:"Week"}),e.jsx("button",{type:"button",className:`member-btn ${s==="month"?"is-solid":"is-neutral"}`,onClick:()=>n("month"),children:"Month"})]}),e.jsxs("div",{className:"member-rota-range-row",children:[e.jsx("button",{type:"button",className:"member-rota-step-btn","aria-label":`Previous ${s}`,onClick:()=>l(q=>yl(q,s,-1)),children:e.jsx(V,{icon:Hs})}),e.jsxs("button",{type:"button",className:"member-rota-period-trigger","aria-label":`Choose ${s}`,onClick:()=>u(!0),children:[e.jsx(V,{icon:Ut}),e.jsxs("span",{children:[e.jsx("strong",{children:xt}),Et?e.jsx("small",{children:Et}):null]})]}),e.jsx("button",{type:"button",className:"member-rota-step-btn","aria-label":`Next ${s}`,onClick:()=>l(q=>yl(q,s,1)),children:e.jsx(V,{icon:ei})})]}),e.jsxs("div",{className:"member-rota-summary","aria-label":"Rota coverage",children:[e.jsxs("span",{children:["Scheduled ",e.jsx("strong",{children:ae.scheduled})]}),e.jsxs("span",{children:["Assigned ",e.jsx("strong",{children:ae.assigned})]}),e.jsxs("span",{className:ae.unassigned>0?"is-warning":"",children:["Unassigned ",e.jsx("strong",{children:ae.unassigned})]})]}),be&&s==="week"?e.jsxs("button",{type:"button",className:"member-btn is-solid instructor-rota-email-btn",disabled:g||ge.length===0,onClick:()=>{W(!1),w(!0)},children:[e.jsx(V,{icon:qn}),"Email this week"]}):null]}),e.jsxs("section",{className:"member-panel-card instructor-rota-calendar-card",children:[e.jsxs("div",{className:"member-row-main",children:[e.jsxs("div",{children:[e.jsx("span",{className:"member-section-eyebrow",children:"Personal calendar"}),e.jsx("h2",{children:"Calendar sync"})]}),e.jsx(V,{icon:Ut})]}),e.jsxs("label",{className:"instructor-rota-calendar-scope",children:["Calendar to sync",e.jsxs("select",{value:N,disabled:y||S,onChange:q=>{I(null),M(!0),D(null),x(q.target.value==="whole"?"whole":"mine")},children:[e.jsx("option",{value:"mine",children:"My rota"}),e.jsx("option",{value:"whole",children:"Whole rota"})]})]}),S?e.jsxs("div",{className:"instructor-rota-calendar-loading",children:[e.jsx(Te,{name:"crescent"}
2),e.jsx("span",{children:"Loading calendar sync..."})]}):null,!S&&U?e.jsxs("div",{className:"instructor-rota-calendar-error",children:[e.jsx("strong",{children:U}),e.jsx("button",{type:"button",className:"member-btn is-neutral",onClick:()=>{ue()},children:"Try again"})]}):null,!S&&!U&&!j?.enabled?e.jsxs(e.Fragment,{children:[e.jsx("p",{children:N==="whole"?"Create a separate private link to see all classes and instructor assignments. Your own rota subscription stays unchanged.":"Create a private link for your own rota. It updates when your teaching assignments change."}),e.jsx("button",{type:"button",className:"member-btn is-solid",disabled:y,onClick:()=>{Xe()},children:y?"Creating...":"Create private calendar link"})]}):null,!S&&!U&&j?.enabled&&j.feedPath?e.jsxs(e.Fragment,{children:[e.jsx("p",{children:"Copy the private link. On a computer, open Google Calendar, choose Other calendars, then From URL, and paste it. Your rota will then appear in the Google Calendar app on Android."}),e.jsx("strong",{children:N==="whole"?"Whole rota calendar":"My rota calendar"}),e.jsx("p",{children:"If Google shows the link as the calendar name, open its settings on a computer and change Name to My Rota or Whole Rota. In the Android app, open Settings, choose this calendar and turn Sync on. Also select it in the calendar list."}),e.jsx("p",{children:"Calendar apps fetch updates on their own schedule. Sending the rota email does not force a calendar refresh. Check the rota here for the latest changes."}),e.jsxs("div",{className:"instructor-rota-calendar-actions",children:[e.jsxs("button",{type:"button",className:"member-btn is-solid",disabled:y,onClick:()=>{ct()},children:[e.jsx(V,{icon:kn}),"Copy private link"]}),e.jsxs("button",{type:"button",className:"member-btn is-neutral",disabled:y,onClick:()=>D("reset"),children:[e.jsx(V,{icon:pc}),"Reset private link"]}),e.jsx("button",{type:"button",className:"member-btn is-neutral",disabled:y,onClick:()=>D("disable"),children:"Turn off calendar sync"})]}),e.jsxs("small",{children:["Keep this link private. Anyone with the link can see ",N==="whole"?"the whole rota":"your rota",". Reset and turn off apply only to the selected calendar."]})]}):null]}),Be?e.jsxs("section",{className:"member-panel-card member-error-card",children:[e.jsx("strong",{children:Be}),e.jsx("button",{type:"button",className:"member-btn is-neutral",onClick:()=>{Ke()},children:"Try again"})]}):null,b?e.jsxs("section",{className:"member-panel-card member-rota-loading",children:[e.jsx(Te,{name:"crescent"}),e.jsx("span",{children:"Loading rota..."})]}):null,!b&&!Be&&pe.length===0?e.jsxs("section",{className:"member-panel-card member-rota-empty",children:[e.jsx("strong",{children:"No classes in this view."}),e.jsx("p",{children:"Try Whole Rota or another period."})]}):null,!b&&!Be?e.jsx("div",{className:"member-rota-days",children:pe.map(q=>e.jsxs("section",{className:"member-panel-card member-rota-day",children:[e.jsx("h2",{children:new Date(`${q.dateKey}T12:00:00`).toLocaleDateString("en-GB",{weekday:"long",day:"numeric",month:"long"})}),e.jsx("div",{className:"member-panel-list",children:q.rows.map(te=>{const B=te.instructors.find(He=>He.role==="lead"||He.isLead),Y=te.instructors.filter(He=>He.wpUserId!==B?.wpUserId),oe=te.status==="scheduled"&&!B,Ue=te.status==="cancelled"?"Cancelled":oe?"Not assigned":"Assigned",_e=We&&te.status!=="cancelled";return e.jsxs("article",{className:`member-panel-row member-rota-class${oe?" is-unassigned":""}${_e?" is-actionable":""}`,role:_e?"button":void 0,tabIndex:_e?0:void 0,"aria-label":_e?`Manage instructors for ${te.className}`:void 0,onClick:_e?()=>{Me(te)}:void 0,onKeyDown:_e?He=>{(He.key==="Enter"||He.key===" ")&&(He.preventDefault(),Me(te))}:void 0,children:[e.jsxs("div",{className:"member-row-main",children:[e.jsxs("strong",{children:[_r(te.startAt,Fe)," to ",_r(te.endAt,Fe)]}),e.jsx("span",{className:`member-pill ${te.status==="cancelled"||oe?"is-danger":"is-accent"}`,children:Ue})]}),e.jsx("h3",{children:te.className}),e.jsxs("div",{className:"member-rota-assignment",children:[e.jsxs("span",{className:"member-rota-lead",children:[B?e.jsx("span",{className:"member-rota-lead-avatar","aria-hidden":"true",children:B.avatarUrl?e.jsx("img",{src:B.avatarUrl,alt:""}):B.displayName.charAt(0).toUpperCase()}):null,e.jsxs("span",{children:[e.jsx("strong",{children:"Lead:"})," ",B?.displayName||"Not assigned"]})]}),Y.length>0?e.jsxs("span",{children:[e.jsx("strong",{children:"Assistants:"})," ",Y.map(He=>
2He.displayName).join(", ")]}):null]})]},te.occurrenceUuid)})})]},q.dateKey))}):null,e.jsx(at,{className:"instructor-rota-period-modal",isOpen:c,onDidDismiss:()=>u(!1),children:e.jsxs("div",{className:"member-modal-sheet instructor-rota-period-sheet",children:[e.jsxs("div",{className:"member-modal-header",children:[e.jsx("h2",{children:s==="week"?"Choose week":"Choose month"}),e.jsx("p",{children:s==="week"?"Choose any date in the week you want to view.":"Choose the month and year you want to view."})]}),e.jsx(Zr,{ref:d,presentation:s==="week"?"date":"month-year",locale:"en-GB",firstDayOfWeek:1,showDefaultButtons:!1,value:Ga(o),onIonCancel:()=>u(!1),onIonChange:q=>{const te=Wb(q.detail.value);te&&(l(te),u(!1))},children:e.jsxs(yd,{slot:"buttons",className:"instructor-rota-period-actions",children:[e.jsx(vt,{onClick:()=>{d.current?.cancel()},children:"Cancel"}),e.jsx(vt,{strong:!0,onClick:()=>{d.current?.confirm()},children:s==="week"?"Choose week":"Choose month"})]})})]})}),e.jsx(at,{isOpen:H!==null,onDidDismiss:qe,children:e.jsx(To,{contextLabel:H?`${H.className} · ${_r(H.startAt,Fe)} to ${_r(H.endAt,Fe)}`:void 0,directory:K,availability:de,draft:{leadWpUserId:L,assistantWpUserIds:ce},loading:Ne,saving:xe,onChange:q=>{Z(q.leadWpUserId),me(q.assistantWpUserIds)},onCancel:qe,onSave:()=>{Ie()}})}),e.jsx(at,{isOpen:R,onDidDismiss:()=>{g||(w(!1),W(!1))},children:e.jsxs("div",{className:"member-modal-sheet instructor-rota-email-sheet",children:[e.jsxs("div",{className:"member-row-main",children:[e.jsxs("div",{children:[e.jsx("span",{className:"member-section-eyebrow",children:"Instructor rota"}),e.jsx("h2",{children:"Confirm schedule email"})]}),e.jsx(V,{icon:qn})]}),e.jsxs("p",{children:["Each instructor receives only their own scheduled classes for ",jl(Ae.from,Ae.to),"."]}),e.jsxs("div",{className:"member-rota-recipient-list",children:[e.jsxs("strong",{children:["Recipients (",ge.length,")"]}),ge.map(q=>e.jsx("span",{children:q.displayName},q.wpUserId))]}),ae.unassigned>0?e.jsxs("div",{className:"member-rota-email-warning",children:[e.jsxs("strong",{children:[ae.unassigned," class",ae.unassigned===1?" is":"es are"," unassigned."]}),e.jsx("p",{children:"Those classes will not appear in an instructor email."})]}):null,e.jsxs("div",{className:"instructor-rota-footer",children:[e.jsx("button",{type:"button",className:"member-btn is-neutral",disabled:g,onClick:()=>w(!1),children:"Back"}),ae.unassigned>0&&!_?e.jsx("button",{type:"button",className:"member-btn is-danger",onClick:()=>W(!0),children:"Continue"}):e.jsx("button",{type:"button",className:"member-btn is-solid",disabled:g||ge.length===0,onClick:()=>{ie()},children:g?"Sending...":"Send emails"})]})]})}),e.jsx(Vn,{isOpen:A!==null,header:A==="reset"?"Reset private calendar link":"Turn off calendar sync",message:A==="reset"?"Your current link will stop working. You will need to add the new link to your calendar.":"Your private link will stop working and your rota will stop updating in your calendar.",buttons:[{text:"Cancel",role:"cancel",handler:()=>D(null)},{text:A==="reset"?"Reset link":"Turn off",role:"destructive",handler:()=>{A&&st(A)}}],onDidDismiss:()=>{y||D(null)}}),e.jsx(Dt,{isOpen:J!=="",message:J,duration:2600,onDidDismiss:()=>ke("")})]})}function Hb(){const t=tu();return e.jsx(Ye,{standardUI:!0,title:t.copy.title,subtitle:t.copy.subtitle,activeTab:"settings",backTo:"/settings",suppressReadOnlyNotice:!0,suppressInstallPrompt:!0,children:e.jsx("section",{className:"member-panel-card",children:e.jsx(lm,{description:t.copy.guidance||t.copy.subtitle})})})}const Vb="skullsystem_oauth_token";function zb(t,s){const n=(t||"").trim(),a=s.trim().replace(/\/$/,"");if(!n||!a)return null;try{const i=new URL(n,a);if(i.origin!==a||i.username||i.password||i.hash)return null;const o=i.pathname==="/api/v1/oauth/authorize"||i.pathname==="/api/v1/oauth/connections",l=i.pathname==="/wp-admin/admin-post.php"&&["skull_mcp_oauth_authorize","skull_mcp_oauth_connections"].includes(i.searchParams.get("action")||"");return!o&&!l?null:i.toString()}catch{return null}}function Pu(t,s){const n=new URLSearchParams(t);return zb(n.get("redirect_to"),s)}function Gb(t){if(typeof window>"u"||!t)return;const s=window.location.protocol==="https:"?"; Secure":"";window.document.cookie=`${Vb}=${encodeURIComponent(t)}; Path=/; SameSite=Lax${s}`}function vl(){const t=tt(),s=mt(),{login:n,isReady:a}=Ge(),[i,o]=r.useState(""),[l,c]=r.useState(""),[u,d]=r.useState(!1),[h,m]=r.useState({}),[f,b]=r.useState(""),[p,g]=r.useState(!1),v=T.auth.getPendingLoginMessage(),x=new URLSearchParams(s.search).get("reset")==="1",k=Pu(s.search,window.location.origin),j=p||!a,I=()=>{const M={};return i.trim()||(M.identifier="Email or username is required."),l.trim()||(M.password="Password is required."),m(M),Object.keys(M).length===0},S=async M=>
2{if(M.preventDefault(),b(""),!!I())try{if(g(!0),k){const y=await T.auth.loginForOAuth({email:i.trim(),password:l,rememberMe:!0});Gb(y),window.location.assign(k);return}await n({email:i.trim(),password:l,rememberMe:!0})}catch(y){y instanceof cn||y instanceof Error?b(y.message):b("Unable to sign in right now.")}finally{g(!1)}};return e.jsxs(mr,{children:[e.jsxs("form",{onSubmit:S,noValidate:!0,className:"member-login-form",children:[k?e.jsx("p",{className:"member-login-status",children:"Sign in to choose which schools ChatGPT can access."}):null,e.jsxs("label",{className:"member-login-field",children:[e.jsx("span",{className:"member-login-label",children:"Email"}),e.jsx("input",{type:"text",className:"member-login-input",autoComplete:"username",value:i,onChange:M=>o(M.target.value),disabled:j})]}),h.identifier?e.jsx("p",{className:"member-login-error",children:h.identifier}):null,e.jsxs("label",{className:"member-login-field",children:[e.jsx("span",{className:"member-login-label",children:"Password"}),e.jsxs("span",{className:"member-login-password-input-wrap",children:[e.jsx("input",{type:u?"text":"password",className:"member-login-password-input",autoComplete:"current-password",value:l,onChange:M=>c(M.target.value),disabled:j}),e.jsx("button",{type:"button",className:"member-login-password-toggle",onClick:()=>d(M=>!M),"aria-label":u?"Hide password":"Show password",disabled:j,children:e.jsx(V,{icon:u?Hr:ar})})]})]}),h.password?e.jsx("p",{className:"member-login-error",children:h.password}):null,x?e.jsx("p",{className:"member-login-status",children:"Password updated. You can sign in now."}):null,f||v?e.jsx("p",{className:"member-login-error",children:f||v}):null,e.jsx(vt,{className:"member-login-submit",expand:"block",type:"submit",disabled:j,children:p?"LOGGING IN...":k?"CONTINUE":"LOGIN"})]}),e.jsx("button",{type:"button",className:"member-login-forgot",disabled:j,onClick:()=>t.push("/forgot-password"),children:"Forgot password?"}),e.jsx("button",{type:"button",className:"member-login-forgot",disabled:j,onClick:()=>t.push("/recover-account"),children:"Used a different email? Recover account"})]})}function Ru(t){const s=`${t??""}`.trim();return!s||!s.startsWith("/")?null:s}function Tu(t){return t.split(/[?#]/,1)[0]??t}function se(t,s){return!!Or({path:s,end:!0},t)}function Kb(t){return t?.accessPolicy?.memberExperienceMode==="booking_beta"}function Yb(t,s){if(!se(s,"/forms"))return!1;const n=new URLSearchParams(t.split("?",2)[1]?.split("#",1)[0]??""),a=`${n.get("next")??""}`.trim(),i=`${n.get("scope")??""}`.trim().toLowerCase(),o=`${n.get("required")??""}`.trim().toLowerCase();return a.startsWith("/timetable")||i==="booking"||i==="onboarding"||i==="required"||o==="1"||o==="true"}function Qb(t,s){return se(s,"/memberships")?`${new URLSearchParams(t.split("?",2)[1]?.split("#",1)[0]??"").get("upgrade_plan")??""}`.trim()!=="":!1}function Zb(t,s){const n=Ru(t);if(!n)return!1;const a=Tu(n);return se(a,"/timetable")||se(a,"/community-groups")||se(a,"/events")||se(a,"/events/workshops")||se(a,"/events/fundraisers")||se(a,"/events/details/:slug")||se(a,"/events/fundraisers/:slug")||se(a,"/event/:slug")||se(a,"/workshops/:slug")||se(a,"/fundraisers/:slug")||se(a,"/resources")||se(a,"/member-hub")&&cr(s)||se(a,"/parent-hub")&&ur(s)||se(a,"/instructor-hub")&&dr(s)||se(a,"/timetable/:sessionId")&&Qe(s)||se(a,"/instructor/classes")&&Qe(s)||se(a,"/people/members/:uuid")&&Qe(s)||se(a,"/staff-tools")&&Qe(s)||se(a,"/staff-tools/availability")&&Qe(s)||se(a,"/staff-tools/rota")&&Qe(s)||se(a,"/staff-tools/log-cash")&&Qe(s)||se(a,"/staff-tools/sales-links")&&Qe(s)||se(a,"/staff-tools/share-tools")&&Qe(s)||se(a,"/staff-tools/prompts")&&Qe(s)||se(a,"/staff-tools/lesson-plans")&&Gs(s)||se(a,"/staff-tools/lesson-plans/:familyUuid")&&Gs(s)||se(a,"/lesson-plans/:lessonPlanUuid/document")&&Gs(s)||se(a,"/people")&&oi(s)||se(a,"/people/members")&&Kn(s)||se(a,"/people/prospects")&&Yn(s)||se(a,"/people/prospects/:uuid")&&Yn(s)||se(a,"/leads")&&Qn(s)||se(a,"/leads/:uuid")&&Qn(s)||se(a,"/people/households")&&Zn(s)||se(a,"/people/households/:uuid")&&Zn(s)||se(a,"/curriculum")&&Qe(s)||se(a,"/curriculum/point/:itemUuid/notes")&&Qe(s)||se(a,"/curriculum/point/:itemUuid/notes/new")&&Qe(s)||se(a,"/curriculum/point/:itemUuid/notes/:entryUuid/edit")&&Qe(s)||se(a,"/curriculum/point/:itemUuid/checkpoints")&&Qe(s)||se(a,"/curriculum/point/:itemUuid/checkpoints/new")&&Qe(s)||se(a,"/curriculum/point/:itemUuid/checkpoints/:entryUuid/edit")&&Qe(s)||se(a,"/training")&&Xt(s)||se(a,"/strength")&&Xt(s)&&s?.featureFlags?.strengthTrackingEnabled===!0||se(a,"/workouts")&&Xt(s)&&s?.featureFlags?.workoutPlannerEnabled===!0||se(a,"/progress")&&Xt(s)||se(a,"/attendance")&&Xt(s)||se(a,"/settings")||se(a,"/ai-connections")||se(a,"/notifications")||se(a,"/profile")||se(a,"/password-setup")||se(a,"/forms")&&ko(s)||se(a,"/memberships")&&va(s)||se(a,"/payment-methods")&&li(s)||Qb(n,a)||Yb(n,a)}function Mo(t,s){const n=Ru(s);if(!n)return"/timetable";const a=Tu(n);return se(a,"/member/links")||se(a,"/resources")?an(t):Kb(t)&&!Zb(n,t)||se(a,"/login")||a.startsWith("/onboarding/")?"/timetable":se(a,"/timetable/:sessionId")?Qe(t)?n:"/timetable":se(a,"/timetable")||se(a,"/events")||se(a,"/events/workshops")||se(a,"/events/fundraisers")||se(a,"/events/details/:slug")||se(a,"/events/fundraisers/:slug")||se(a,"/event/:slug")||se(a,"/workshops/:slug")||se(a,"/fundraisers/:slug")?n:se(a,"/dashboard")?"/timetable":se(a,"/member-hub")?cr(t)?n:an(t):se(a,"/parent-hub")?ur(t)?n:an(t):se(a,"/instructor-hub")?dr(t)?n:an(t):se(a,"/account")||se(a,"/community-groups")||se(a,"/settings")||se(a,"/ai-connections")||se(a,"/notifications")||se(a,"/profile")?n:se(a,"/training")?Xt(t)?n:"/timetable":se(a,"/strength")?Xt(t)&&t.featureFlags?.strengthTrackingEnabled===!0?n:"/timetable":se(a,"/workouts")?Xt(t)&&t.featureFlags?.workoutPlannerEnabled===!0?n:"/timetable":se(a,"/staff-tools")||se(a,"/staff-tools/availability")||se(a,"/staff-tools/rota")||se(a,"/staff-tools/log-cash")||se(a,"/staff-tools/sales-links")||se(a,"/staff-tools/share-tools")||se(a,"/staff-tools/prompts")||se(a,"/staff-tools/lesson-plans")||se(a,"/staff-tools/lesson-plans/:familyUuid")||se(a,"/lesson-plans/:lessonPlanUuid/document")||se(a,"/instructor/classe
2s")?se(a,"/staff-tools/lesson-plans")||se(a,"/staff-tools/lesson-plans/:familyUuid")||se(a,"/lesson-plans/:lessonPlanUuid/document")?Gs(t)?n:"/staff-tools":Qe(t)?n:"/timetable":se(a,"/people")?oi(t)?n:"/timetable":se(a,"/people/members/:uuid")?Kn(t)||Qe(t)?n:"/timetable":se(a,"/people/members")?Kn(t)?n:"/timetable":se(a,"/people/prospects")||se(a,"/people/prospects/:uuid")?Yn(t)?n:"/timetable":se(a,"/people/households")||se(a,"/people/households/:uuid")?Zn(t)?n:"/timetable":se(a,"/forms")?ko(t)?n:"/timetable":se(a,"/password-setup")?un(t)?n:"/timetable":se(a,"/progress")||se(a,"/attendance")?Xt(t)?n:"/timetable":se(a,"/memberships")?va(t)?n:"/timetable":se(a,"/payment-methods")?li(t)?n:"/timetable":se(a,"/billing-history")?wo(t)?n:"/timetable":se(a,"/household")?Bc(t)?n:"/timetable":se(a,"/curriculum")||se(a,"/curriculum/point/:itemUuid/notes")||se(a,"/curriculum/point/:itemUuid/notes/new")||se(a,"/curriculum/point/:itemUuid/notes/:entryUuid/edit")||se(a,"/curriculum/point/:itemUuid/checkpoints")||se(a,"/curriculum/point/:itemUuid/checkpoints/new")||se(a,"/curriculum/point/:itemUuid/checkpoints/:entryUuid/edit")?Ws(t)?n:"/timetable":(se(a,"/chat")||se(a,"/chat/:channelUuid"),"/timetable")}function Jb(t){const s=/^(\d{4})-(\d{2})-(\d{2})$/.exec(t.trim());return s?{year:Number(s[1]),month:Number(s[2]),day:Number(s[3])}:null}function Xb(t){const s=t.getUTCFullYear(),n=`${t.getUTCMonth()+1}`.padStart(2,"0"),a=`${t.getUTCDate()}`.padStart(2,"0");return`${s}-${n}-${a}`}function ef(t,s){const n=Jb(t);if(!n)return t;const a=new Date(Date.UTC(n.year,n.month-1,n.day+s));return Xb(a)}function tf(t){const s=new Intl.DateTimeFormat("en-GB",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(new Date),n=s.find(o=>o.type==="year")?.value??"1970",a=s.find(o=>o.type==="month")?.value??"01",i=s.find(o=>o.type==="day")?.value??"01";return`${n}-${a}-${i}`}function sf(t,s){const n=new Date(t);if(Number.isNaN(n.getTime()))return null;const a=new Intl.DateTimeFormat("en-GB",{timeZone:s,year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(n),i=a.find(c=>c.type==="year")?.value,o=a.find(c=>c.type==="month")?.value,l=a.find(c=>c.type==="day")?.value;return!i||!o||!l?null:`${i}-${o}-${l}`}function nf(t,s,n){let a=null;for(const i of t){const o=sf(i.startTime,n);!o||o<s||(!a||o<a)&&(a=o)}return a??s}async function af(t){const s=tf(t),n=ef(s,60),a=await T.timetable.listTimetable({rangeStart:`${s}T00:00:00.000Z`,rangeEnd:`${n}T23:59:59.999Z`,programId:null}),i=Array.isArray(a.items)?a.items:[];return nf(i,s,t)}function Nl(t,s,n){const a=s?.trim()??"";if(a.startsWith("/")&&!a.startsWith("//")&&!a.includes("\\")){const o=new URL(a,"https://member.invalid"),l=go(o.pathname);if(/^\/(?:book-a-trial|trial-intake\/[a-z0-9-]+|onboarding\/(?:trial(?:\/status|\/offer\/[a-zA-Z0-9-]+)?|membership(?:\/status|\/plan\/[a-zA-Z0-9-]+)?|conversion(?:\/status)?))$/.test(l))return`${l}${o.search}${o.hash}`}const i=s||(n?`/timetable?date=${encodeURIComponent(n)}`:"/timetable");return Mo(t,i)}async function rf(t,s){if(s)return Nl(t,s,null);let n=null;try{n=await af(T.tenant.getTenantTimezone())}catch{n=null}return Nl(t,null,n)}function of(){const t=tt(),s=mt(),{acceptMobileLoginHandoff:n,isReady:a}=Ge(),i=r.useMemo(()=>new URLSearchParams(s.search).get("code")?.trim()||"",[s.search]),o=/^[A-Za-z0-9_-]{43}$/.test(i),[l,c]=r.useState(!1),[u,d]=r.useState(""),h=async()=>{if(!(!o||l)){d(""),c(!0);try{await n(i),t.replace("/timetable")}catch(m){d(m instanceof cn||m instanceof Error?m.message:"Unable to use this mobile login link.")}finally{c(!1)}}};return e.jsxs(mr,{contentClassName:"member-mobile-login-shell",children:[e.jsx("div",{className:"member-mobile-login-icon","aria-hidden":"true",children:e.jsx(V,{icon:cm})}),e.jsx("h1",{className:"member-mobile-login-title",children:"Test member app on this phone"}),e.jsx("p",{className:"member-mobile-login-copy",children:"This one time link signs this phone into the selected member or prospect account for testing."}),e.jsxs("div",{className:"member-mobile-login-notice",children:[e.jsx(V,{icon:cc,"aria-hidden":"true"}),e.jsx("span",{children:"The link expires after five minutes and works once."})]}),o?null:e.jsx("p",{className:"member-mobile-login-error",role:"alert",children:"This mobile login link is invali
2d or incomplete. Create a new link in SkullSystem Admin."}),u?e.jsx("p",{className:"member-mobile-login-error",role:"alert",children:u}):null,e.jsx(vt,{className:"member-mobile-login-submit",expand:"block",onClick:()=>{h()},disabled:!a||!o||l,children:l?e.jsx(Te,{name:"crescent"}):"CONTINUE TO MEMBER APP"}),e.jsx("button",{type:"button",className:"member-mobile-login-cancel",disabled:l,onClick:()=>t.replace("/login"),children:"Back to sign in"})]})}function lf(){return e.jsx(Cn,{className:"skull-not-found-page",children:e.jsx(wn,{fullscreen:!0,forceOverscroll:!1,children:e.jsxs("main",{className:"skull-not-found-shell",children:[e.jsx("div",{className:"skull-not-found-glow","aria-hidden":"true"}),e.jsxs("section",{className:"skull-not-found-card",children:[e.jsx("img",{src:Ki,alt:"SkullSystem",className:"skull-not-found-mark"}),e.jsx("p",{className:"skull-not-found-code",children:"404"}),e.jsx("h1",{children:"This route has gone rogue."}),e.jsx("p",{className:"skull-not-found-copy",children:"The page you asked for does not exist. Bold choice, though."}),e.jsxs("div",{className:"skull-not-found-actions",children:[e.jsx(tr,{to:"/timetable",className:"skull-not-found-primary",children:"Back to the real app"}),e.jsx(tr,{to:"/login",className:"skull-not-found-secondary",children:"Go to login"})]}),e.jsx("p",{className:"skull-not-found-footnote",children:"SkullSystem checked twice. Still not a page."})]})]})})})}function cf(t){return t==="granted"?"Allowed on this device":t==="denied"?"Blocked on this device":t==="default"?"Not enabled":"Not supported"}function kl(t){const s=t?.device.latestDelivery;return s?s.openedAt?"Opened on this device":s.status==="accepted"?"Accepted by the push service. This does not prove that the phone displayed it.":s.status==="queued"||s.status==="processing"?"Queued for delivery":s.status==="retry"?"Waiting to retry":s.status==="subscription_expired"?"The saved subscription expired. Disable and enable notifications again.":s.status==="failed"?"Delivery failed. Disable and enable notifications again, then retry.":s.status==="suppressed"?"Not sent because a reminder rule blocked it":"Delivery state is not available":null}function uf(){const t=tt(),[s,n]=r.useState(null),[a,i]=r.useState(!0),[o,l]=r.useState(!1),[c,u]=r.useState(""),d=T.notifications.permission(),h=r.useCallback(async N=>{i(!0);try{n(await T.notifications.getSettings(N))}catch(x){u(re(x,"Unable to load notification settings."))}finally{i(!1)}},[]);r.useEffect(()=>{const N=new AbortController;return h(N.signal),()=>N.abort()},[h]);const m=r.useMemo(()=>{const N=new Map;for(const x of s?.events??[])!x.channels.push.ownerEnabled&&!x.channels.email.ownerEnabled&&!x.channels.sms.ownerEnabled||N.set(x.group,[...N.get(x.group)??[],x]);return[...N.entries()]},[s]),f=r.useMemo(()=>(s?.events??[]).some(N=>N.channels.push.ownerEnabled||N.channels.email.ownerEnabled||N.channels.sms.ownerEnabled),[s]);async function b(){l(!0);try{n(await T.notifications.subscribe()),u("Notifications are enabled on this device.")}catch(N){u(re(N,"Unable to enable notifications."))}finally{l(!1)}}async function p(){l(!0);try{n(await T.notifications.unsubscribe()),u("Notifications are disabled on this device.")}catch(N){u(re(N,"Unable to disable notifications."))}finally{l(!1)}}async function g(){l(!0);try{const N=await T.notifications.sendTestPush();n(await T.notifications.getSettings()),u(N.queued?"Test notification queued. Lock your phone and allow up to two minutes.":"A test was already requested or could not be queued.")}catch(N){u(re(N,"Unable to send the test notification."))}finally{l(!1)}}async function v(N,x,k){l(!0);try{n(await T.notifications.savePreference(N,x,k)),u("Notification preference saved.")}catch(j){u(re(j,"Unable to save notification preference."))}finally{l(!1)}}return e.jsxs(Ye,{standardUI:!0,title:"Notifications",subtitle:"Choose which notifications you receive.",activeTab:"settings",backTo:"/settings",onRefresh:h,refresherDisabled:o,suppressReadOnlyNotice:!0,children:[a?e.jsxs("div",{className:"member-panel-loading",children:[e.jsx(Te,{name:"crescent"}),e.jsx("span",{children:"Loading notification settings..."})]}):null,a?null:e.jsxs(e.Fragment,{children:[e.jsxs("section",{className:"member-panel-card member-notification-device-card",children:[e.jsx("h2",{children:"This device"}),e.jsxs("p",{children:["Permission: ",cf(d)]}),e.jsxs("p",{children:["Subscription: ",s?.device.subscribed?"Active":"Not subscribed"]}),e.jsx("p",{children:"Enable this device to receive all available alerts. You can switch off any alerts you do not want below."}),e.jsx("p",{children:"Tap a notification to open the app."}),s?.device.subscribed?e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",className:"member-panel-action is-solid",disabled:o||d!=="granted"||!s.platformConfigured,onClick:()=>{g()},children:"Send test notification"}),e.jsx("button",{type:"button",className:"member-panel-action",disabled:o,onClick:()=>{p()},children:"Disable on this device"})]}):e.jsx("button",{type:"button",className:"member-panel-action is-solid",disabled:o||d==="denied"||d==="unsupported"||!s?.platformConfigured,onClick:()=>{b()},children:"Enable notifications"}),kl(s)?e.jsxs("p",{children:[e.jsx("strong",{children:"Last delivery:"})," ",kl(s)]}
2):null,s?.device.subscribed?e.jsx("p",{children:"On iPhone, Sleep Focus or another Focus can silence this app. Turn Focus off for the test, or allow SkullSystem in Settings, Focus, active Focus, Apps."}):null,s?.platformConfigured?null:e.jsx("p",{children:"Web Push has not been configured by the platform yet."}),d==="denied"?e.jsx("p",{children:"Notifications are blocked in this browser. Restore permission in browser or phone settings."}):null,e.jsxs(pt,{className:"member-toggle-row member-setting-info",lines:"none",children:[e.jsxs(yt,{children:[e.jsx("h3",{children:"Private lock screen preview"}),e.jsx("p",{children:"Hide message, class and account details until the app opens."})]}),e.jsx(js,{slot:"end",checked:s?.device.privatePreview??!0,disabled:!s?.device.subscribed||o,onIonChange:N=>{l(!0),T.notifications.savePrivatePreview(N.detail.checked).then(n).catch(x=>u(re(x,"Unable to save private preview."))).finally(()=>l(!1))}})]})]}),f?null:e.jsxs("section",{className:"member-access-notice",role:"status",children:[e.jsx("strong",{children:"No reminder types are available yet"}),e.jsx("p",{children:"Your gym has not enabled any reminder types yet."})]}),m.map(([N,x])=>N==="Lead conversations"?e.jsxs("section",{className:"member-notification-group",children:[e.jsx("h2",{children:"Lead conversations"}),e.jsx("p",{children:"All available alerts are on by default. Switch off any alerts you do not want. These choices are saved to your staff account."}),e.jsx("div",{className:"member-panel-list",children:x.map(k=>e.jsxs(pt,{className:"member-toggle-row",lines:"none",children:[e.jsxs(yt,{children:[e.jsx("h3",{children:k.label}),e.jsx("p",{children:k.eventKey==="lead_new_message"?"The first message in a new chat.":k.eventKey==="lead_new_reply"?"A lead replies in an existing chat.":"Jack stops and needs a staff member to take over."}),k.channels.push.ownerEnabled?null:e.jsx("p",{children:"Disabled by your gym."})]}),e.jsx(js,{slot:"end",checked:k.channels.push.userEnabled,disabled:o||!k.channels.push.ownerEnabled,"aria-label":k.label,onIonChange:j=>{v(k.eventKey,"push",j.detail.checked)}})]},k.eventKey))}),s?.device.subscribed?null:e.jsx("p",{children:"Enable notifications on this device to receive these alerts."})]},N):e.jsxs("section",{className:"member-notification-group",children:[e.jsx("h2",{children:N}),e.jsx("div",{className:"member-panel-list",children:x.map(k=>e.jsxs("div",{className:"member-notification-event member-setting-group",children:[e.jsx("h3",{children:k.label}),["push","email","sms"].filter(j=>k.channels[j].ownerEnabled).map(j=>e.jsxs(pt,{className:"member-toggle-row",lines:"none",children:[e.jsx(yt,{children:e.jsx("h3",{children:j==="push"?"Push notification":j==="sms"?"SMS":"Email"})}),e.jsx(js,{slot:"end",checked:k.channels[j].userEnabled,disabled:o,"aria-label":`${k.label} ${j==="push"?"Push notification":j==="sms"?"SMS":"Email"} preference`,onIonChange:I=>{v(k.eventKey,j,I.detail.checked)}})]},j))]},k.eventKey))})]},N)),e.jsx("button",{type:"button",className:"member-panel-action is-page-action",onClick:()=>t.push("/settings"),children:"Back to App Settings"})]}),e.jsx(Dt,{isOpen:!!c,message:c,duration:3e3,onDidDismiss:()=>u("")})]})}function on({ariaLabel:t,value:s,onChange:n,isSearching:a=!1,className:i="",...o}){return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:`member-search-control ${i}`,children:[e.jsx(V,{icon:bc,"aria-hidden":"true"}),e.jsx("input",{type:"search",autoComplete:"off",enterKeyHint:"search",...o,"aria-label":t,value:s,onChange:l=>n(l.target.value)}),a?e.jsx("span",{className:"member-search-progress","aria-hidden":"true"}):null]}),e.jsx("span",{className:"sr-only",role:"status","aria-live":"polite",children:a?`Searching ${t.toLowerCase()}`:""})]})}const wl={data:[],pagination:{next_cursor:null}},Wa=new Map;function Di({text:t,query:s}){return e.jsx(e.Fragment,{children:qm(t,s).map((n,a)=>n.match?e.jsx("mark",{children:n.text},a):e.jsx("span",{children:n.text},a))})}function df(){const{user:t,hasRole:s}=Ge();return!s("instructor","admin","owner")&&t?.featureFlags?.curriculumTrackingEnabled!==!0?e.jsx(Ye,{standardUI:!0,title:"Curriculum",activeTab:"none",backTo:"/training",children:e.jsxs("section",{className:"member-panel-card",children:[e.jsx("h2",{children:"Curriculum tracking is not enabled"}),e.jsx("p",{children:"This school has not enabled curriculum viewing for the member app."})]})}):e.jsx(mf,{})}function mf(){const[t,s]=Yl(),n=mt(),a=r.useRef(n.search);a.current=n.search;
2const i=po(),{user:o}=Ge(),[l,c]=r.useState([]),[u,d]=r.useState([]),[h,m]=r.useState(null),[f,b]=r.useState(wl),[p,g]=r.useState(!0),[v,N]=r.useState(""),[x,k]=r.useState(0),[j,I]=r.useState(!1),[S,M]=r.useState(!1);r.useEffect(()=>{if(p)return;const G=n.search,J=document.querySelector(".curriculum-reader:not(.ion-page-hidden) ion-content");let ke=!1,Be=()=>{};return J?.getScrollElement().then(fe=>{if(ke)return;fe.scrollTop=Wa.get(G)||0;const Ae=()=>{Wa.set(G,fe.scrollTop),Wa.size>50&&Wa.delete(Wa.keys().next().value)};fe.addEventListener("scroll",Ae,{passive:!0}),Be=()=>fe.removeEventListener("scroll",Ae)}),()=>{ke=!0,Be()}},[n.search,p]);const y=t.get("program")||"",P=t.get("item")||"",U=t.get("entry")||"",F=t.get("view")==="library",A=t.get("q")||"",D=t.get("level")||"",R=t.get("type")||(P?"checkpoint":""),w=t.get("scope")||"",_=t.get("section")||"",W=["owner","admin","instructor"].includes(o?.role||""),H=(G,J=!0)=>{const ke=new URLSearchParams(t);Object.entries(G).forEach(([Be,fe])=>fe?ke.set(Be,fe):ke.delete(Be)),s(ke,{replace:J})};r.useEffect(()=>{const G=new AbortController;return T.curriculum.listPrograms({signal:G.signal}).then(J=>{c(J.rows),!y&&!F&&!P&&J.rows.length&&s(ke=>{const Be=new URLSearchParams(ke);return Be.set("program",J.defaultProgramUuid||J.rows[0].uuid),Be},{replace:!0})}).catch(J=>{G.signal.aborted||N(String(J.message||J))}),()=>G.abort()},[y,F,P,s]),r.useEffect(()=>{const G=new AbortController;return d([]),y&&T.curriculum.readerItems(y,G.signal).then(J=>d(J.data)).catch(J=>{G.signal.aborted||N(String(J.message||J))}),()=>G.abort()},[y]);const ne=r.useMemo(()=>P?{item_uuid:P,entry_uuid:U,type:R,scope:w}:{program_uuid:y,q:A,level:D,section:_,type:F?R:"",scope:F?w:""},[P,U,y,A,D,_,R,w,F]);r.useEffect(()=>{const G=new AbortController;g(!0),N(""),b(wl),m(null);const J=window.setTimeout(async()=>{try{P&&m(await T.curriculum.readerDetail(P,G.signal)),(P||F||A.trim())&&b(await T.curriculum.readerSearch(ne,!!P||F,G.signal))}catch(ke){G.signal.aborted||N(ke instanceof Error?ke.message:"Unable to load curriculum.")}finally{G.signal.aborted||g(!1)}},A?250:0);return()=>{G.abort(),window.clearTimeout(J)}},[ne,P,F,A,x]);const K=(G,J)=>{const ke=new URLSearchParams({item:G,back:n.pathname+n.search});J&&(ke.set("type",J.entry_type),ke.set("scope",J.visibility_scope),ke.set("entry",J.uuid)),i(`/curriculum?${ke}`,{state:{readerBack:n.pathname+n.search}})},ye=()=>{const G=t.get("back");G==="/curriculum"||G?.startsWith("/curriculum?")?i(G,{replace:!0}):i("/curriculum")},de=async()=>{if(!f.pagination.next_cursor||S)return;M(!0);const G=a.current;try{const J=await T.curriculum.readerSearch({...ne,cursor:f.pagination.next_cursor},!!P||F);if(a.current!==G)return;b(ke=>({data:[...ke.data,...J.data],pagination:J.pagination}))}catch(J){N(J instanceof Error?J.message:"Unable to load more.")}finally{M(!1)}},O=async(G,J)=>{if(!(!h||S)){M(!0),N("");try{m(await T.curriculum.readerPresentation(h.item.uuid,{hero_note_uuid:G?.uuid||null,hero_media_uuid:J}))}catch(ke){N(ke instanceof Error?ke.message:"Unable to save image.")}finally{M(!1)}}},L=[...new Set(u.map(G=>G.level_label).filter(G=>!!G))],Z=t.get("browseLevel")||L[0]||"",ce=Fm(u,Z),me=ce.find(G=>G.node_type==="level")?.uuid,[Ne,ve]=r.useState(null);r.useEffect(()=>{const G=new AbortController;return ve(null),me&&T.curriculum.readerDetail(me,G.signal).then(ve).catch(()=>{}),()=>G.abort()},[me]);const xe=G=>{h&&i(`/curriculum/point/${h.item.uuid}/${R==="note"?"notes":"checkpoints"}/${G?`${G.uuid}/edit`:"new"}?readerReturnTo=${encodeURIComponent(n.pathname+n.search)}`,{state:{readerReturnTo:n.pathname+n.search,activeScope:G?.visibility_scope||"my"}})};return e.jsxs(Ye,{standardUI:!0,title:h?Dn(h.item):F?"Notes & Checkpoints":"Curriculum",activeTab:o?.role==="instructor"?"curriculum":"none",pageClassName:"curriculum-reader",onRefresh:()=>k(G=>G+1),children:[P?e.jsx(vt,{fill:"clear",onClick:ye,children:"Back"}):e.jsxs(Hn,{className:"member-compact-segment",value:F?"library":"browse",onIonChange:G=>H({view:G.detail.value==="library"?"library":"",q:"",type:"",scope:"",level:"",section:""},!1),children:[e.jsx(Ps,{value:"browse",children:"Curriculum"}),e.jsx(Ps,{value:"library",children:"Notes & Checkpoints"})]}),U&&e.jsxs(vt,{fill:"clear",onClick:()=>H({entry:""}),children:["Show all ",R==="note"?"notes":"checkpoints"," on this point"]}),v&&e.jsxs("p",{role:"alert",className:"member-panel-error",children:[v,e.jsx(vt,{fill:"clear",onClick:()=>k(G=>G+1),children:"Retry"})]}),!P&&e.jsxs(e.Fragment,{children:[e.jsx(rs,{label:"Programme",value:y,options:[...F?[{value:"",label:"All programmes"}]:[],...l.map(G=>({value:G.uuid,label:G.name}))],onChange:G=>H({program:G,level:"",browseLevel:"",section:""})}),e.jsx(on,{ariaLabel:F?"Search notes and checkpoints":"Search all curriculum levels",placeholder:F?"Search notes and checkpoints":"Search all levels by code or keyword",value:A,onChange:G=>H({q:G})}),F||A?e.jsxs(e.Fragment,{children:[e.jsxs(vt,{fill:"clear",onClick:()=>I(G=>!G),"aria-expanded":j,children:["Filters",D||w||R||_?" (active)":""]}),j&&e.jsxs("div",{className:"member-panel-card",children:[e.jsx(rs,{label:"Level",value:D,options:[{value:"",label:"All levels"},...L.map(G=>({value:G,label:G}))],onChange:G=>H({level:G,section:""})}),F&&e.jsxs(e.Fragment,{children:[e.jsx(rs,{label:"Section",value:_,options:[{value:"",label:"All sections"},...u.filter(G=>
2G.node_type==="group"&&(!D||G.level_label===D)).map(G=>({value:G.uuid,label:Dn(G)}))],onChange:G=>H({section:G})}),e.jsx(rs,{label:"Type",value:R,options:[{value:"",label:"All entries"},{value:"checkpoint",label:"Checkpoints"},{value:"note",label:"Notes"}],onChange:G=>H({type:G})})]})]})]}):e.jsx(rs,{label:"Level",value:Z,options:L.map(G=>({value:G,label:G})),onChange:G=>H({browseLevel:G,open:""})})]}),(F||P)&&e.jsx(rs,{label:"Visibility",value:w,options:[{value:"",label:"All I can access"},{value:"public",label:"Official checkpoints"},...W?[{value:"instructors",label:"Instructors"}]:[],{value:"my",label:"Private to me"}],onChange:G=>H({scope:G})}),p&&e.jsxs("div",{className:"member-panel-loading",children:[e.jsx(Te,{})," Loading curriculumâ¦"]}),!p&&h&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"curriculum-reader-location",children:Pi(h.path)}),h.hero?.url&&e.jsx("img",{className:"curriculum-reader-hero",src:h.hero.url,alt:h.item.title}),h.hero&&h.can_manage_hero&&e.jsx(vt,{fill:"clear",disabled:S,onClick:()=>O(null,null),children:"Remove top image"}),Cr(h.item).map(G=>e.jsx("p",{className:"curriculum-reader-copy",children:G},G)),h.children.length>0&&e.jsx("section",{"aria-label":"Subpoints",children:h.children.map(G=>e.jsx(pt,{button:!0,detail:!0,onClick:()=>K(G.uuid),children:e.jsxs(yt,{className:"ion-text-wrap",children:[e.jsx("h2",{children:Dn(G)}),Cr(G).map(J=>e.jsx("p",{children:J},J))]})},G.uuid))}),e.jsxs(Hn,{className:"member-compact-segment",value:R,onIonChange:G=>H({type:String(G.detail.value),entry:""}),children:[e.jsx(Ps,{value:"checkpoint",children:"Checkpoints"}),e.jsx(Ps,{value:"note",children:"Notes"})]}),h.can_add_entry&&e.jsxs(vt,{onClick:()=>xe(),children:["Add ",R==="note"?"note":"checkpoint"]})]}),!p&&!P&&!F&&!A&&e.jsxs(e.Fragment,{children:[Ne?.pdf&&e.jsx(vt,{fill:"outline",href:Ne.pdf.url,target:"_blank",rel:"noopener noreferrer",children:"Download level PDF"}),e.jsx(vd,{value:t.get("open")||void 0,onIonChange:G=>{G.target.tagName==="ION-ACCORDION-GROUP"&&H({open:String(G.detail.value||"")})},children:ce.filter(G=>G.node_type==="subject").map(G=>e.jsxs("section",{children:[e.jsx("h2",{children:Dn(G)}),ce.filter(J=>J.node_type==="group"&&J.parent_uuid===G.uuid).map(J=>e.jsxs(Nd,{value:J.uuid,children:[e.jsx(pt,{slot:"header",children:e.jsx(yt,{className:"ion-text-wrap",children:Dn(J)})}),e.jsxs("div",{slot:"content",className:"member-panel-card",children:[Cr(J).map(ke=>e.jsx("p",{children:ke},ke)),ce.filter(ke=>ke.parent_uuid===J.uuid).map(ke=>e.jsx(pt,{button:!0,detail:!0,onClick:()=>K(ke.uuid),children:e.jsx(yt,{className:"ion-text-wrap",children:Dn(ke)})},ke.uuid)),e.jsx(vt,{fill:"clear",onClick:()=>K(J.uuid),children:"Section information"})]})]},J.uuid))]},G.uuid))}),!ce.length&&e.jsx("p",{children:"No curriculum available for this level."})]}),!p&&(P||F||A)&&e.jsxs(e.Fragment,{children:[!f.data.length&&e.jsxs("p",{children:["No ",P||F?"entries":"results"," found. Try another keyword or clear the filters."]}),f.data.map(G=>G.entry?e.jsxs("section",{className:"member-panel-card",id:`entry-${G.entry.uuid}`,children:[e.jsxs("p",{className:"curriculum-reader-location",children:[G.entry.entry_type==="checkpoint"?"Checkpoint":"Note"," ","·"," ",G.entry.visibility_scope==="public"?"Official":G.entry.visibility_scope==="my"?"Private to me":"Instructors"]}),F&&e.jsx(vt,{fill:"clear",onClick:()=>K(G.item.uuid,G.entry),children:Pi(G.path)}),e.jsx("p",{className:"curriculum-reader-copy",children:e.jsx(Di,{text:F?Wm(G.entry.note_text,A):G.entry.note_text,query:A})}),(F?[]:G.entry.attachments).map(J=>e.jsxs("div",{children:[J.url&&(J.mime_type.startsWith("image/")?e.jsx("a",{href:J.url,target:"_blank",rel:"noopener noreferrer",children:e.jsx("img",{className:"curriculum-reader-attachment",src:J.thumbnail_url||J.url,alt:J.original_filename||"Checkpoint image",loading:"lazy"})}):e.jsx("a",{href:J.url,target:"_blank",rel:"noopener noreferrer",children:J.original_filename||"Download attachment"})),h?.can_manage_hero&&["item","variation"].includes(h.item.node_type)&&h.presentation_ready&&G.entry?.visibility_scope==="public"&&J.mime_type.startsWith("image/")&&e.jsx(vt,{fill:"clear",disabled:S,onClick:()=>O(G.entry,J.media_uuid),children:"Use as top image"})]},J.media_uuid)),(F?[]:G.entry.reference_links).map(J=>e.jsx("p",{children:e.jsx("a",{href:J.url,target:"_blank",rel:"noopener noreferrer",children:J.label||J.url})},J.url)),h&&G.entry.can_edit&&e.jsx(vt,{fill:"clear",onClick:()=>xe(G.entry),children:"Edit"})]},G.entry.uuid):e.jsx(pt,{button:!0,detail:!0,onClick:()=>K(G.item.uuid),children:e.jsxs(yt,{className:"ion-text-wrap",children:[e.jsx("h2",{children:e.jsx(Di,{text:Dn(G.item),query:A})}),e.jsx("p",{children:Pi(G.path)}),Cr(G.item).filter(J=>J.toLowerCase().includes(A.toLowerCase())).slice(0,1).map(J=>e.jsx("p",{children:e.jsx(Di,{text:J,query:A})},J))]})},G.item.uuid)),f.pagination.next_cursor&&e.jsx(vt,{disabled:S,onClick:de,children:"Load more"})]})]})}function Mr(t){return(t||"").replace(/\*/g,"").replace(/\s+/g," ").trim()}function lo(t){const s=(t.code||"").trim();if(!s)return"";const n=s.toLowerCase();return n.startsWith("pillar:")||n.startsWith("section:")||n.startsWith("level:")?"":s.replace(/\*/g,"").replace(/\s+/g," ").trim()}function hf(t){const s=(t.code||"").trim();if(!s)return"";if(s.toLowerCase().startsWith("section:")){const n=s.split(":");return(n[n.length-1]||"").trim()}return""}function pf(t){const s=lo(t);if(!s)return"";const n=s.split(/\s+/).filter(a=>a.length>0);return n[n.length-1]||""}function bf(t){return pf(t).split(".").map(s=>s.trim()).filter(s=>s.length>0)}function ff(t){return t?/^\d+$/.test(t)?`${t}.`:t:""}function gf(t){return/^[a-z]+$/i.test(t.trim())}
2function xf(t,s){if(t.nodeType==="group"){const n=hf(t),a=Mr(t.title)||"Untitled";return`${n?`${n} `:""}${a}`}if(t.nodeType==="item"||t.nodeType==="variation"){const n=Mr(t.title)||"Untitled",a=bf(t);if(a.length===0){const l=lo(t);return l?`${l} ${n}`:n}const i=a.length>1?a.slice(1).join("."):a[0]||"",o=gf(i)?`${i}.`:ff(i);return o?`${o} ${n}`:n}return t.nodeType==="subject"?Mr(t.title||"Untitled").toUpperCase():t.nodeType==="level"&&(t.levelLabel||"").trim()!==""?(t.levelLabel||"").trim():Mr(t.title)||lo(t)||"Untitled"}function Li(t){return t==="my"?"My private entries":t==="instructors"?"Instructor notes":"Official checkpoints"}function jf(t){return t==="private"?"Private to me":t==="staff"?"Instructors only":"Official checkpoint"}function yf(t){return t==="my"?"private":t==="instructors"?"staff":"member_staff"}function qa(t){return t==="checkpoint"?"Checkpoints":"Notes"}function vf(t,s){return t.updatedAt?`Updated ${zs(t.updatedAt,s)}`:t.createdAt?zs(t.createdAt,s):"Date unavailable"}function Nf(t,s,n){return t?n==="checkpoint"&&s?["private","staff","member_staff"]:["private","staff"]:["private"]}function kf(t){return t?["public","instructors","my"]:["public","my"]}function wf(t){return{mediaUuid:t.mediaUuid,originalFilename:t.originalFilename,mimeType:t.mimeType,sizeBytes:t.sizeBytes,visibility:t.visibility,url:t.url,thumbnailUrl:t.thumbnailUrl}}function Cl(t,s,n,a){return{visibility:s==="public"?a&&t==="checkpoint"?"member_staff":"private":n?yf(s):"private",noteText:"",sortOrderInput:"",referenceLinks:[],attachments:[]}}function Cf(t){return`${t.reduce((n,a)=>a.entryType!=="checkpoint"||a.sortOrder==null||!Number.isFinite(a.sortOrder)?n:Math.max(n,a.sortOrder),0)+1}`}function Sf(t){return t.attachments.filter(s=>typeof s.mimeType=="string"&&s.mimeType.startsWith("image/")&&!!(s.url||s.thumbnailUrl))}function co(t,s){return`/curriculum/point/${t}/${s==="note"?"notes":"checkpoints"}`}function Pf(t,s,n){const a=co(t,s);return n?`${a}/${n}/edit`:`${a}/new`}async function Rf(t,s){return T.curriculum.readerLegacyItem(t,s)}function Tf(t){return{visibility:t.visibility,noteText:t.noteText,sortOrderInput:t.entryType==="checkpoint"&&t.sortOrder!==null?`${t.sortOrder}`:"",referenceLinks:t.referenceLinks.map(s=>({...s})),attachments:t.attachments.map(s=>wf(s))}}function _f({entryType:t,editingEntry:s,isSaving:n,isUploading:a,errorMessage:i,availableVisibilities:o,state:l,onCancel:c,onChange:u,onOpenAttachmentPicker:d,onSave:h}){const m=t==="checkpoint",f=s?`Update ${m?"checkpoint":"note"}`:`Save ${m?"checkpoint":"note"}`,b=o.map(p=>({value:p,label:jf(p)}));return e.jsxs("form",{className:"member-form-stack",noValidate:!0,onSubmit:p=>{p.preventDefault(),!(n||a)&&h()},children:[e.jsx(rs,{label:"Visibility",value:l.visibility,options:b,onChange:p=>{u({...l,visibility:p})}}),m?e.jsx(Bt,{label:"Checkpoint number",helpText:"Lower numbers appear first in the checkpoint list.",type:"number",inputMode:"numeric",min:"1",value:l.sortOrderInput,placeholder:"1",onChange:p=>{u({...l,sortOrderInput:p.replace(/[^\d]/g,"")})}}):null,e.jsx(vn,{label:m?"Checkpoint":"Note",value:l.noteText,placeholder:m?"Write the checkpoint...":"Write the note...",onChange:p=>{u({...l,noteText:p})}}),e.jsx(pt,{className:"member-form-block member-form-info-item member-form-section-item",lines:"none",mode:"md",children:e.jsxs(yt,{children:[e.jsx("h3",{children:"References"}),e.jsxs("p",{children:["Add links that support this ",m?"checkpoint":"note","."]})]})}),l.referenceLinks.length>0?e.jsx("div",{className:"member-form-fields",children:l.referenceLinks.map((p,g)=>e.jsxs("section",{className:"member-form-section",children:[e.jsx(Bt,{label:`Reference label ${g+1}`,value:p.label||"",placeholder:"Label (optional)",onChange:v=>{const N=[...l.referenceLinks];N[g]={...N[g],label:v},u({...l,referenceLinks:N})}}),e.jsx(Bt,{label:`Reference URL ${g+1}`,value:p.url,type:"url",placeholder:"https://...",onChange:v=>{const N=[...l.referenceLinks];N[g]={...N[g],url:v},u({...l,referenceLinks:N})}}),e.jsx("div",{className:"member-list-actions",children:e.jsx("button",{type:"button",className:"member-form-action-btn is-inline is-neutral",onClick:()=>
2{u({...l,referenceLinks:l.referenceLinks.filter((v,N)=>N!==g)})},children:"Remove"})})]},`reference-${g}`))}):e.jsx("p",{className:"member-copy",children:"No references added yet."}),e.jsx("div",{className:"member-list-actions",children:e.jsx("button",{type:"button",className:"member-form-action-btn is-inline is-neutral",onClick:()=>{u({...l,referenceLinks:[...l.referenceLinks,{label:"",url:""}]})},children:"Add reference"})}),e.jsx(pt,{className:"member-form-block member-form-info-item member-form-section-item",lines:"none",mode:"md",children:e.jsxs(yt,{children:[e.jsx("h3",{children:"Attachments"}),e.jsxs("p",{children:["Add photos or PDFs to support this ",m?"checkpoint":"note","."]})]})}),e.jsx("div",{className:"member-list-actions",children:e.jsx("button",{type:"button",className:"member-form-action-btn is-inline is-neutral",disabled:a,onClick:d,children:a?"Uploading...":"Add attachment"})}),l.attachments.length>0?e.jsx("div",{className:"member-panel-list",children:l.attachments.map(p=>{const g=typeof p.mimeType=="string"&&p.mimeType.startsWith("image/");return e.jsxs("div",{className:"member-panel-row member-curriculum-attachment-row",children:[e.jsxs("div",{className:"member-row-main",children:[e.jsx("strong",{children:p.originalFilename||"Attachment"}),e.jsx("span",{className:"member-pill",children:p.sizeBytes?`${Math.round(p.sizeBytes/1024)} KB`:"File"})]}),e.jsx("div",{className:"member-curriculum-entry-media",children:g&&(p.thumbnailUrl||p.url)?e.jsx("img",{className:"member-curriculum-entry-thumbnail",src:p.thumbnailUrl||p.url||"",alt:p.originalFilename||"Attachment"}):e.jsxs("span",{className:"member-curriculum-file-badge",children:[e.jsx(V,{icon:fc}),p.mimeType||"Document"]})}),e.jsx("div",{className:"member-list-actions",children:e.jsx("button",{type:"button",className:"member-form-action-btn is-inline is-neutral",onClick:()=>{u({...l,attachments:l.attachments.filter(v=>v.mediaUuid!==p.mediaUuid)})},children:"Remove"})})]},p.mediaUuid)})}):e.jsx("p",{className:"member-copy",children:"No attachments added yet."}),i?e.jsx("p",{className:"member-password-error",children:i}):null,e.jsxs("div",{className:"member-list-actions member-form-action-row",children:[e.jsx("button",{type:"submit",className:"member-form-action-btn is-primary",disabled:n||a,children:n?"Saving...":f}),e.jsx("button",{type:"button",className:"member-form-action-btn",disabled:n||a,onClick:c,children:"Close"})]})]})}function ca({entryType:t,composerMode:s="list"}){const n=tt(),a=mt(),i=new URLSearchParams(a.search).get("readerReturnTo")||a.state?.readerReturnTo,o=i?.startsWith("/curriculum?")?i:null,l=r.useRef(!1);r.useEffect(()=>{l.current=!1},[a.key]);const{itemUuid:c="",entryUuid:u}=Qs(),{user:d}=Ge(),h=d?.role==="instructor",m=T.tenant.getTenantTimezone(),f=d?.role==="owner"||d?.role==="admin"||d?.role==="instructor",b=d?.role==="owner"||d?.role==="admin"||d?.staffCapabilities?.lesson_planning_approve_publish===!0,p=r.useMemo(()=>kf(f),[f]),g=r.useMemo(()=>Nf(f,b,t),[b,f,t]),v=a.state?.item&&a.state.item.uuid===c?a.state.item:null,N=s==="edit"&&u&&a.state?.entry?.uuid===u?a.state.entry:null,x=a.state?.activeScope&&p.includes(a.state.activeScope)?a.state.activeScope:p[0]??"public",k=s!=="list",[j,I]=r.useState(v),[S,M]=r.useState(a.state?.programName||""),[y,P]=r.useState(a.state?.programUuid||v?.programUuid||""),[U,F]=r.useState(x),[A,D]=r.useState([]),[R,w]=r.useState(!v),[_,W]=r.useState(!0),[H,ne]=r.useState(N),[K,ye]=r.useState(Cl(t,"public",f,b)),[de,O]=r.useState(""),[L,Z]=r.useState(!1),[ce,me]=r.useState(!1),[Ne,ve]=r.useState(!1),[xe,G]=r.useState(null),[J,ke]=r.useState(""),Be=r.useRef(null),fe=r.useRef(null);r.useEffect(()=>{p.includes(U)||F(p[0]??"public")},[U,p]),r.useEffect(()=>{if(k){if(s==="edit"){const ae=N||u&&A.find(ge=>ge.uuid===u)||null;if(!ae)return;ne(ae),O(""),ye(Tf(ae));return}ne(null),O(""),ye({...Cl(t,x,f,b),sortOrderInput:t==="checkpoint"?Cf(A):""})}},[f,b,s,u,A,t,x,N,k]),r.useEffect(()=>{if(v){I(v),P(a.state?.programUuid||v.programUuid),a.state?.programName&&M(a.state.programName),w(!1);return}const ae=new AbortController;return w(!0),ke(""),Rf(c,ae.signal).then(ge=>{I(ge.item),P(ge.programUuid),M(ge.programName)}
2).catch(ge=>{I(null),ke(re(ge,"Unable to load this curriculum point."))}).finally(()=>{w(!1)}),()=>{ae.abort()}},[v,c,a.state?.programName,a.state?.programUuid]);const Ae=r.useCallback(async(ae,ge,qe)=>{W(!0),ke("");try{const Me=await T.curriculum.listNotes(ae.uuid,{entryType:t,visibilityScope:ge,signal:qe});D(Me)}catch(Me){D([]),ke(re(Me,`Unable to load ${qa(t).toLowerCase()}.`))}finally{W(!1)}},[t]);r.useEffect(()=>{if(!j){D([]),W(!1);return}const ae=new AbortController;return Ae(j,U,ae.signal),()=>{ae.abort()}},[U,j,Ae]);function lt(ae){j&&n.push({pathname:Pf(j.uuid,t,ae?.uuid||null),state:{item:j,programUuid:y,programName:S,activeScope:U,entry:ae}})}function be(){if(!l.current){if(l.current=!0,o){n.replace(o);return}n.replace({pathname:co(c,t),state:{...j?{item:j}:{},programUuid:y,programName:S,activeScope:U}})}}function We(ae,ge){if(ae.length===0)return;const qe=Math.min(Math.max(ge,0),ae.length-1);G({images:ae,index:qe})}function Fe(){G(null)}function Ke(ae){G(ge=>{if(!ge||ge.images.length===0)return ge;const qe=(ge.index+ae+ge.images.length)%ge.images.length;return{...ge,index:qe}})}async function ue(){if(!j)return;const ae=t==="checkpoint"?Number.parseInt(K.sortOrderInput.trim(),10):NaN;if(t==="checkpoint"&&(!Number.isFinite(ae)||ae<1)){O("Checkpoint number must be 1 or higher.");return}const ge=K.referenceLinks.map(Me=>({label:Me.label?.trim()||null,url:Me.url.trim()})).filter(Me=>Me.url!==""),qe={itemUuid:j.uuid,entryType:t,visibility:K.visibility,noteText:K.noteText,mediaUuids:K.attachments.map(Me=>Me.mediaUuid),referenceLinks:ge,sortOrder:t==="checkpoint"?ae:void 0};Z(!0),O("");try{const Me=H?await T.curriculum.updateNote(H.uuid,qe):await T.curriculum.createNote(qe);if(F(Me.visibilityScope),l.current=!0,o){const Ie=new URL(o,window.location.origin);Ie.searchParams.set("scope",Me.visibilityScope),n.replace(Ie.pathname+Ie.search);return}n.replace({pathname:co(j.uuid,t),state:{item:j,programUuid:y,programName:S,activeScope:Me.visibilityScope}})}catch(Me){O(re(Me,`Unable to save this ${t}.`))}finally{Z(!1)}}async function Se(ae){if(!(!ae||ae.length===0)){me(!0),O("");try{const ge=[];for(const qe of Array.from(ae))ge.push(await T.curriculum.uploadNoteAttachment(qe,qe.name));ye(qe=>({...qe,attachments:[...qe.attachments,...ge]}))}catch(ge){O(re(ge,"Unable to upload one or more attachments."))}finally{me(!1)}}}const pe=j?xf(j):"Curriculum point";return e.jsxs(Ye,{standardUI:!0,title:pe,subtitle:`${S||"Curriculum"} · ${qa(t)}`,activeTab:h?"curriculum":"none",backTo:o||`/curriculum?item=${c}`,onRefresh:j?()=>Ae(j,U):void 0,refresherDisabled:L||ce,children:[R?e.jsxs("div",{className:"member-panel-loading",children:[e.jsx(Te,{name:"crescent"}),e.jsx("span",{children:"Loading curriculum point..."})]}):null,!R&&J&&!j?e.jsx("div",{className:"member-panel-error",children:J}):null,!R&&j?e.jsxs(e.Fragment,{children:[e.jsxs(Hn,{value:t,className:"member-tab-switch",onIonChange:ae=>{const ge=`${ae.detail.value??""}`.trim();(ge==="note"||ge==="checkpoint")&&n.replace({pathname:`/curriculum/point/${c}/${ge==="note"?"notes":"checkpoints"}`,state:{item:j,programUuid:y,programName:S}})},children:[e.jsx(Ps,{value:"note",children:e.jsx("span",{children:"Notes"})}),e.jsx(Ps,{value:"checkpoint",children:e.jsx("span",{children:"Checkpoints"})})]}),e.jsx("section",{className:"member-panel-card",children:e.jsx(Hn,{value:U,className:"member-tab-switch",onIonChange:ae=>{const ge=`${ae.detail.value??""}`.trim();p.includes(ge)&&F(ge)},children:p.map(ae=>e.jsx(Ps,{value:ae,children:e.jsx("span",{children:Li(ae)})},ae))})}),J&&j?e.jsx("div",{className:"member-panel-error",children:J}):null,_?e.jsxs("div",{className:"member-panel-loading",children:[e.jsx(Te,{name:"crescent"}),e.jsxs("span",{children:["Loading ",qa(t).toLowerCase(),"..."]})]}):null,!_&&A.length===0?e.jsxs("section",{className:"member-panel-card",children:[e.jsxs("h2",{children:["No ",qa(t).toLowerCase()," yet"]}),e.jsxs("p",{children:[Li(U)," ",qa(t).toLowerCase()," for this point will appear here."]})]}):null,!_&&A.length>0?e.jsx("div",{className:"member-panel-list",children:A.map(ae=>{const ge=ae.entryType==="checkpoint"?"member-curriculum-entry-card is-checkpoint":"member-curriculum-entry-card",qe=Sf(ae),Me=ae.author?.displayName||(ae.visibilityScope==="my"?"You":"Instructor");return e.jsxs("section",{className:`member-panel-card ${ge}`,children:[e.jsxs("div",{className:"member-row-main",children:[e.jsxs("div",{className:"member-curriculum-entry-head",children:[e.jsx(Io,{className:"member-curriculum-scope-chip",children:e.jsx(yt,{children:Li(ae.visibilityScope)})}),e.jsx(Io,{className:"member-curriculum-scope-chip is-outline",children:e.jsx(yt,{children:Me})})]}),ae.canEdit?e.jsxs(vt,{fill:"clear",size:"small",onClick:()=>lt(ae),children:[e.jsx(V,{icon:ai,slot:"start"}),"Edit"]}):null]}),ae.noteText?e.jsx("p",{className:"member-curriculum-entry-text",children:ae.noteText}):null,ae.referenceLinks.length>0?e.jsx("div",{className:"member-list-actions",children:ae.referenceLinks.map((Ie,ie)=>e.jsxs("a",{className:"member-btn is-neutral",href:Ie.url,target:"_blank",rel:"noreferrer",children:[e.jsx(V,{icon:xo}),Ie.label||"Open reference"]},`${ae.uuid}-reference-${ie}`))}):null,ae.attachments.length>0?e.jsx("div",{className:"member-curriculum-entry-media",children:ae.attachments.map(Ie=>{if(typeof Ie.mimeType=="string"&&Ie.mimeType.startsWith("image/")&&(Ie.thumbnailUrl||Ie.url)){const Xe=qe.findIndex(ct=>ct.mediaUuid===Ie.mediaUuid);return e.jsx("button",{type:"button",className:"member-curriculum-entry-image-button",onClick:()=>{We(qe,Xe>=0?Xe:0)},children:e.jsx("img",{className:"member-curriculum-entry-thumbn
2ail",src:Ie.thumbnailUrl||Ie.url||"",alt:Ie.originalFilename||"Attachment"})},Ie.mediaUuid)}return e.jsxs("a",{className:"member-curriculum-file-badge",href:Ie.url||"#",target:"_blank",rel:"noreferrer",children:[e.jsx(V,{icon:fc}),Ie.originalFilename||"Attachment"]},Ie.mediaUuid)})}):null,e.jsx("p",{className:"member-curriculum-entry-timestamp",children:vf(ae,m)})]},ae.uuid)})}):null,_?null:e.jsx("div",{className:"member-curriculum-footer-action",children:e.jsxs("button",{type:"button",className:"member-curriculum-add-btn",onClick:()=>lt(null),children:[e.jsx("span",{children:t==="checkpoint"?"ADD CHECKPOINT":"ADD NOTE"}),e.jsx(V,{icon:Yi})]})}),e.jsx(at,{isOpen:!!xe,onDidDismiss:Fe,className:"member-curriculum-lightbox-modal",children:xe?e.jsxs("div",{className:"member-curriculum-lightbox",children:[e.jsxs("div",{className:"member-curriculum-lightbox-header",children:[e.jsx("span",{children:`${xe.index+1} / ${xe.images.length}`}),e.jsx("button",{type:"button",className:"member-curriculum-lightbox-close",onClick:Fe,children:e.jsx(V,{icon:zn})})]}),e.jsxs("div",{className:"member-curriculum-lightbox-stage",children:[xe.images.length>1?e.jsx("button",{type:"button",className:"member-curriculum-lightbox-nav is-prev",onClick:()=>Ke(-1),children:e.jsx(V,{icon:Hs})}):null,e.jsx("img",{className:"member-curriculum-lightbox-image",src:xe.images[xe.index]?.url||xe.images[xe.index]?.thumbnailUrl||"",alt:xe.images[xe.index]?.originalFilename||"Curriculum attachment"}),xe.images.length>1?e.jsx("button",{type:"button",className:"member-curriculum-lightbox-nav is-next",onClick:()=>Ke(1),children:e.jsx(V,{icon:ei})}):null]}),xe.images.length>1?e.jsx("div",{className:"member-curriculum-lightbox-thumbs",children:xe.images.map((ae,ge)=>e.jsx("button",{type:"button",className:`member-curriculum-lightbox-thumb${ge===xe.index?" is-active":""}`,onClick:()=>We(xe.images,ge),children:e.jsx("img",{src:ae.thumbnailUrl||ae.url||"",alt:ae.originalFilename||`Image ${ge+1}`})},ae.mediaUuid))}):null]}):null}),e.jsx(at,{isOpen:k,onDidDismiss:()=>{O(""),k&&!l.current&&be()},children:e.jsxs("div",{className:"member-modal-sheet",children:[e.jsxs("div",{className:"member-modal-header",children:[e.jsx("h2",{children:H?`Edit ${t}`:`New ${t}`}),e.jsx("p",{children:"Add text, references, and attachments for this curriculum point."})]}),e.jsx(_f,{entryType:t,editingEntry:H,isSaving:L,isUploading:ce,errorMessage:de,availableVisibilities:g,state:K,onCancel:be,onChange:ye,onOpenAttachmentPicker:()=>{ve(!0)},onSave:()=>{ue()}})]})}),e.jsx(ec,{isOpen:Ne,onDidDismiss:()=>ve(!1),buttons:[{text:"Take photo",icon:yo,handler:()=>{Be.current?.click()}},{text:"Choose files",icon:um,handler:()=>{fe.current?.click()}},{text:"Cancel",role:"cancel"}]}),e.jsx("input",{ref:Be,hidden:!0,type:"file",accept:"image/*",capture:"environment",onChange:ae=>{Se(ae.target.files),ae.currentTarget.value=""}}),e.jsx("input",{ref:fe,hidden:!0,type:"file",accept:"image/*,application/pdf",multiple:!0,onChange:ae=>{Se(ae.target.files),ae.currentTarget.value=""}})]}):null]})}function Mf(t,s,n,a){const i=Object.entries(t).map(([l,c])=>({attendee_member_uuid:l,ticket_uuid:c.ticketUuid,session_uuids:On(s.find(u=>u.uuid===c.ticketUuid)??null,c.sessionUuids),approving_instructor_wp_user_id:n?Number(n):void 0})),o=i[0];return o?{attendee_member_uuid:o.attendee_member_uuid,ticket_uuid:o.ticket_uuid,session_uuids:o.session_uuids,approving_instructor_wp_user_id:o.approving_instructor_wp_user_id,registrations:i.length>1?i:void 0,fundraiser_donation_minor:a,terms_accepted:!0}:{}}function Lr(t){return`skullsystem:workshop-hold:${t}:member`}function Uf(t){const s=Lr(t);try{const n=window.sessionStorage.getItem(s),a=n?JSON.parse(n):null,i=a?Sc(a.expires_at,Qi(a.server_time)).expired:!0;return!a?.order_uuid||i?(window.sessionStorage.removeItem(s),null):a}catch{return window.sessionStorage.removeItem(s),null}}function Sl(t,s){return t.attendee_audience==="adults"&&s.attendee_type!=="adult"||t.attendee_audience==="under_18"&&s.attendee_type!=="child"||!s.date_of_birth?!1:_m(s.date_of_birth,Mm(t,s.attendee_type))}function Ef(t,s){return t===0?"You":s.attendee_type==="child"?"Linked child":"Household adult"}function Ur(t,s){return t.member_eligibility?.[s]?t.member_price_minor:t.public_price_minor}function Af({workshop:t,attendees:s,instructors:n,registrations:a,staffReadOnly:i,onCompleted:o}){const l=mt(),c=tt(),[u,d]=r.useState("choose"),[h,m]=r.useState({}),[f,b]=r.useState(""),[p,g]=r.useState("none"),[v,N]=r.useState(""),[x,k]=r.useState(!1),[j,I]=r.useState(!1),[S,M]=r.useState(null),[y,P]=r.useState(null),[U,F]=r.useState(0),[A,D]=r.useState(null),[R,w]=r.useState(!1),[_,W]=r.useState(""),[H,ne]=r.useState(!1),[K,ye]=r.useState(!1),[de,O]=r.useState(null),[L,Z]=r.useState({}),[ce,me]=r.useState(()=>Date.now());Xu(R);const Ne=wa(()=>w(!1)),ve=r.useMemo(()=>t.tickets.filter(q=>q.is_visible&&q.status==="active"),[t.tickets]),xe=r.useMemo(()=>new Set(a.filter(q=>!["cancelled","refunded"].includes(q.status)).map(q=>q.attendee_member_uuid).filter(q=>!!q)),[a]),G=r.useMemo(()=>s.filter(q=>!xe.has(q.member_uuid)&&Sl(t,q)&&ve.length>0),[xe,s,ve.length,t]),J=r.useMemo(()=>Object.entries(h),[h]),ke=r.useMemo(()=>new URLSearchParams(l.search).get("checkout")||"",[l.search]),Be=r.useMemo(()=>
2{if(p==="none")return 0;const q=v.trim();if(!/^(?:\d+|\d*\.\d{1,2})$/.test(q))return-1;const te=Number(q),B=Math.round(te*100);return Number.isSafeInteger(B)&&B>=0?B:-1},[v,p]),fe=r.useMemo(()=>!t.fundraiser||p==="none"?!0:Be>=t.fundraiser.custom_min_minor&&Be<=t.fundraiser.custom_max_minor,[Be,p,t.fundraiser]),Ae=r.useMemo(()=>J.reduce((q,[te,B])=>{const Y=ve.find(oe=>oe.uuid===B.ticketUuid);return q+(Y?Ur(Y,te):0)},0),[J,ve]);r.useEffect(()=>{const q=Uf(t.uuid);q&&(M(q),F(Qi(q.server_time)),d("review"))},[t.uuid]),r.useEffect(()=>{const q=new AbortController;return T.membership.listPaymentMethods({signal:q.signal}).then(te=>{ye(te.some(B=>!!(B.id&&B.isDefault)))}).catch(()=>{ye(!1)}),()=>q.abort()},[t.uuid]),r.useEffect(()=>{const q=window.setInterval(()=>me(Date.now()),3e4);return()=>window.clearInterval(q)},[]),r.useEffect(()=>{if(!S){P(null);return}const q=()=>P(Sc(S.expires_at,U));q();const te=window.setInterval(q,1e3);return()=>window.clearInterval(te)},[S,U]);const lt=r.useCallback(()=>{const q=ve[0];return q?{ticketUuid:q.uuid,sessionUuids:On(q,[])}:null},[ve]);r.useEffect(()=>{if(u!=="choose"||G.length!==1)return;const q=G[0].member_uuid;m(te=>{if(te[q])return te;const B=lt();return B?{[q]:B}:te})},[lt,G,u]);const be=q=>{W(""),m(te=>{if(te[q]){const Y={...te};return delete Y[q],Y}const B=lt();return B?{...te,[q]:B}:te})},We=(q,te)=>{const B=ve.find(Y=>Y.uuid===te);B&&(m(Y=>({...Y,[q]:{ticketUuid:te,sessionUuids:On(B,[])}})),W(""))},Fe=(q,te)=>{const B=h[q],Y=ve.find(_e=>_e.uuid===B?.ticketUuid);if(!B||!Y||["fixed_bundle","all_sessions"].includes(Y.selection_rule))return;const oe=An(Y),Ue=B.sessionUuids.includes(te)?B.sessionUuids.filter(_e=>_e!==te):B.sessionUuids.length>=oe?[...B.sessionUuids.slice(1),te]:[...B.sessionUuids,te];m(_e=>({..._e,[q]:{...B,sessionUuids:Ue}}))},Ke=()=>{if(J.length===0)return"Choose at least one attendee.";if(!fe)return"Enter a donation amount within the allowed range.";if(t.instructor_confirmation_mode==="required"&&!f)return"Choose the instructor who gave permission.";for(const[q,te]of J){const B=s.find(Ue=>Ue.member_uuid===q),Y=ve.find(Ue=>Ue.uuid===te.ticketUuid)??null;if(!B||!Y)return"Choose a ticket for each attendee.";const oe=On(Y,te.sessionUuids);if(Um(t,Y,ce).state!=="open")return`${Y.name} is not currently open for registration.`;if(!Em(Y,oe))return`Choose ${An(Y)} session${An(Y)===1?"":"s"} for ${B.first_name}.`;if(Si(t.sessions,oe))return`${Y.name} is sold out for ${B.first_name}. Use the waitlist option below.`}return x?null:"Accept the event booking terms to continue."},ue=async()=>{const q=Ke();if(q){W(q);return}w(!0),W("");try{const te=await T.commerce.createMemberHold(t.uuid,Mf(h,ve,f,p==="none"?0:Be));M(te),F(Qi(te.server_time)),window.sessionStorage.setItem(Lr(t.uuid),JSON.stringify(te)),d("review")}catch(te){W(te instanceof Error?te.message:"Your places could not be held.")}finally{w(!1)}},Se=r.useCallback(async()=>{if(!S)return;const q=await T.commerce.confirmWorkshopOrder(S.order_uuid,!0);q.payment_status==="succeeded"&&(D(q),d("success"),window.sessionStorage.removeItem(Lr(t.uuid)),await o())},[S,o,t.uuid]),pe=r.useCallback(async()=>{if(S){w(!0),O("restart"),W("");try{if((await T.commerce.releaseWorkshopHold(S.order_uuid,!0)).completed){await Se();return}window.sessionStorage.removeItem(Lr(t.uuid)),M(null),P(null),ne(!1);const te=new URLSearchParams(l.search);te.delete("checkout"),c.replace({pathname:l.pathname,search:te.size>0?`?${te.toString()}`:"",hash:l.hash}),d("choose")}catch(q){W(q instanceof Error?q.message:"Registration could not be restarted.")}finally{w(!1),O(null)}}},[Se,c,S,l.hash,l.pathname,l.search,t.uuid]),ae=async()=>{if(!S||y?.expired){W("Your seat hold has expired. Start again to choose tickets.");return}w(!0),O("saved_card"),W("");try{const q=await T.commerce.createWorkshopPayment(S.order_uuid,"saved_card",!0);if(q.completed){await Se();return}if(q.client_secret){const{loadStripe:te}=await ir(async()=>{const{loadStripe:oe}=await import("./index-B0HAhLET.js");return{loadStripe:oe}},[]),B=await te(q.publishable_key);if(!B)throw new Error("Secure payment could not be loaded.");const Y=await B.confirmCardPayment(q.client_secret);
2if(Y.error)throw new Error(Y.error.message||"Your account could not be charged.");await Se();return}throw new Error("Your account could not be charged. Pay by card instead.")}catch(q){if(q instanceof Error&&/seat hold has expired/i.test(q.message)){await pe();return}W(q instanceof Error?q.message:"Your account could not be charged.")}finally{w(!1),O(null)}},ge=async()=>{if(!S||y?.expired){W("Your seat hold has expired. Start again to choose tickets.");return}w(!0),O("new_card"),W("");try{const q=new URL(window.location.href);q.searchParams.set("checkout","success");const te=new URL(window.location.href);te.searchParams.set("checkout","cancelled");const B=await T.commerce.createWorkshopCheckout(S.order_uuid,q.toString(),te.toString(),!0);if(B.completed){await Se();return}if(!B.checkout_url)throw new Error("Secure Stripe checkout could not be opened.");Ne(B.checkout_url);return}catch(q){if(q instanceof Error&&/seat hold has expired/i.test(q.message)){await pe();return}W(q instanceof Error?q.message:"Payment could not be started.")}finally{w(!1),O(null)}};r.useEffect(()=>{if(!(!S||H||!ke)){if(ne(!0),ke==="cancelled"){d("review"),W("Stripe checkout was cancelled. Your places remain held while the timer is running.");return}ke==="success"&&(w(!0),W(""),Se().catch(q=>{d("review"),W(q instanceof Error?q.message:"Payment confirmation could not be loaded.")}).finally(()=>w(!1)))}},[H,ke,Se,S]);const qe=async q=>{const te=h[q],B=ve.find(Y=>Y.uuid===te?.ticketUuid)??null;if(!(!te||!B)){w(!0),W("");try{await T.commerce.joinMemberWaitlist(t.uuid,{attendee_member_uuid:q,ticket_uuid:B.uuid,session_uuids:On(B,te.sessionUuids)}),Z(Y=>({...Y,[q]:!0}))}catch(Y){W(Y instanceof Error?Y.message:"The waitlist could not be joined.")}finally{w(!1)}}},Me=G.length===1?G[0]:null,Ie=Me?h[Me.member_uuid]:null,ie=ve.find(q=>q.uuid===Ie?.ticketUuid)??null,Xe=On(ie,Ie?.sessionUuids||[]),ct=!!(ie&&!["fixed_bundle","all_sessions"].includes(ie.selection_rule)&&ie.session_uuids.length>1),st=!!(ie&&Si(t.sessions,Xe)),xt=!!(Me&&Ie&&(ve.length>1||ct||st&&(ie?.waitlist_enabled||t.waitlist_enabled))),Et=G.length>1?"Choose each person attending and their ticket. Everyone is included in one payment.":G.length===0?"No eligible people are currently available for this event.":null;return e.jsxs("section",{className:"member-event-registration","aria-labelledby":"member-event-registration-title",children:[e.jsxs("div",{className:"member-event-registration-heading",children:[e.jsxs("div",{children:[e.jsx("h2",{id:"member-event-registration-title",children:u==="review"?"Review and pay":u==="success"?t.thank_you_title||"Registration complete":"Register for this event"}),u==="review"?e.jsx("p",{children:"Your places are held for 8 minutes."}):u==="success"?e.jsx("p",{children:"Your payment and registrations are complete."}):Et?e.jsx("p",{children:Et}):null]}),u==="review"&&y?e.jsx("strong",{className:`member-event-hold-timer is-${y.warning}`,children:y.expired?"Hold expired":`${y.label} left`}):null]}),_?e.jsx("div",{className:"member-panel-error member-event-registration-error",role:"alert",children:_}):null,u==="choose"?e.jsxs(e.Fragment,{children:[G.length!==1?e.jsx("div",{className:"member-event-attendee-list",children:s.map((q,te)=>{const B=!!h[q.member_uuid],Y=xe.has(q.member_uuid),oe=Sl(t,q),Ue=h[q.member_uuid],_e=ve.find(rt=>rt.uuid===Ue?.ticketUuid)??null,He=On(_e,Ue?.sessionUuids||[]),kt=!!(_e&&Si(t.sessions,He));return e.jsxs("article",{className:`member-event-attendee-card${B?" is-selected":""}`,children:[e.jsxs("label",{className:"member-event-attendee-toggle",children:[e.jsx("input",{type:"checkbox",checked:B,disabled:i||Y||!oe||ve.length===0,onChange:()=>be(q.member_uuid)}),e.jsxs("span",{children:[e.jsxs("strong",{children:[q.first_name," ",q.last_name]}),e.jsx("small",{children:Y?"Already registered":oe?Ef(te,q):q.date_of_birth?"Not eligible for this event age group":"Date of birth needed before registration"})]})]}),B&&Ue?e.jsxs("div",{className:"member-event-attendee-options",children:[ve.length>1?e.jsxs("label",{children:[e.jsx("span",{children:"Ticket"}),e.jsx("select",{className:"member-select",value:Ue.ticketUuid,onChange:rt=>We(q.member_uuid,rt.target.value),children:ve.map(rt=>e.jsxs("option",{value:rt.uuid,children:[rt.name," · ",$t(Ur(rt,q.member_uuid),rt.currency)]},rt.uuid))})]}):null,_e&&!["fixed_bundle","all_sessions"].includes(_e.selection_rule)&&_e.session_uuids.length>1?e.jsxs("fieldset",{className:"member-event-session-choices",children:[e.jsxs("legend",{children:["Choose ",An(_e)," session",An(_e)===1?"":"s"]}),t.sessions.filter(rt=>_e.session_uuids.includes(rt.uuid)).map(rt=>e.jsxs("label",{children:[e.jsx("input",{type:"checkbox",checked:He.includes(rt.uuid),disabled:rt.status!=="scheduled"||rt.spots_remaining<1,onChange:()=>Fe(q.member_uuid,rt.uuid)}),e.jsx("span",{children:rt.name})]},rt.uuid))]}):null,_e?e.jsxs("small",{className:"member-event-attendee-price",children:[e.jsx(V,{icon:ha}),_e.member_eligibility?.[q.member_uuid]?"Member price":"Standard price"," ",$t(Ur(_e,q.member_uuid),_e.currency)]}):null,kt&&(_e?.waitlist_enabled||t.waitlist_enabled)?e.jsx("button",{type:"button",className:"member-btn is-neutral",disabled:R||L[q.member_uuid],onClick:()=>{qe(q.member_uuid)},children:L[q.member_uuid]?"Waitlist joined":`Join waitlist for ${q.first_name}`}):null]}):null]},q.member_uuid)})}):null,xt&&Me&&Ie?e.jsxs("div",{className:"member-event-attendee-options member-event-single-attendee-options",children:[ve.length>1?e.jsxs("label",{children:[e.jsx("span",{children:"Ticket"}),e.jsx("select",{className:"member-select",value:Ie.ticketUuid,onChange:q=>We(Me.member_uuid,q.target.value),children:ve.map(q=>e.jsxs("option",{value:q.uuid,children:[q.name," · ",$t(Ur(q,Me.member_uuid),q.currency)]},q.uuid))})]}):null,ct&&ie?e.jsxs("fieldset",{className:"member-event-session-choices",children:[e.jsxs("legend",{children:["Choose ",An(ie)," session",An(ie)===1?"":"s"]}),t.sessions.filter(q=>ie.session_uuids.includes(q.uuid)).map(q=>e.jsxs("label",{children:[e.jsx("input",{type:"checkbox",checked:Xe.includes(q.uuid),disabled:q.status!=="scheduled"||q.spots_remaining<1,onChange:()=>Fe(Me.member_uuid,q.uuid)}),e.jsx("span",{children:q.name})]},q.uuid))]}
2):null,st&&(ie?.waitlist_enabled||t.waitlist_enabled)?e.jsx("button",{type:"button",className:"member-btn is-neutral",disabled:R||L[Me.member_uuid],onClick:()=>{qe(Me.member_uuid)},children:L[Me.member_uuid]?"Waitlist joined":"Join waitlist"}):null]}):null,t.instructor_confirmation_mode!=="off"?e.jsxs("label",{className:"member-event-registration-field",children:[e.jsxs("span",{children:["Instructor who gave permission",t.instructor_confirmation_mode==="required"?" *":""]}),e.jsxs("select",{className:"member-select",value:f,onChange:q=>b(q.target.value),children:[e.jsx("option",{value:"",children:t.instructor_confirmation_mode==="required"?"Choose an instructor":"No instructor selected"}),n.map(q=>e.jsx("option",{value:String(q.wp_user_id),children:q.name},q.wp_user_id))]})]}):null,t.fundraiser?e.jsxs("div",{className:"member-event-order-option",children:[e.jsxs("div",{children:[e.jsxs("strong",{children:["Optional donation to ",t.fundraiser.title]}),e.jsx("p",{children:"Add one donation to this order."})]}),e.jsxs("div",{className:"member-event-donation-buttons",children:[e.jsx("button",{type:"button","aria-pressed":p==="none",className:p==="none"?"is-selected":"",onClick:()=>{g("none"),N("")},children:"No donation"}),t.fundraiser.preset_amounts_minor.map(q=>e.jsx("button",{type:"button","aria-pressed":p==="preset"&&Be===q,className:p==="preset"&&Be===q?"is-selected":"",onClick:()=>{g("preset"),N((q/100).toFixed(2))},children:$t(q,t.fundraiser?.currency||"GBP")},q)),e.jsx("button",{type:"button","aria-pressed":p==="custom",className:p==="custom"?"is-selected":"",onClick:()=>g("custom"),children:"Other amount"})]}),p==="custom"?e.jsxs("label",{className:"member-event-registration-field",children:[e.jsx("span",{children:"Donation amount"}),e.jsx("input",{className:"member-input",inputMode:"decimal",value:v,onChange:q=>N(q.target.value),placeholder:"0.00"})]}):null]}):null,e.jsxs("div",{className:"member-event-order-summary",children:[e.jsxs("span",{children:[J.length," attendee",J.length===1?"":"s"]}),e.jsx("strong",{children:$t(Ae+Math.max(0,Be),ve[0]?.currency||"GBP")})]}),e.jsxs("label",{className:"member-event-terms",children:[e.jsx("input",{type:"checkbox",checked:x,onChange:q=>k(q.target.checked)}),e.jsx("span",{children:"I accept the event booking terms."})]}),t.terms_html?e.jsx("button",{type:"button",className:"member-event-terms-link","aria-haspopup":"dialog",onClick:()=>I(!0),children:"Read booking terms"}):null,e.jsxs("button",{type:"button",className:"member-btn is-solid member-event-register-action",disabled:R||i||J.length===0||!x,onClick:()=>{ue()},children:[R?e.jsx(Te,{name:"crescent"}):null,i?"Member profile required":"Review registration"]})]}):null,u==="review"&&S?e.jsxs("div",{className:"member-event-review",children:[e.jsxs("div",{className:"member-event-review-list",children:[(S.registrations||[]).map(q=>e.jsxs("div",{children:[e.jsx("span",{children:q.attendee_name}),e.jsx("strong",{children:$t(q.amount_minor,S.currency)})]},q.registration_uuid)),S.registrations?.length?null:e.jsxs("div",{children:[e.jsx("span",{children:"Event ticket"}),e.jsx("strong",{children:$t(S.ticket_subtotal_minor,S.currency)})]}),S.fundraiser_donation_minor>0?e.jsxs("div",{children:[e.jsxs("span",{children:["Donation to ",S.fundraiser?.title||"fundraiser"]}),e.jsx("strong",{children:$t(S.fundraiser_donation_minor,S.currency)})]}):null,e.jsxs("div",{className:"is-total",children:[e.jsx("span",{children:"Total"}),e.jsx("strong",{children:$t(S.amount_minor,S.currency)})]})]}),e.jsxs("div",{className:"member-event-review-actions",children:[!y?.expired&&K?e.jsxs("button",{type:"button",className:"member-btn is-solid member-event-detail-primary",disabled:R,onClick:()=>{ae()},children:[de==="saved_card"?e.jsx(Te,{name:"crescent"}):null,"Charge my account"]}):null,y?.expired?null:e.jsxs("button",{type:"button",className:"member-btn is-solid member-event-detail-primary",disabled:R,onClick:()=>{ge()},children:[de==="new_card"?e.jsx(Te,{name:"crescent"}):null,"Pay by Card"]}),e.jsxs("button",{type:"button",className:"member-btn is-neutral",disabled:R,onClick:()=>{pe()},children:[de==="restart"?e.jsx(Te,{name:"crescent"}):null,"Start Again"]})]})]}):null,u==="success"&&A?e.jsxs("div",{className:"member-event-registration-success",children:[e.jsx(V,{icon:si}),t.thank_you_message?e.jsx("div",{dangerouslySetInnerHTML:{__html:t.thank_you_message}}):e.jsx("p",{children:"Your place is confirmed."}),e.jsxs("div",{className:"member-event-review-list",children:[e.jsxs("div",{children:[e.jsx("span",{children:"Reference"}),e.jsx("strong",{children:A.order.display_reference||A.order.uuid})]}),e.jsxs("div",{className:"is-total",children:[e.jsx("span",{children:"Paid"}),e.jsx("strong",{children:$t(A.order.amount_minor,A.order.currency)})]})]}),A.forms_accesses?.map(q=>q.access.token?e.jsxs(tr,{className:"member-btn is-solid",to:`/workshop-forms/${encodeURIComponent(q.access.token)}`,children:["Complete forms for ",q.attendee_name]},q.registration_uuid):null),!A.forms_accesses?.length&&A.forms_access?.token?e.jsx(tr,{className:"member-btn is-solid",to:`/workshop-forms/${encodeURIComponent(A.forms_access.token)}`,children:"Complete attendee forms"}):null]}):null,e.jsx(at,{isOpen:j,onDidDismiss:()=>I(!1),className:"member-event-terms-modal",children:e.jsxs("div",{className:"member-modal-sheet member-event-terms-dialog",children:[e.jsx("div",{className:"member-modal-header",children:e.jsx("h2",{children:"Event booking terms"})}),e.jsx("div",{className:"member-event-terms-html",dangerouslySetInnerHTML:{__html:t.terms_html}}),e.jsx("button",{type:"button",className:"member-btn is-neutral",onClick:()=>I(!1),children:"Close"})]})})]})}function uo(t){return new Date(/[zZ]|[+-]\d\d:\d\d$/.test(t)?t:`${t.replace(" ","T")}Z`)}function _u(t,s){const n=uo(t);return Number.isNaN(n.getTime())?t:new Intl.DateTimeFormat("en-GB",{timeZone:s,weekday:"short",day:"numeric",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit"}).format(n)}function Mu(t){if(!t||typeof window>"u")return null;const s=T.tenant.getTenantHost()||window.location.host;return`${window.location.protocol}//${s}/api/v1/public/media/${encodeURIComponent(t)}`}function Pl(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`fundraiser-cash-${crypto.randomUUID()}`:`fundraiser-cash-${Date.now()}-${Math.random().toString(16).slice(2)}`}function Df(t){return t==="other"?"Event":t.charAt(0).toUpperCase()+t.slice(1)}function Lf(){const{slug:t=""}=Qs(),[s,n]=r.useState(null),[a,i]=r.useState([]),[o,l]=r.useState([]),[c,u]=r.useState([]),[d,h]=r.useState(!1),[m,f]=r.useState(!0),[b,p]=r.useState(""),[g,v]=r.useState(null),[N,x]=r.useState(""),[k,j]=r.useState(!1),I=r.useCallback(async(y=!0)=>{y&&f(!0),p("");try{const P=await T.commerce.getMemberWorkshop(t);n(P.workshop),i(P.attendees||[]),l(P.instructors||[]),u(P.registrations||[]),h(P.staff_read_only===!0)}catch(P){p(re(P,"Unable to load this event."))}finally{y&&f(!1)}},[t]);r.useEffect(()=>{I()},[I]);const S=r.useMemo(()=>[...s?.sessions||[]].filter(y=>y.status==="scheduled").sort((y,P)=>uo(y.start_at).getTime()-uo(P.start_at).getTime()),[s?.sessions]),M=async()=>
2{if(!g)return;const y=g.uuid;j(!0),x("");try{await T.commerce.cancelMemberWorkshopRegistration(y,"Cancelled in member app"),u(P=>P.map(U=>U.uuid===y?{...U,status:"cancelled",can_cancel_online:!1}:U)),v(null),await I(!1)}catch(P){x(re(P,"Registration could not be cancelled."))}finally{j(!1)}};return e.jsxs(Ye,{title:s?.title||"Event details",subtitle:s?Df(s.event_type):void 0,activeTab:"events",backTo:"/events",children:[m?e.jsxs("div",{className:"member-panel-loading",children:[e.jsx(Te,{name:"crescent"}),e.jsx("span",{children:"Loading event..."})]}):null,!m&&b?e.jsx("div",{className:"member-panel-error",children:b}):null,!m&&s?e.jsxs("div",{className:"member-event-detail-layout",children:[e.jsxs("article",{className:"member-event-detail-card",children:[e.jsx(ys,{image:s.image,fallbackUrl:Mu(s.image_media_uuid),className:"member-event-detail-image",eager:!0}),e.jsxs("div",{className:"member-event-detail-content",children:[s.description?e.jsx("div",{className:"member-event-detail-copy",dangerouslySetInnerHTML:{__html:s.description}}):null,e.jsxs("section",{className:"member-event-detail-section",children:[e.jsx("h2",{children:S.length===1?"Date and location":"Sessions"}),e.jsx("div",{className:"member-event-detail-grid",children:S.map(y=>e.jsxs("div",{className:"member-event-detail-item",children:[S.length>1?e.jsx("strong",{children:y.name}):null,e.jsxs("span",{children:[e.jsx(V,{icon:Ut}),_u(y.start_at,s.timezone)]}),y.location?.name?e.jsxs("span",{children:[e.jsx(V,{icon:ni}),y.location.name]}):null,e.jsxs("small",{children:[y.spots_remaining," place",y.spots_remaining===1?"":"s"," remaining"]})]},y.uuid))})]}),s.registration_method==="internal"?e.jsxs("section",{className:"member-event-detail-section",children:[e.jsx("h2",{children:"Tickets"}),e.jsx("div",{className:"member-event-detail-grid",children:s.tickets.filter(y=>y.status==="active"&&y.is_visible).map(y=>e.jsxs("div",{className:"member-event-detail-item",children:[e.jsx("strong",{children:y.name}),y.description?e.jsx("span",{children:y.description}):null,e.jsxs("span",{children:[e.jsx(V,{icon:ha})," Member price"," ",$t(y.member_price_minor,y.currency)]})]},y.uuid))})]}):null,c.length>0?e.jsxs("section",{className:"member-event-detail-section",children:[e.jsx("h2",{children:"Your registrations"}),e.jsx("div",{className:"member-event-detail-grid",children:c.map(y=>e.jsxs("div",{className:"member-event-detail-item",children:[e.jsx("strong",{children:y.attendee_name}),e.jsx("span",{children:y.ticket_name}),e.jsx("small",{children:gt(y.status)}),y.forms_access?.token||y.can_cancel_online?e.jsxs("div",{className:"member-event-registration-actions",children:[y.forms_access?.token?e.jsx(tr,{className:"member-btn is-neutral",to:`/workshop-forms/${encodeURIComponent(y.forms_access.token)}`,children:"Complete forms"}):null,y.can_cancel_online?e.jsx("button",{type:"button",className:"member-btn is-neutral",onClick:()=>{x(""),v(y)},children:"Cancel registration"}):null]}):null]},y.uuid))})]}):null,s.registration_method==="external"?e.jsxs("a",{className:"member-btn is-solid member-event-detail-primary",href:s.external_registration_url||"#",target:"_blank",rel:"noreferrer",children:[s.external_cta_label||"Register on organiser website",e.jsx(V,{icon:ri})]}):null,s.registration_method==="internal"?e.jsx(Af,{workshop:s,attendees:a,instructors:o,registrations:c,staffReadOnly:d,onCompleted:()=>I(!1)}):null]})]}),e.jsx(Pc,{eventTitle:s.title,internalSharePath:`/events/details/${encodeURIComponent(s.slug)}?source=member-events`,sharePath:s.public_visible?`/event/${encodeURIComponent(s.slug)}`:`/event/${encodeURIComponent(s.slug)}?member_access=1`,listPath:"/events",listLabel:"Events",sharingScope:s.public_visible?"public":"members"})]}):null,e.jsx(at,{isOpen:!!g,onDidDismiss:()=>{k||v(null)},className:"member-event-cancellation-modal",children:e.jsxs("div",{className:"member-event-cancellation-dialog",children:[e.jsx("h2",{children:"Cancel registration?"}),e.jsx("p",{children:g?Rc({attendeeName:g.attendee_name,amountMinor:g.amount_minor,refundAvailable:g.cancellation_refund_available}):""}),N?e.jsx("div",{className:"member-panel-error",children:N}):null,e.jsxs("div",{children:[e.jsx("button",{type:"button",className:"member-btn is-neutral",disabled:k,onClick:()=>v(null),children:"Keep registration"}),e.jsxs("button",{type:"button",className:"member-btn is-solid",disabled:k,onClick:()=>{M()},children:[k?e.jsx(Te,{name:"crescent"}):null,"Cancel registration"]})]})]})})]})}function If(){const{slug:t=""}=Qs(),s=mt(),[n,a]=r.useState(null),[i,o]=r.useState(0),[l,c]=r.useState(""),[u,d]=r.useState(!1),[h,m]=r.useState(null),[f,b]=r.useState(!1),[p,g]=r.useState(!0),[v,N]=r.useState(""),[x,k]=r.useState(!1),[j,I]=r.useState(""),[S,M]=r.useState(""),[y,P]=r.useState(""),[U,F]=r.useState(""),[A,D]=r.useState(!1),[R,w]=r.useState(""),_=T.auth.hasRole("owner","admin","instructor"),W=r.useCallback(async()=>{try{const L=await T.commerce.getMemberFundraiser(t);a(L)}catch(L){N(re(L,"Unable to refresh fundraiser totals."))}},[t]),H=wa(()=>{b(!1),W()}),ne=r.useMemo(()=>new URLSearchParams(s.search).get("checkout")==="success",[s.search]),K=n?.uuid||"";r.useEffect(()=>{let L=!0;return g(!0),N(""),T.commerce.getMemberFundraiser(t).then(Z=>{L&&(a(Z),o(Z.preset_amounts_minor[0]||Z.custom_min_minor))}).catch(Z=>{L&&N(re(Z,"Unable to load this fundraiser."))}).finally(()=>{L&&g(!1)}),()=>{L=!1}},[t]),r.useEffect(()=>{if(!K||!ne)return;const L=window.sessionStorage.getItem(`skullsystem:member-fundraiser-donation:${K}`);if(!L){N("The donation reference is missing. Check your email or ask the gym to confirm the payment.");return}b(!0),T.commerce.confirmDonation(L).then(Z=>{if(!Z.completed)throw new Error("Stripe is still confirming this donation. Refresh this page in a moment.");m(Z.donation),window.sessionStorage.removeItem(`skullsystem:member-fundraiser-donation:${K}`),W()}).catch(Z=>N(re(Z,"Donation could not be confirmed."))).finally(()=>b(!1))},[ne,K,W]);const ye=async()=>
2{if(!n)return;const L=u?Math.round(Number(l)*100):i;if(!Number.isFinite(L)||L<n.custom_min_minor||L>n.custom_max_minor){N(`Choose an amount from ${$t(n.custom_min_minor,n.currency)} to ${$t(n.custom_max_minor,n.currency)}.`);return}b(!0),N("");try{const Z=new URL(window.location.href);Z.search="",Z.hash="";const ce=new URL(Z);ce.searchParams.set("checkout","success");const me=new URL(Z);me.searchParams.set("checkout","cancelled");const Ne=await T.commerce.createMemberFundraiserCheckout(n.uuid,{amount_minor:L,success_url:ce.toString(),cancel_url:me.toString()});if(!Ne.checkout_url)throw new Error("Secure checkout could not be opened.");window.sessionStorage.setItem(`skullsystem:member-fundraiser-donation:${n.uuid}`,Ne.donation_uuid),H(Ne.checkout_url)}catch(Z){N(re(Z,"Donation checkout could not be started.")),b(!1)}},de=async()=>{if(!n)return;const L=Number(j);if(!Number.isFinite(L)||L<=0){w("Enter the cash amount collected.");return}D(!0);try{const Z=await T.cash.create({purposeType:"fundraiser",fundraiserUuid:n.uuid,donorName:S.trim()||void 0,amount:L,locationNote:y.trim()||void 0,idempotencyKey:U||Pl()});a(ce=>ce&&ce.uuid===n.uuid?{...ce,raised_minor:ce.raised_minor+Z.amountMinor,donation_count:ce.donation_count+1,cash_raised_minor:ce.cash_raised_minor+Z.amountMinor,cash_donation_count:ce.cash_donation_count+1}:ce),k(!1),I(""),M(""),P(""),F(""),w(`${$t(Math.round(L*100),n.currency)} cash donation logged.`),W()}catch(Z){w(re(Z,"Unable to log this cash donation."))}finally{D(!1)}},O=n?.goal_minor&&n.goal_minor>0?Math.min(100,Math.round(n.raised_minor/n.goal_minor*100)):0;return e.jsxs(Ye,{title:n?.title||"Fundraiser details",subtitle:"Fundraiser",activeTab:"fundraisers",backTo:"/events/fundraisers",children:[p?e.jsxs("div",{className:"member-panel-loading",children:[e.jsx(Te,{name:"crescent"}),e.jsx("span",{children:"Loading fundraiser..."})]}):null,!p&&v?e.jsx("div",{className:"member-panel-error",children:v}):null,!p&&n?e.jsxs(e.Fragment,{children:[e.jsxs("article",{className:"member-event-detail-card",children:[e.jsx(ys,{image:n.image,fallbackUrl:Mu(n.image_media_uuid),className:"member-event-detail-image",eager:!0}),e.jsxs("div",{className:"member-event-detail-content",children:[h?e.jsxs("section",{className:"member-event-donation-success",children:[e.jsx("h2",{children:h.thank_you_title||"Thank you"}),e.jsx("div",{className:"member-event-detail-copy",dangerouslySetInnerHTML:{__html:h.thank_you_message}}),e.jsxs("strong",{children:["Donation ",$t(h.amount_minor,h.currency)]})]}):n.story?e.jsx("div",{className:"member-event-detail-copy",dangerouslySetInnerHTML:{__html:n.story}}):null,n.show_progress&&n.goal_minor?e.jsxs("section",{className:"member-event-detail-fundraising",children:[e.jsxs("div",{children:[e.jsxs("strong",{children:[$t(n.raised_minor,n.currency)," ","raised"]}),e.jsxs("span",{children:["Goal ",$t(n.goal_minor,n.currency)]})]}),e.jsx("div",{className:"member-event-progress-track",children:e.jsx("i",{style:{width:`${O}%`}})}),e.jsxs("small",{children:[n.donation_count," donation",n.donation_count===1?"":"s"]})]}):null,n.ends_at?e.jsxs("div",{className:"member-event-detail-item",children:[e.jsx("strong",{children:"Open for donations"}),e.jsxs("span",{children:[e.jsx(V,{icon:Ut}),"Until ",_u(n.ends_at,rr())]})]}):null,_?e.jsxs("section",{className:"member-event-staff-cash-action",children:[e.jsx("button",{type:"button",className:"member-btn is-neutral",onClick:()=>{F(Pl()),k(!0)},children:"Log cash donation"}),e.jsx("small",{children:"Staff only. This updates the raised total and keeps an audit record."})]}):null,h?null:e.jsxs("section",{className:"member-event-donation-options",children:[e.jsx("h2",{children:"Choose your donation"}),e.jsxs("div",{className:"member-event-donation-choices",children:[n.preset_amounts_minor.map(L=>e.jsx("button",{type:"button",className:!u&&i===L?"is-selected":"","aria-pressed":!u&&i===L,onClick:()=>{d(!1),o(L)},children:$t(L,n.currency)},L)),e.jsx("button",{type:"button",className:`member-event-donation-custom-choice${u?" is-selected":""}`,"aria-pressed":u,onClick:()=>d(!0),children:"Choose amount"})]}),u?e.jsxs("label",{className:"member-event-donation-custom",children:[e.jsxs("span",{children:["Donation amount in ",n.currency]}),e.jsx(Ds,{type:"number",min:n.custom_min_minor/100,max:n.custom_max_minor/100,value:l,onCh
2ange:L=>c(L.target.value)})]}):null,e.jsxs("button",{type:"button",className:"member-btn is-solid member-event-detail-primary",disabled:f,onClick:()=>{ye()},children:[e.jsx(V,{icon:gc}),f?"Opening Stripe...":"Donate securely"]})]})]})]}),e.jsx(Pc,{eventTitle:n.title,sharePath:`/fundraisers/${encodeURIComponent(n.slug)}`,listPath:"/events/fundraisers",listLabel:"Fundraisers",showBackAction:!1}),e.jsx(at,{isOpen:x,onDidDismiss:()=>!A&&k(!1),children:e.jsxs("div",{className:"member-modal-sheet staff-cash-sheet",children:[e.jsxs("div",{className:"member-modal-header",children:[e.jsx("h2",{children:"Log cash donation"}),e.jsx("p",{children:n.title})]}),e.jsxs("label",{className:"member-input-label",children:["Amount collected",e.jsx(Ds,{className:"member-input",type:"number",min:"0.01",step:"0.01",inputMode:"decimal",value:j,onChange:L=>I(L.target.value)})]}),e.jsxs("label",{className:"member-input-label",children:["Donor name",e.jsx("input",{className:"member-input",maxLength:120,value:S,onChange:L=>M(L.target.value),placeholder:"Optional"})]}),e.jsxs("label",{className:"member-input-label",children:["Cash location",e.jsx("input",{className:"member-input",maxLength:255,value:y,onChange:L=>P(L.target.value),placeholder:"For example, office safe"})]}),e.jsxs("div",{className:"member-list-actions staff-cash-actions",children:[e.jsx("button",{type:"button",className:"member-btn is-neutral",onClick:()=>k(!1),disabled:A,children:"Cancel"}),e.jsx("button",{type:"button",className:"member-btn is-solid",onClick:()=>{de()},disabled:A,children:A?e.jsxs(e.Fragment,{children:[e.jsx(Te,{name:"crescent"})," Saving"]}):"Confirm cash donation"})]})]})}),e.jsx(Dt,{isOpen:!!R,message:R,duration:2500,onDidDismiss:()=>w("")})]}):null]})}function mo(t){return new Date(/[zZ]|[+-]\d\d:\d\d$/.test(t)?t:`${t.replace(" ","T")}Z`)}function Ir(t,s,n=!0){const a=mo(t);return Number.isNaN(a.getTime())?t:new Intl.DateTimeFormat("en-GB",{timeZone:s,weekday:"short",day:"numeric",month:"short",year:n?"numeric":void 0,hour:"2-digit",minute:"2-digit"}).format(a)}function Uu(t){const s=`${t??""}`.replace(/<\/(p|div|li|h[1-6])>/gi," ");if(typeof document>"u")return s.replace(/<[^>]+>/g," ").replace(/\s+/g," ").trim();const n=document.createElement("div");return n.innerHTML=s,`${n.textContent??""}`.replace(/\s+/g," ").trim()}function Eu(t){if(!t||typeof window>"u")return null;const s=T.tenant.getTenantHost()||window.location.host;return`${window.location.protocol}//${s}/api/v1/public/media/${encodeURIComponent(t)}`}function $f({workshop:t,onOpen:s}){const n=r.useMemo(()=>[...t.sessions].filter(h=>h.status==="scheduled").sort((h,m)=>mo(h.start_at).getTime()-mo(m.start_at).getTime()),[t.sessions]),a=n[0]??null,i=n[n.length-1]??null,o=Array.from(new Set(n.map(h=>h.location?.name).filter(Boolean))),l=Uu(t.description),c=Eu(t.image_media_uuid),u=t.timezone||rr(),d=a?n.length>1&&i&&i.uuid!==a.uuid?`${n.length} sessions, ${Ir(a.start_at,u,!1)} to ${Ir(i.end_at,u)}`:Ir(a.start_at,u):"Schedule being confirmed";return e.jsxs("button",{type:"button",className:"member-event-card",onClick:s,children:[e.jsx(ys,{image:t.image,fallbackUrl:c,className:"member-event-image"}),e.jsxs("span",{className:"member-event-card-body",children:[e.jsx("span",{className:"member-event-eyebrow",children:t.event_type==="other"?"Event":t.event_type.charAt(0).toUpperCase()+t.event_type.slice(1)}),e.jsx("strong",{children:t.title}),e.jsxs("span",{className:"member-event-meta",children:[e.jsx(V,{icon:Ut}),d]}),o.length>0?e.jsxs("span",{className:"member-event-meta",children:[e.jsx(V,{icon:ni}),o.join(", ")]}):null,l?e.jsx("span",{className:"member-event-summary",children:l}):null,e.jsxs("span",{className:"member-event-cta",children:[t.registration_method==="external"?"View event details":"View tickets and member price"," ",e.jsx(V,{icon:ri})]})]})]})}function Of({fundraiser:t,onOpen:s}){const n=Eu(t.image_media_uuid),a=Uu(t.story),i=t.goal_minor&&t.goal_minor>0?Math.min(100,Math.round(t.raised_minor/t.goal_minor*100)):null;return e.jsxs("button",{type:"button",className:"member-event-card",onClick:s,children:[e.jsx(ys,{image:t.image,fallbackUrl:n,className:"member-event-image member-event-fundraiser-image"}),e.jsxs("span",{className:"member-event-card-body",children:[e.jsxs("span",{className:"member-event-e
2yebrow",children:[e.jsx(V,{icon:gc})," Fundraiser"]}),e.jsx("strong",{children:t.title}),t.ends_at?e.jsxs("span",{className:"member-event-meta",children:[e.jsx(V,{icon:Ut}),"Open until"," ",Ir(t.ends_at,rr())]}):null,a?e.jsx("span",{className:"member-event-summary",children:a}):null,t.show_progress&&t.goal_minor?e.jsxs("span",{className:"member-event-fundraising-progress",children:[e.jsxs("span",{children:[e.jsxs("b",{children:[$t(t.raised_minor,t.currency)," ","raised"]}),e.jsxs("small",{children:["Goal ",$t(t.goal_minor,t.currency)]})]}),e.jsx("span",{className:"member-event-progress-track",children:e.jsx("i",{style:{width:`${i??0}%`}})})]}):null,e.jsxs("span",{className:"member-event-cta",children:["View fundraiser ",e.jsx(V,{icon:ri})]})]})]})}function Ii({kind:t}){const s=tt(),[n,a]=r.useState([]),[i,o]=r.useState([]),[l,c]=r.useState(!0),[u,d]=r.useState(""),[h,m]=r.useState("all"),[f,b]=r.useState(null),[p,g]=r.useState([]),[v,N]=r.useState(null),[x,k]=r.useState(1),j=t==="events",I=n,S=r.useCallback(async()=>{c(!0),d("");try{if(j){const y=await T.commerce.listMemberWorkshops(f,h==="all"?null:h);a(y.rows),N(y.pagination.has_more?y.pagination.next_cursor:null)}else o(await T.commerce.listMemberFundraisers())}catch(y){d(re(y,`Unable to load ${t}.`))}finally{c(!1)}},[f,h,j,t]);r.useEffect(()=>{S()},[S]);const M=j?I.length===0:i.length===0;return e.jsxs(Ye,{title:j?"Events":"Fundraisers",subtitle:j?"Find workshops, seminars, gradings, and other events.":"Support current gym fundraisers.",activeTab:j?"events":"fundraisers",onRefresh:S,children:[l?e.jsxs("div",{className:"member-panel-loading",children:[e.jsx(Te,{name:"crescent"}),e.jsxs("span",{children:["Loading ",t,"..."]})]}):null,!l&&u?e.jsx("div",{className:"member-panel-error",children:u}):null,!l&&!u&&M?e.jsxs("div",{className:"member-panel-empty",children:["No"," ",j?"events match this filter":"fundraisers are open"," ","right now."]}):null,!l&&!u?e.jsxs(e.Fragment,{children:[j?e.jsx("div",{className:"member-event-filters member-timetable-filter-strip","aria-label":"Filter events by type",children:["all","workshop","seminar","grading","other"].map(y=>e.jsx("button",{type:"button",className:`member-timetable-filter-pill${h===y?" is-active":""}`,onClick:()=>{y!==h&&(m(y),b(null),g([]),k(1))},children:y==="all"?"All":y==="other"?"Other":y.charAt(0).toUpperCase()+y.slice(1)},y))}):null,e.jsx("section",{className:"member-events-list","aria-label":j?"Available events":"Open fundraisers",children:j?I.map(y=>e.jsx($f,{workshop:y,onOpen:()=>s.push(`/events/details/${encodeURIComponent(y.slug)}?source=member-events`)},y.uuid)):i.map(y=>e.jsx(Of,{fundraiser:y,onOpen:()=>s.push(`/events/fundraisers/${encodeURIComponent(y.slug)}?source=member-events`)},y.uuid))}),j&&(x>1||v)?e.jsxs("nav",{className:"member-events-pagination","aria-label":"Event pages",children:[e.jsx("button",{type:"button",disabled:x===1,onClick:()=>{const y=p[p.length-1]??null;g(P=>P.slice(0,-1)),b(y),k(P=>Math.max(1,P-1))},children:"Previous"}),e.jsxs("span",{"aria-current":"page",children:["Page ",x]}),e.jsx("button",{type:"button",disabled:!v,onClick:()=>{v&&(g(y=>[...y,f]),b(v),k(y=>y+1))},children:"Next"})]}):null]}):null]})}function ho({isOpen:t,title:s,message:n,confirmLabel:a,busy:i=!1,onCancel:o,onConfirm:l}){return e.jsxs(ui,{isOpen:t,title:s,canDismiss:!i,onClose:o,children:[e.jsx("p",{className:"member-confirm-copy",children:n}),e.jsxs("div",{className:"member-confirm-actions",children:[e.jsx("button",{type:"button",className:"member-btn is-neutral",disabled:i,onClick:o,children:"Cancel"}),e.jsx("button",{type:"button",className:"member-btn is-danger",disabled:i,onClick:l,children:i?"Working...":a})]})]})}function Au({accept:t,label:s,hint:n,accessibleLabel:a,mobileLabel:i,mobileHint:o,onFiles:l,currentName:c,multiple:u=!1,camera:d=!1,cameraLabel:h="Take photo",disabled:m=!1}){const f=r.useRef(null),b=r.useRef(null),[p,g]=r.useState(!1);function v(N){N?.length&&l(N)}return e.jsxs("div",{className:"member-file-picker",children:[e.jsx("input",{ref:f,hidden:!0,type:"file",accept:t,multiple:u,disabled:m,onChange:N=>{v(N.currentTarget.files),N.currentTarget.value=""}}),d?e.jsx("input",{ref:b,hidden:!0,type:"file",accept:"image/*",capture:"environment",disabled:m,onChange:N=>{v(N.currentTarget.files),N.currentTarget.value=""}}):null,e.jsxs("div",{className:`member-file-dropzone${p?" is-dragging":""}${m?" is-disabled":""}`,role:"button",tabIndex:m?-1:0,"aria-label":a||`${s}. ${n}`,onClick:()=>{m||f.current?.click()},onKeyDown:N=>{!m&&(N.key==="Enter"||N.key===" ")&&(N.preventDefault(),f.current?.click())},onDragEnter:N=>{N.preventDefault(),m||g(!0)},onDragOver:N=>{N.preventDefault()},onDragLeave:()=>g(!1),onDrop:N=>{N.preventDefault(),g(!1),m||v(N.dataTransfer.files)},children:[e.jsx("span",{className:"member-file-dropzone-icon","aria-hidden":"true",children:"â"}),e.jsxs("strong",{children:[e.jsx("span",{className:i?"member-file-dropzone-desktop-copy":void 0,children:s}),i?e.jsx("span",{className:"member-file-dropzone-mobile-copy",children:i}):null]}),e.jsx("span",{children:c||e.jsxs(e.Fragment,{children:[e.jsx("span",{className:o?"member-file-dropzone-desktop-copy":void 0,children:n}),o?e.jsx("span",{className:"member-file-dropzone-mobile-copy",children:o}):null]})})]}),d?e.jsx("button",{className:"member-btn member-btn-secondary",type:"button",disabled:m,onClick:()=>b.current?.click(),children:h}):null]})}function Bf({value:t,onChange:s}){const n=r.useRef(null),[a,i]=r.useState({bold:!1,list:!1});r.useEffect(()=>{n.current&&n.current.innerHTML!==t&&(n.current.innerHTML=t)},[t]);const o=r.useCallback(()=>{const u=document.getSelection()?.anchorNode;!n.current||!u||!n.current.contains(u)||i({bold:document.queryCommandState("bold"),list:document.queryCommandState("insertUnorderedList")})},[]);r.useEffect(()=>(document.addEventListener("selectionchange",o),()=>document.removeEventListener("selectionchange",o)),[o]);const l=c=>{n.current?.focus(),document.execCommand(c),n.current&&s(n.current.innerHTML),o()};return e.jsxs("div",{className:"mobile-shop-description-editor",children:[e.jsxs("div",{className:"mobile-shop-description-tools",role:"toolbar","aria-label":"Description formatting",children:[e.jsx("span",{children:"Formatting"}),e.jsxs("button",{type:"button","aria-pressed":a.bold,className:`member-btn ${a.bold?"is-solid":"is-neutral"}`,onMouseDown:c=>c.preventDefault(),onClick:()=>l("bold"),children:[e.jsx("strong",{"aria-hidden":"true",children:"B"}),"Bold"]}),e.jsxs("button",{type:"button","aria-pressed":a.list,className:`member-btn ${a.list?"is-solid":"is-neutral"}`,onMouseDown:c=>c.preventDefault(),onClick:()=>l("insertUnorderedList"),children:[e.jsx("span",{"aria-hidden":"true",children:"â¢"}),"Bulleted list"]})]}),e.jsx("div",{ref:n,className:"mobile-shop-description-input",contentEditable:!0,role:"textbox","aria-label":"Product description","aria-multiline":"true","data-placeholder":"Write the product description members will see",onFocus:o,onKeyUp:o,onMouseUp:o,onInput:c=>{s(c.currentTarget.innerHTML),o()},suppressContentEditableWarning:!0})]})}function Ff({open:t,product:s,config:n,onClose:a,onSaved:i}){const[o,l]=r.useState(""),[c,u]=r.useState(""),[d,h]=r.useState(""),[m,f]=r.useState([]),[b,p]=r.useState([]),[g,v]=r.useState([]),[N,x]=r.useState(null),[k,j]=r.useState(!0),[I,S]=r.useState(""),[M,y]=r.useState(n.locations[0]?.id??0),[P,U]=r.useState(!1),[F,A]=r.useState("");r.useEffect(()=>{t&&(l(s?.title??""),u(s?.description??""),h(s?String(s.base_price_minor/100):""),f(s?.categories??[]),p(s?.images??[]),x(null),v(W=>(W.forEach(H=>URL.revokeObjectURL(H.url)),[])),j(!0),S(""),y(n.locations[0]?.id??0),A(""))},[t,s,n.locations]);const D=W=>{const H=Array.from(W??[]);if(H.length){if(b.length+g.length+H.length>10){A("Use no more than ten images.");return}for(const ne of H)if(ne.size>8*1024*1024||!["image/jpeg","image/png","image/webp"].includes(ne.type)){A("Choose JPEG, PNG or WebP images up to 8 MB each.");return}v(ne=>[...ne,...H.map(K=>({file:K,url:URL.createObjectURL(K)}))]),A("")}},R=async(W,H)=>T.shop.request(`products/${W.uuid}/basic`,{version:W.version,title:o.trim(),description:c,base_price_minor:Math.round(Number(d)*100),categories:m,images:H.map(ne=>ne.uuid)},!0,"PATCH"),w=async()=>{const W=s??N;if(!o.trim()){A("Enter a product title.");return}const H=Math.round(Number(d)*100);if(!Number.isSafeInteger(H)||H<1){A("Enter a price of at least £0.01.");return}if(!W&&!n.profiles.length){A("Complete Shop fulfilment setup in Admin before adding a product.");return}if(!W&&I!==""&&(!k||!n.permissions.shop_adjust_stock)){A("Set stock
2in Admin after sizes or colours are configured.");return}if(!W&&I!==""&&(!Number.isSafeInteger(Number(I))||Number(I)<0)){A("Enter a whole stock count from zero.");return}U(!0),A("");let ne=W;try{if(ne)ne=await R(ne,b),x(ne);else if(ne=await T.shop.request("products/drafts",{title:o.trim(),description:c,base_price_minor:H,categories:m,simple_product:k},!0),x(ne),I!==""){const ye=ne.variants[0];await T.shop.request("inventory",{request_key:crypto.randomUUID(),changes:[{variant_id:ye.id,location_id:M,quantity:Number(I),reason:"stocktake",version:ye.stock.find(de=>de.location_id===M)?.version??1}]},!0),ne=await T.shop.request(`products/${ne.uuid}`,void 0,!0),x(ne)}let K=[...ne.images];for(const ye of g){const de=ye.uploaded??await T.shop.uploadProductImage(ye.file);ye.uploaded||v(O=>O.map(L=>L.url===ye.url?{...L,uploaded:de}:L)),K=[...K,de],ne=await R(ne,K),x(ne),URL.revokeObjectURL(ye.url),v(O=>O.filter(L=>L.url!==ye.url))}i(ne)}catch(K){A(`${ne&&!s?"Draft saved. ":""}${K instanceof Error?K.message:"Product could not be saved."}`),ne&&x(ne)}finally{U(!1)}},_=(W,H)=>{const ne=[...b],[K]=ne.splice(W,1);ne.splice(H,0,K),p(ne)};return e.jsx(at,{isOpen:t,canDismiss:!P,onDidDismiss:a,children:e.jsxs("div",{className:"member-ui member-modal-sheet mobile-shop-editor",children:[e.jsxs("header",{children:[e.jsxs("div",{children:[e.jsx("h2",{children:s||N?"Edit product":"Add product"}),e.jsx("p",{children:s||N?"Update the details members see. Variants and fulfilment stay in Admin.":"Create a draft now, then finish and publish it in Admin."})]}),e.jsxs("button",{className:"member-btn is-neutral",type:"button",onClick:a,disabled:P,children:[e.jsx(V,{icon:Hs,"aria-hidden":"true"})," Back"]})]}),F&&e.jsx("p",{className:"member-shop-error",role:"alert",children:F}),e.jsxs("section",{className:"member-panel-card member-input-group",children:[e.jsxs("label",{className:"member-input-label",children:["Title",e.jsx("input",{className:"member-input",maxLength:191,value:o,onChange:W=>l(W.target.value)})]}),e.jsxs("section",{className:"mobile-shop-field","aria-labelledby":"mobile-shop-description-label",children:[e.jsx("strong",{id:"mobile-shop-description-label",className:"mobile-shop-field-label",children:"Description"}),e.jsx("p",{className:"mobile-shop-help",children:"Add the details members need. Select text, then use the formatting buttons."}),e.jsx(Bf,{value:c,onChange:u})]}),e.jsxs("label",{className:"member-input-label",children:["Base price including tax",e.jsx(Ds,{className:"member-input",type:"number",inputMode:"decimal",min:"0.01",step:"0.01",value:d,onChange:W=>h(W.target.value)})]}),(s??N)?.variants.some(W=>W.price_minor!==null)&&e.jsx("p",{className:"mobile-shop-help",children:"This changes only variants which use the base price. Variant prices stay unchanged."})]}),e.jsxs("fieldset",{className:"member-panel-card",children:[e.jsx("legend",{children:"Categories"}),e.jsx("div",{className:"mobile-shop-checks",children:n.categories.map(W=>e.jsxs("label",{className:`mobile-shop-choice${m.includes(W.id)?" is-selected":""}`,children:[e.jsx("input",{type:"checkbox",checked:m.includes(W.id),onChange:()=>f(H=>H.includes(W.id)?H.filter(ne=>ne!==W.id):[...H,W.id])}),W.name]},W.id))})]}),!s&&!N&&e.jsxs("fieldset",{className:"member-panel-card",children:[e.jsx("legend",{children:"Product type"}),e.jsxs("label",{className:`mobile-shop-choice${k?" is-selected":""}`,children:[e.jsx("input",{type:"radio",checked:k,onChange:()=>j(!0)}),"Simple product with no sizes or colours"]}),e.jsxs("label",{className:`mobile-shop-choice${k?"":" is-selected"}`,children:[e.jsx("input",{type:"radio",checked:!k,onChange:()=>{j(!1),S("")}}),"Product will have sizes or colours"]}),!k&&e.jsx("p",{className:"mobile-shop-help",children:"Set variants and their stock in Admin."})]}),!s&&!N&&k&&n.permissions.shop_adjust_stock&&e.jsxs("div",{className:"member-panel-card mobile-shop-stock-start",children:[e.jsxs("label",{className:"member-input-label",children:["Stock location",e.jsx("select",{className:"member-input member-select",value:M,onChange:W=>y(Number(W.target.value)),children:n.locations.map(W=>e.jsx("option",{value:W.id,children:W.name},W.id))})]}),e.jsxs("label",{className:"member-input-label",children:["Exact stock count, optional",e.jsx(Ds,{className:"member-input",type:"number",inputMode:"numeric",min:"0",value:I,onChange:W=>S(W.target.value)})]})]}),e.jsxs("section",{className:"member-panel-card",children:[e.jsx("h3",{children:"Photos"}),e.jsx("p",{className:"mobile-shop-help",children:"Up to ten JPEG, PNG or WebP images. The first image is the cover."}),e.jsx("div",{className:"mobile-shop-photo-picker",children:e.jsx(Au,{accept:"image/jpeg,image/png,image/webp",label:"Drop product photos here or choose photos",hint:"JPEG, PNG or WebP, up to ten images",accessibleLabel:"Cho
2ose product photos from your device",mobileLabel:"Choose photos from your phone",mobileHint:"Open your photo library, or take a new photo below",multiple:!0,camera:!0,cameraLabel:"Take a photo",disabled:P||b.length+g.length>=10,onFiles:D})}),e.jsxs("div",{className:"mobile-shop-gallery-edit",children:[b.map((W,H)=>e.jsxs("div",{children:[e.jsx(ys,{image:W.image,fallbackUrl:W.url,alt:`${o||"Product"} ${H+1}`,sizes:"96px",width:96,height:96}),e.jsx("span",{children:H===0?"Cover":`Photo ${H+1}`}),e.jsxs("div",{children:[e.jsx("button",{className:"member-btn is-neutral",type:"button",disabled:P||H===0,onClick:()=>_(H,H-1),children:"Earlier"}),e.jsx("button",{className:"member-btn is-neutral",type:"button",disabled:P||H===b.length-1,onClick:()=>_(H,H+1),children:"Later"}),e.jsx("button",{className:"member-btn is-neutral",type:"button",disabled:P,onClick:()=>p(ne=>ne.filter(K=>K.uuid!==W.uuid)),children:"Remove"})]})]},W.uuid)),g.map((W,H)=>e.jsxs("div",{children:[e.jsx("img",{src:W.url,alt:`New product photo ${H+1}`}),e.jsx("span",{children:"Uploads when saved"}),e.jsx("button",{className:"member-btn is-neutral",type:"button",disabled:P,onClick:()=>{URL.revokeObjectURL(W.url),v(ne=>ne.filter(K=>K.url!==W.url))},children:"Remove"})]},W.url))]})]}),e.jsxs("footer",{children:[e.jsx("button",{className:"member-btn is-neutral",type:"button",onClick:a,disabled:P,children:"Cancel"}),e.jsx("button",{type:"button",className:"member-btn is-solid",onClick:()=>{w()},disabled:P,children:P?"Savingâ¦":s||N?"Save changes":"Create draft"})]})]})})}function Wf({product:t,config:s,open:n,onClose:a,onSaved:i}){const[o,l]=r.useState(s.locations[0]?.id??0),[c,u]=r.useState("stocktake"),[d,h]=r.useState({}),[m,f]=r.useState(!1),[b,p]=r.useState(""),g=t.variants.filter(x=>x.stock_policy!=="made_to_order"),v=c==="stocktake"||c==="correction",N=async()=>{const x=g.flatMap(k=>{const j=d[k.id];if(j===void 0||j==="")return[];const I=k.stock.find(S=>S.location_id===o);return[{variant_id:k.id,location_id:o,quantity:Number(j),reason:c,version:I?.version??1}]});if(!x.length){p(v?"Enter at least one exact stock count.":"Enter at least one stock quantity.");return}if(x.some(k=>!Number.isSafeInteger(k.quantity)||k.quantity<0)){p("Enter whole stock quantities from zero.");return}f(!0),p("");try{await T.shop.request("inventory",{request_key:crypto.randomUUID(),changes:x},!0);const k=await T.shop.request(`products/${t.uuid}`,void 0,!0);i(k)}catch(k){p(k instanceof Error?k.message:"Stock could not be updated.")}finally{f(!1)}};return e.jsx(at,{isOpen:n,canDismiss:!m,onDidDismiss:a,children:e.jsxs("div",{className:"member-ui member-modal-sheet mobile-shop-editor",children:[e.jsxs("header",{children:[e.jsxs("div",{children:[e.jsx("h2",{children:"Update stock"}),e.jsx("p",{children:t.title})]}),e.jsxs("button",{className:"member-btn is-neutral",type:"button",onClick:a,disabled:m,children:[e.jsx(V,{icon:Hs,"aria-hidden":"true"})," Back"]})]}),b&&e.jsx("p",{className:"member-shop-error",role:"alert",children:b}),e.jsxs("label",{className:"member-input-label",children:["Gym",e.jsx("select",{className:"member-input member-select",value:o,onChange:x=>{l(Number(x.target.value)),h({})},children:s.locations.map(x=>e.jsx("option",{value:x.id,children:x.name},x.id))})]}),e.jsxs("label",{className:"member-input-label",children:["Reason",e.jsx("select",{className:"member-input member-select",value:c,onChange:x=>u(x.target.value),children:["stocktake","added","removed","damaged","returned","correction"].map(x=>e.jsx("option",{value:x,children:x==="stocktake"?"Set exact count":x},x))})]}),g.map(x=>{const k=x.stock.find(j=>j.location_id===o);return e.jsxs("div",{className:"member-shop-review",children:[e.jsx("strong",{children:ua(x.options)}),e.jsxs("span",{children:["On hand ",k?.on_hand??0,", reserved ",k?.reserved??0,", available ",k?.available??0]}),e.jsxs("label",{className:"member-input-label",children:[v?"New exact count":c==="added"||c==="returned"?"Quantity to add":"Quantity to remove",e.jsx(Ds,{className:"member-input",type:"number",inputMode:"numeric",min:"0",value:d[x.id]??"",onChange:j=>h(I=>({...I,[x.id]:j.target.value}))})]})]},x.id)}),e.jsxs("footer",{children:[e.jsx("button",{className:"member-btn is-neutral",type:"button",onClick:a,disabled:m,children:"Cancel"}),e.jsx("button",{type:"button",className:"member-btn is-solid",onClick:()=>{N()},disabled:m,children:m?"Savingâ¦":"Save stock"})]})]})})}function qf(t,s,n=window.open.bind(window)){const a=n(t,"_blank");return a?(a.opener=null,"new_window"):(s(t),"fallback")}function Hf(t,s){return`skull-shop-basket:v1:${t}:${s}`}function Rl(t,s){try{const n=JSON.parse(t.getItem(s)??"[]");if(!Array.isArray(n))return[];const a=new Set;return n.filter(i=>!i||typeof i.variant_uuid!="string"||!/^[0-9a-f-]{36}$/i.test(i.variant_uuid)||!Number.isInteger(i.quantity)||i.quantity<1||i.quantity>100||a.has(i.variant_uuid)?!1:(a.add(i.variant_uuid),!0)).slice(0,50).map(i=>({variant_uuid:i.variant_uuid,quantity:i.quantity,label:typeof i.label=="string"?i.label.slice(0,240):"Shop item"}))}catch{return[]}}function Vf(t,s){if(t.find(a=>a.variant_uuid===s.variant_uuid))return t.map(a=>a.variant_uuid===s.variant_uuid?{...a,quantity:Math.min(100,a.quantity+s.quantity)}:a);if(t.length>=50)throw new Error("A basket can contain up to 50 different items.");return[...t,s]}function In({staff:t=!1,basePath:s}){const{user:n}=Ge(),a=tt(),i=mt(),o=t?"/staff-tools/shop":s??sr,l=i.pathname.slice(o.length).split("/").filter(
2Boolean),c=l[0]??(t?"orders":"catalogue"),u=l[1],[d,h]=r.useState(null),[m,f]=r.useState([]),[b,p]=r.useState(null),[g,v]=r.useState({}),[N,x]=r.useState(0),[k,j]=r.useState(1),[I,S]=r.useState([]),[M,y]=r.useState(null),[P,U]=r.useState([]),[F,A]=r.useState({}),[D,R]=r.useState("stocktake"),[w,_]=r.useState(null),[W,H]=r.useState(""),[ne,K]=r.useState(""),[ye,de]=r.useState(""),[O,L]=r.useState("action"),[Z,ce]=r.useState(null),[me,Ne]=r.useState(null),[ve,xe]=r.useState(""),[G,J]=r.useState(""),[ke,Be]=r.useState(!1),[fe,Ae]=r.useState(!0),[lt,be]=r.useState(!1),We=Hf(n?.tenantUuid??T.tenant.getTenantHost()??"",n?.wpUserId??0)+(t?":counter":""),[Fe,Ke]=r.useState(()=>Rl(localStorage,We)),[ue,Se]=r.useState({items:[],fulfilment_method:"pickup",payment_method:t?"cash":"card",address:{line1:"",line2:"",city:"",postal_code:"",country:"GB"}}),[pe,ae]=r.useState(null),[ge,qe]=r.useState(null),Me=r.useRef(null),[Ie,ie]=r.useState(""),[Xe,ct]=r.useState(""),[st,xt]=r.useState(""),[Et,q]=r.useState(""),[te,B]=r.useState([]),[Y,oe]=r.useState(""),[Ue,_e]=r.useState(""),[He,kt]=r.useState("active"),[rt,Lt]=r.useState(void 0),[Ft,Pt]=r.useState(null),[Rs,es]=r.useState(0),[ht,vs]=r.useState(0),jt=!!d&&!t&&(n?.role==="owner"||n?.staffCapabilities?.shop_edit_products===!0||!!d?.permissions.shop_edit_products);r.useEffect(()=>{if(qe(null),c!=="basket"||!Fe.length||!d?.schema_ready||!t&&!d.can_checkout)return;let $=!0;return T.shop.request(t?"counter/options":"options",{items:Fe.map(({variant_uuid:le,quantity:Ve})=>({variant_uuid:le,quantity:Ve}))},t).then(le=>{$&&(qe(le),Se(Ve=>{const ot=le.pickup_location_ids.includes(Ve.pickup_location_id??0)?Ve.pickup_location_id:le.pickup_location_ids[0],_t=t||Ve.fulfilment_method==="pickup"&&ot||!le.shipping_enabled?"pickup":"shipping";return{...Ve,pickup_location_id:ot,fulfilment_method:_t,payment_method:!t&&Ve.payment_method==="cash"&&(!ot||!le.cash_location_ids.includes(ot))?"card":Ve.payment_method}}))}).catch(le=>{$&&xe(le.message)}),()=>{$=!1}},[Fe,c,t,d?.schema_ready,d?.can_checkout]),r.useEffect(()=>{Ke(Rl(localStorage,We)),ae(null),Me.current=null},[We]);const Kt=$=>{Ke($),ae(null),Me.current=null;try{localStorage.setItem(We,JSON.stringify($))}catch{xe("Your basket cannot be saved on this device. Keep this page open.")}},Rt=$=>{Se(le=>({...le,...$})),ae(null),Me.current=null},Wt=r.useCallback(async()=>{if(!u)throw new Error("Order was not found.");const $=await T.shop.request(`orders/${u}`,void 0,t);if(t||$.status==="cancelled"||$.payment_method==="cash"||!["pending","failed"].includes($.payment_status))return $;try{return await T.shop.request(`orders/${u}/reconcile`,{})}catch{return $}},[u,t]),Yt=r.useCallback(async()=>{u&&c==="orders"&&y(await Wt())},[u,c,Wt]);r.useEffect(()=>{if(!u||c!=="orders")return;const $=()=>{Yt().catch(()=>{})};return window.addEventListener("focus",$),()=>window.removeEventListener("focus",$)},[u,c,Yt]);const Ts=wa(()=>{Be(!1),Yt()});r.useEffect(()=>{let $=!0;return Ae(!0),xe(""),h(null),p(null),y(null),ae(null),ce(null),f([]),S([]),T.shop.request("config",void 0,t).then(le=>{if($){if(!le)throw new Error("The Shop could not be loaded. Check your connection and try again.");h(le),_(Ve=>Ve??le.stock_locations?.find(ot=>ot.active)?.id??le.locations[0]?.id??null),Se(Ve=>({...Ve,pickup_location_id:Ve.pickup_location_id??le.locations[0]?.id}))}}).catch(le=>{$&&xe(le.message)}).finally(()=>{$&&Ae(!1)}),()=>{$=!1}},[ht,t,i.pathname,n?.wpUserId,n?.tenantUuid]),r.useEffect(()=>{if(!d?.schema_ready)return;let $=!0;Ae(!0),xe("");const le=new URLSearchParams;return Z&&le.set("cursor",String(Z)),W&&le.set("category_id",W),ye&&le.set("search",ye),jt&&(c==="catalogue"||c==="products")&&le.set("status",He),t&&c==="orders"&&O==="action"&&le.set("needs_action","1"),(async()=>{if(c==="products"&&u){const ot=await T.shop.request(`products/${u}`,void 0,t||jt);$&&(p(ot),v(ot.variants[0]?.options??{}),x(0),j(1))}else if(c==="catalogue"||c==="counter"){const ot=await T.shop.request(`products?${le}`,void 0,t||jt);$&&(f(_t=>Z?[..._t,...ot.rows]:ot.rows),Ne(ot.next_cursor))}else if(c==="orders"&&u){const ot=await Wt();$&&y(ot)}else if(c==="orders"){const ot=await T.shop.request(`orders?${le}`,void 0,t);$&&(S(_t=>Z?[..._t,...ot.rows]:ot.rows),Ne(ot.next_cursor))}else if(c==="inventory"&&w){le.set("location_id",String(w));const ot=await T.shop.request(`inventory?${le}`,void 0,!0);$&&(U(_t=>Z?[..._t,...ot.rows]:ot.rows),Ne(ot.next_cursor))}})().catch(ot=>{$&&xe(ot.message)}).finally(()=>{$&&Ae(!1)}),()=>{$=!1}},[d?.schema_ready,c,u,t,Z,W,ye,He,jt,Rs,O,ue.pickup_location_id,w,Wt]),r.useEffect(()=>{if(!M||!["pending","failed"].includes(M.payment_status)||M.payment_method==="cash")return;const $=window.setInterval(()=>{Yt().catch(()=>{})},5e3);return()=>window.clearInterval($)},[M?.uuid,M?.payment_status,M?.payment_method,Yt]);const At=async $=>{Be(!0),xe(""),J("");try{await $()}catch(le){xe(le.message)}finally{Be(!1)}},is=$=>At(async()=>{const le=await T.shop.request(`products/${$}`,void 0,!0);Lt(le)}),ts=()=>({...ue,items:Fe.map(({variant_uuid:$,quantity:le})=>({variant_uuid:$,quantity:le})),...t?{payment_method:"cash",counter_sale:!0,customer_name:Ie,customer_email:Xe,member_uuid:st}:{}});async function os($){const le=await T.shop.request(`orders/${$.uuid}/payment`,{return_url:new URL(`${o}/orders/${$.uuid}`,window.location.origin).toString()});if(le.url){qf(le.url,Ts);return}if(!le.publishable_key||!le.client_secret)throw new Error("Payment setup is incomplete. Your order is still reserved.");const{loadStripe:Ve}=await ir(async()=>{const{loadStripe:Ns}=await import("./index-B0HAhLET.js");return{loadStripe:Ns}},[]),ot=await Ve(le.publishable_key,le.account_id?{stripeAccount:le.account_id}:void 0);if(!ot)throw new Error("Card payments could not be loaded.");const _t=await ot.confirmCardPayment(le.client_secret);
2if(_t.error)throw new Error(_t.error.message||"Card payment was not completed.");J("Payment submitted. Waiting for Stripe confirmation."),await Yt()}async function Zs(){if(!pe)return;const $={...ts(),quote_hash:pe.quote_hash},le=JSON.stringify($);Me.current?.hash!==le&&(Me.current={hash:le,key:crypto.randomUUID()});const Ve=await T.shop.request(t?"counter":"orders",{...$,request_key:Me.current.key},t);Kt([]),y(Ve),t&&!d?.permissions.shop_view_orders?J(`Cash sale ${Ve.id} recorded. ${Ve.status==="completed"?"Items marked collected.":"Paid order awaiting fulfilment."}`):a.push(`${o}/orders/${Ve.uuid}`),!t&&Ve.payment_method!=="cash"&&Ve.payment_status==="pending"&&await os(Ve)}const bt=b?.variants.find($=>Zo($.options)===Zo(g)),hs=bt?.stock?.reduce(($,le)=>$+le.available,0)??0,Js=!!bt&&b?.status==="active"&&!!bt.active&&!bt.archived&&(b?.sales_mode==="preorder_campaign"?b.preorder_open!==!1&&(bt.preorder_limit==null||(bt.preorder_available??0)>0):bt.stock_policy==="made_to_order"||hs>0||bt.stock_policy==="allow_preorder"&&(bt.preorder_available??0)>0),ps=b?.sales_mode==="preorder_campaign"?b.preorder_open===!1?"Preorders closed":bt?.preorder_limit!=null?`${bt.preorder_available??0} preorders remaining`:"Available to preorder":bt?.stock_policy==="made_to_order"?"Made to order":hs>0?hs<=(bt?.low_stock_threshold??d?.low_stock_threshold??3)?`Low stock: ${hs} available`:"In stock":bt?.stock_policy==="allow_preorder"&&(bt.preorder_available??0)>0?"Available to preorder":"Out of stock",Qt=bt?.image_uuid?b?.images.find($=>$.uuid===bt.image_uuid):void 0,ls=($,le)=>{v({...g,[$]:le}),x(-1)},qt=t?!!d&&(c==="orders"?d.permissions.shop_view_orders:c==="inventory"?d.permissions.shop_adjust_stock:d.permissions.shop_log_sales):!0;return e.jsxs(Ye,{standardUI:!0,title:t?"Shop staff tools":"Shop",subtitle:t?"Orders, stock and cash sales.":"School clothing and equipment.",activeTab:"none",children:[e.jsxs("div",{className:"member-shop",children:[d&&e.jsxs("nav",{"aria-label":"Shop navigation",className:"member-shop-nav",children:[t?e.jsxs(e.Fragment,{children:[d?.permissions.shop_view_orders&&e.jsx("button",{className:c==="orders"?"is-active":"",onClick:()=>a.push(`${o}/orders`),children:"Orders"}),d?.permissions.shop_adjust_stock&&e.jsx("button",{className:c==="inventory"?"is-active":"",onClick:()=>a.push(`${o}/inventory`),children:"Stock"}),d?.permissions.shop_log_sales&&e.jsx("button",{className:c==="counter"?"is-active":"",onClick:()=>a.push(`${o}/counter`),children:"Cash sale"})]}):e.jsxs(e.Fragment,{children:[e.jsx("button",{className:c==="catalogue"||c==="products"?"is-active":"",onClick:()=>a.push(o),children:"Browse"}),e.jsx("button",{className:c==="orders"?"is-active":"",onClick:()=>a.push(`${o}/orders`),children:"My orders"})]}),e.jsxs("button",{className:c==="basket"?"is-active":"",onClick:()=>a.push(`${o}/basket`),children:["Basket (",Fe.reduce(($,le)=>$+le.quantity,0),")"]})]}),!d&&fe&&e.jsxs("section",{className:"member-panel-card member-shop-state",role:"status",children:[e.jsx("h2",{children:"Loading Shop"}),e.jsx("p",{children:"Getting products, categories and stock."})]}),!d&&!fe&&ve&&e.jsxs("section",{className:"member-panel-card member-shop-state is-error",role:"alert",children:[e.jsx("h2",{children:"Shop unavailable"}),e.jsx("p",{children:ve}),e.jsx("button",{className:"member-btn is-solid",type:"button",onClick:()=>vs($=>$+1),children:"Try again"})]}),d&&ve&&e.jsx("p",{role:"alert",className:"member-shop-error",children:ve}),G&&e.jsx("p",{role:"status",children:G}),d&&fe&&e.jsx("p",{className:"member-shop-loading",role:"status",children:"Updating Shopâ¦"}),!qt&&d&&e.jsx("p",{children:"This account does not have permission for this shop tool."}),d&&!d.member_visible&&!t&&!jt&&c!=="orders"&&e.jsx("p",{children:"The shop is currently closed. Your existing orders remain available."}),qt&&(t||jt||d?.member_visible||c==="orders")&&e.jsxs(e.Fragment,{children:[(c==="catalogue"||c==="counter")&&e.jsxs(e.Fragment,{children:[e.jsxs("form",{className:"member-section member-shop-filters",onSubmit:$=>{$.preventDefault(),ce(null),de(ne)},children:[e.jsxs("div",{className:"member-shop-filters-heading",children:[e.jsxs("div",{children:[e.jsx("h2",{children:t?"Counter products":"Products"}),e.jsx("p",{children:"Search and filter the Shop catalogue."})]}),jt&&c==="catalogue"&&e.jsx("button",{type:"button",className:"member-btn is-solid mobile-shop-add",onClick:()=>Lt(null),children:"Add product"})]}),e.jsxs("div",{className:"member-shop-search-row",children:[e.jsxs("label",{className:"member-input-label",children:["Search",e.jsx(on,{ariaLabel:"Search products",value:ne,onChange:K,placeholder:"Product title"})]}),e.jsx("button",{className:"member-btn is-neutral",type:"submit",children:"Search"})]}),e.jsxs("div",{className:"member-shop-filter-grid",children:[e.jsxs("label",{className:"member-input-label",children:["Category",e.jsxs("select",{className:"member-input member-select",value:W,onChange:$=>{ce(null),H($.target.value)},children:[e.jsx("option",{value:"",children:"All categories"}),d?.categories.map($=>e.jsx("option",{value:$.id,children:$.name},$.id))]})]}),jt&&c==="catalogue"&&e.jsxs("label",{className:"member-input-label",children:["Product status",e.jsxs("select",{className:"member-input member-select",value:He,onCh
2ange:$=>{ce(null),kt($.target.value)},children:[e.jsx("option",{value:"active",children:"Live"}),e.jsx("option",{value:"draft",children:"Draft and offline"})]})]})]})]}),e.jsx("div",{className:"member-shop-products",children:m.filter($=>!t||$.status==="active").map($=>e.jsxs("article",{className:"member-panel-card member-shop-product",children:[e.jsxs("button",{type:"button",className:"mobile-shop-product-open",onClick:()=>a.push(`${o}/products/${$.uuid}`),children:[$.image_url?e.jsx(ys,{image:$.image,fallbackUrl:$.image_url,alt:$.title,sizes:"(max-width: 640px) 50vw, 280px",width:320,height:320}):null,e.jsx("strong",{children:$.title}),e.jsxs("span",{children:["From ",us($.base_price_minor,d?.currency)]}),$.sales_mode==="preorder_campaign"&&e.jsx("span",{className:"mobile-shop-status",children:$.preorder_open===!1?"Preorders closed":"Preorder"}),jt&&e.jsx("span",{className:"mobile-shop-status",children:$.status==="active"?"Live":gt($.status)})]}),jt&&e.jsx("button",{className:"member-btn is-neutral",type:"button",onClick:()=>{is($.uuid)},children:"Edit product"})]},$.uuid))}),!fe&&!m.length&&e.jsx("p",{children:"No products found."})]}),c==="products"&&b&&e.jsxs("section",{className:"member-panel-card member-shop-detail",children:[(N<0?Qt??b.images[0]:b.images[N])?.url&&e.jsx(ys,{className:"member-shop-cover",image:(N<0?Qt??b.images[0]:b.images[N]).image,fallbackUrl:(N<0?Qt??b.images[0]:b.images[N]).url,alt:b.title,sizes:"(max-width: 640px) 100vw, 720px",width:1280,height:1280,eager:!0}),e.jsx("div",{className:"member-shop-thumbnails",children:b.images.map(($,le)=>e.jsx("button",{className:"member-btn is-neutral","aria-label":`View image ${le
2+1}`,"aria-pressed":N===le,onClick:()=>x(le),children:e.jsx(ys,{image:$.image,fallbackUrl:$.url,alt:`${b.title} ${le+1}`,sizes:"96px",width:96,height:96})},$.uuid))}),e.jsx("h2",{children:b.title}),jt&&e.jsxs("div",{className:"member-shop-actions mobile-shop-manager-actions",children:[e.jsx("span",{className:"mobile-shop-status",children:b.status==="active"?"Live":gt(b.status)}),e.jsx("button",{className:"member-btn is-neutral",type:"button",onClick:()=>Lt(b),children:"Edit product"}),d?.permissions.shop_adjust_stock&&b.sales_mode!=="preorder_campaign"&&e.jsx("button",{className:"member-btn is-neutral",type:"button",onClick:()=>Pt(b),children:"Update stock"}),b.status==="active"&&e.jsx("button",{type:"button",className:"member-btn is-danger",disabled:ke,onClick:()=>be(!0),children:"Take offline"})]}),e.jsx(ho,{isOpen:lt,title:"Take product offline?",message:"Members will no longer see this product. Existing orders and stock will stay unchanged.",confirmLabel:"Take offline",busy:ke,onCancel:()=>be(!1),onConfirm:()=>{b&&At(async()=>{const $=await T.shop.request(`products/${b.uuid}/offline`,{version:b.version},!0);p($),be(!1),J("Product taken offline. Existing orders and stock were not changed."),es(le=>le+1)})}}),e.jsx("div",{className:"member-shop-description",dangerouslySetInnerHTML:{__html:b.description}}),b.options.map($=>e.jsxs("label",{className:"member-input-label",children:[$.name,e.jsx("select",{className:"member-input member-select",value:g[$.name]??"",onChange:le=>ls($.name,le.target.value),children:$.values.map(le=>e.jsx("option",{value:le,children:le},le))})]},$.name)),e.jsx("strong",{children:bt?us(bt.effective_price_minor,d?.currency):"This combination is not available."}),e.jsx("p",{children:ps}),b.sales_mode==="preorder_campaign"&&b.preorder_closes_at&&e.jsxs("p",{children:["Order by ",new Date(b.preorder_closes_at.includes("T")?b.preorder_closes_at:`${b.preorder_closes_at.replace(" ","T")}Z`).toLocaleString("en-GB")]}),e.jsx("p",{children:bt?.availability_message}),jt&&e.jsxs("section",{className:"mobile-shop-stock-summary","aria-label":"Stock summary",children:[e.jsx("h3",{children:"Stock"}),b.variants.map($=>e.jsxs("div",{children:[e.jsx("strong",{children:ua($.options)}),b.sales_mode==="preorder_campaign"?e.jsx("span",{children:"No physical stock required for preorders"}):$.stock_policy==="made_to_order"?e.jsx("span",{children:"Made to order"}):$.stock.length?$.stock.map(le=>e.jsxs("span",{children:[d?.stock_locations?.find(Ve=>Ve.id===le.location_id)?.name??"Gym",": ",le.on_hand," on hand, ",le.reserved," reserved, ",le.available," available"]},le.location_id)):e.jsx("span",{children:"No stock recorded"})]},$.id))]}),e.jsxs("label",{className:"member-input-label",children:["Quantity",e.jsx(Ds,{className:"member-input",type:"number",min:"1",max:"100",value:k,onChange:$=>j(Number($.target.value))})]}),e.jsx("button",{className:"member-btn is-solid",disabled:!Js||!Number.isInteger(k)||k<1||k>100,onClick:()=>{if(bt)try{Kt(Vf(Fe,{variant_uuid:bt.uuid,quantity:k,label:`${b.title} · ${ua(bt.options)}`})),J("Added to basket.")}catch($){xe($.message)}},children:"Add to basket"})]}),c==="basket"&&e.jsxs("section",{className:"member-panel-card member-shop-detail",children:[e.jsx("h2",{children:t?"Counter sale":"Basket"}),Fe.map($=>e.jsxs("div",{className:"member-shop-basket-row",children:[e.jsx("strong",{children:$.label}),e.jsxs("label",{className:"member-input-label",children:["Quantity",e.jsx(Ds,{className:"member-input",type:"number",min:"1",max:"100",value:$.quantity,onChange:le=>Kt(Fe.map(Ve=>Ve.variant_uuid===$.variant_uuid?{...Ve,quantity:Number(le.target.value)}:Ve))})]}),e.jsx("button",{className:"member-btn is-neutral",onClick:()=>Kt(Fe.filter(le=>le.variant_uuid!==$.variant_uuid)),children:"Remove"})]},$.variant_uuid)),Fe.length?e.jsxs(e.Fragment,{children:[!d?.can_checkout&&!t&&e.jsx("p",{children:"Only active adult members, parents, billing owners and instructors can check out. Child accounts can browse."}),!d?.checkout_ready&&e.jsx("p",{children:"Checkout is awaiting release acceptance."}),e.jsxs("label",{className:"member-input-label",children:["Fulfilment",e.jsxs("select",{className:"member-input member-select",value:ue.fulfilment_method,onChange:$=>Rt({fulfilment_method:$.target.value,payment_method:t?"cash":"card"}),children:[!!ge?.pickup_location_ids.length&&e.jsx("option",{value:"pickup",children:"Collect at gym"}),!t&&ge?.shipping_enabled&&e.jsx("option",{value:"shipping",children:"UK delivery"})]})]}),ue.fulfilment_method==="pickup"&&(ge?.pickup_location_ids.length??0)===1?e.jsxs("p",{children:["Pickup at ",d?.locations.find($=>
2$.id===ge?.pickup_location_ids[0])?.name]}):ue.fulfilment_method==="pickup"?e.jsxs("label",{className:"member-input-label",children:["Pickup gym",e.jsx("select",{className:"member-input member-select",value:ue.pickup_location_id??"",onChange:$=>Rt({pickup_location_id:Number($.target.value)}),children:d?.locations.filter($=>ge?.pickup_location_ids.includes($.id)).map($=>e.jsx("option",{value:$.id,children:$.name},$.id))})]}):e.jsxs(e.Fragment,{children:[["line1","line2","city","postal_code"].map($=>e.jsxs("label",{className:"member-input-label",children:[{line1:"Address",line2:"Address line 2",city:"Town or city",postal_code:"Postcode"}[$],e.jsx("input",{className:"member-input",autoComplete:{line1:"address-line1",line2:"address-line2",city:"address-level2",postal_code:"postal-code"}[$],value:ue.address?.[$]??"",onChange:le=>Rt({address:{...ue.address,[$]:le.target.value,country:"GB"}})})]},$)),e.jsx("p",{children:"United Kingdom only."})]}),t?e.jsxs(e.Fragment,{children:[e.jsxs("label",{className:"member-input-label",children:["Customer name",e.jsx("input",{className:"member-input",value:Ie,onChange:$=>{ie($.target.value),ae(null)}})]}),e.jsxs("label",{className:"member-input-label",children:["Email (optional)",e.jsx("input",{className:"member-input",type:"email",value:Xe,onChange:$=>{ct($.target.value),ae(null)}})]}),e.jsxs("label",{className:"member-input-label",children:["Find a member (optional)",e.jsx(on,{ariaLabel:"Find a member",value:Et,onChange:q,placeholder:"Name or email"})]}),e.jsx("button",{className:"member-btn is-neutral",disabled:ke||Et.trim().length<2,onClick:()=>{At(async()=>{const $=await T.shop.request(`customers?search=${encodeURIComponent(Et)}`,void 0,!0);B($.rows)})},children:"Find member"}),te.map($=>e.jsxs("button",{className:"member-btn is-neutral",onClick:()=>{xt($.uuid),ie($.name),ct($.email),B([]),ae(null)},children:[$.name," · ",$.email]},$.uuid)),st&&e.jsxs("p",{children:["Linked to ",Ie,"."," ",e.jsx("button",{className:"member-btn is-neutral",onClick:()=>{xt(""),ae(null)},children:"Use walk in customer instead"})]}),e.jsx("p",{children:"Confirm only after receiving the cash. Available stocked items will be marked collected. Special orders remain awaiting fulfilment."})]}):e.jsxs(e.Fragment,{children:[e.jsxs("label",{className:"member-input-label",children:["Payment",e.jsxs("select",{className:"member-input member-select",value:ue.payment_method,onChange:$=>Rt({payment_method:$.target.value}),children:[e.jsx("option",{value:"card",children:"Pay by Card"}),e.jsx("option",{value:"saved_card",children:"Charge my account"}),!!d?.cash_enabled&&!!ge?.cash_location_ids.includes(ue.pickup_location_id??0)&&ue.fulfilment_method==="pickup"&&e.jsx("option",{value:"cash",children:"Cash at gym"})]})]}),!!d?.discounts_ready&&e.jsxs("label",{className:"member-input-label",children:["Discount code (optional)",e.jsx("input",{className:"member-input",autoCapitalize:"characters",autoComplete:"off",value:ue.discount_code??"",onChange:$=>Rt({discount_code:$.target.value}),placeholder:"Enter code"})]})]}),e.jsxs("p",{children:["Availability and delivery charges are checked for the whole basket before ordering.",d?.tax_mode==="vat_registered"&&" VAT is calculated before payment."]}),ge&&!ge.pickup_location_ids.length&&(t||!ge.shipping_enabled)&&e.jsx("p",{role:"alert",children:"The whole basket cannot currently be fulfilled. Reduce quantities or remove unavailable items."}),e.jsx("button",{className:"member-btn is-neutral",disabled:ke||!ge||!ge.pickup_location_ids.length&&(t||!ge.shipping_enabled)||!d?.checkout_ready||!t&&!d?.can_checkout,onClick:()=>{At(async()=>ae(await T.shop.request(t?"counter/quote":"quote",{...ts()},t)))},children:"Review total and availability"}),pe&&e.jsxs("div",{className:"member-shop-review",children:[e.jsx("h3",{children:"Order review"}),pe.items.map($=>e.jsxs("p",{children:[$.quantity," à ",$.snapshot.title," ·"," ",ua($.snapshot.options)," ·"," ",us($.quantity*$.unit_amount_minor)," ",$.preorder_quantity>0?`· ${$.preorder_quantity} preorder`:$.snapshot.stock_policy==="made_to_order"?"· Made to order":""]},$.variant_uuid)),pe.groups.map(($,le)=>e.jsxs("p",{children:[$.name," · ",$.preparation_message," · Delivery ",us($.shipping_minor)]},le)),e.jsxs("p",{children:["Products: ",us(pe.subtotal_minor)]}),pe.discount_minor>0&&pe.discount&&e.jsxs("p",{children:[pe.discount.name,": â",us(pe.discount_minor)]}),e.jsxs("p",{children:["Delivery: ",us(pe.shipping_minor)]}),pe.tax_mode!=="not_registered"&&e.jsxs("p",{children:["VAT included: ",us(pe.tax_minor)]}),e.jsxs("strong",{children:["Total: ",us(pe.amount_minor,pe.currency)]}),e.jsx("p",{children:ue.fulfilment_method==="pickup"?pe.pickup_instructions:pe.delivery_terms}),ue.payment_method==="cash"&&!t&&e.jsxs("p",{children:["Bring cash to the gym within"," ",d?.cash_hold_days," days to keep your reservation."]}),e.jsx("button",{className:"member-btn is-solid",disabled:ke,onClick:()=>{At(Zs)},children:ke?"Processingâ¦":t?"Confirm cash received and record sale":ue.payment_method==="cash"?"Place cash order":"Place order and pay"})]})]}):e.jsx("p",{children:"Your basket is empty."})]}),c==="orders"&&!u&&e.jsxs("div",{className:"member-panel-list",children:[t&&e.jsxs("label",{className:"member-input-label",children:["Show orders",e.jsxs("select",{className:"member-input member-select",value:O,onChange:$=>{L($.target.value),ce(null)},children:[e.jsx("option",{value:"action",children:"Needing action"}),e.jsx("option",{value:"all",children:"All orders"})]})]}),I.map($=>e.jsxs("button",{className:"member-panel-card member-shop-order",onClick:()=>a.push(`${o}/orders/${$.uuid}`),children:[e.jsxs("strong",{children:["Order #",$.id," ·"," ",us($.amount_minor,$.currency)]}),t&&e.jsx("span",{children:$.customer.name}),e.jsxs("span",{children:[gt($.payment_status)," ·"," ",gt($.status)]})]},$.uuid)),!fe&&!I.length&&e.jsx("p",{children:"No orders found."})]}),c==="orders"&&M&&e.jsxs("section",{className:"member-panel-card member-shop-detail",children:[e.jsxs("h2",{children:["Order #",M.id]}),e.jsxs("p",{children:[gt(M.payment_status)," · ",gt(M.status)]}),e.jsx("strong",{children:us(M.amount_minor,M.currency)}),!!M.discount_minor&&M.discount&&e.jsxs("p",{children:[M.discount.name,": â",us(M.discount_minor)]}),e.jsxs("p",{children:[M.tax_mode!=="not_registered"&&`VAT included: ${us(M.tax_minor)}. `,"Delivery: ",us(M.shipping_minor),"."]}),M.refunded_minor>0&&e.jsxs("p",{children:["Refunded: ",us(M.refunded_minor)]}),M.items.map($=>e.jsxs("p",{children:[$.quantity," à ",$.snapshot.title," ·"," ",ua($.snapshot.options)," ·"," ",$.snapshot.availability_message,$.refunded_quantity>0?` · ${$.refunded_quantity} refunded`:""]},$.uuid)),["pending","failed"].includes(M.payment_status)&&M.status!=="c
2ancelled"&&e.jsx(e.Fragment,{children:M.payment_method==="cash"?e.jsxs(e.Fragment,{children:[e.jsxs("p",{children:["Payment is due at the gym. Reservation expires"," ",M.hold_expires_at?new Date(M.hold_expires_at.replace(" ","T")+"Z").toLocaleString("en-GB"):"","."]}),e.jsx("p",{children:d?.pickup_instructions}),t&&d?.permissions.shop_log_sales&&e.jsx("button",{className:"member-btn is-neutral",disabled:ke,onClick:()=>{At(async()=>y(await T.shop.request(`orders/${M.uuid}/cash`,{},!0)))},children:"Confirm cash received"})]}):!t&&e.jsx("button",{className:"member-btn is-neutral",disabled:ke,onClick:()=>{At(()=>os(M))},children:"Continue card payment"})}),M.groups.map($=>{const le=vh($,M);return e.jsxs("div",{className:"member-shop-review",children:[e.jsx("h3",{children:$.snapshot.name}),e.jsxs("p",{children:[gt($.status)," ·"," ",$.snapshot.preparation_message]}),$.tracking&&e.jsxs("p",{children:[$.carrier,": ",$.tracking]}),t&&d?.permissions.shop_fulfil_orders&&le&&e.jsxs(e.Fragment,{children:[le==="dispatched"&&e.jsxs(e.Fragment,{children:[e.jsxs("label",{className:"member-input-label",children:["Carrier",e.jsx("input",{className:"member-input",value:Y,onChange:Ve=>oe(Ve.target.value)})]}),e.jsxs("label",{className:"member-input-label",children:["Tracking",e.jsx("input",{className:"member-input",value:Ue,onChange:Ve=>_e(Ve.target.value)})]})]}),e.jsxs("button",{className:"member-btn is-neutral",disabled:ke,onClick:()=>{At(async()=>y(await T.shop.request(`orders/${M.uuid}/fulfil`,{group_uuid:$.uuid,status:le,carrier:Y,tracking:Ue},!0)))},children:["Mark ",gt(le)]})]})]},$.uuid)}),e.jsx("button",{className:"member-btn is-neutral",disabled:ke,onClick:()=>{At(Yt)},children:"Refresh order"}),e.jsx("p",{children:"Contact the school for cancellations or refunds."})]}),c==="inventory"&&d?.permissions.shop_adjust_stock&&e.jsxs("section",{className:"member-panel-card member-shop-detail",children:[e.jsxs("label",{className:"member-input-label",children:["Stock location",e.jsx("select",{className:"member-input member-select",value:w??"",onChange:$=>{ce(null),A({}),_(Number($.target.value))},children:(d.stock_locations??d.locations).filter($=>!("active"in $)||$.active).map($=>e.jsx("option",{value:$.id,children:$.name},$.id))})]}),e.jsxs("label",{className:"member-input-label",children:["Reason",e.jsx("select",{className:"member-input member-select",value:D,onChange:$=>R($.target.value),children:["stocktake","added","removed","damaged","returned","correction"].map($=>e.jsx("option",{value:$,children:$==="stocktake"?"Set exact count":gt($)},$))})]}),P.map($=>e.jsxs("div",{className:"member-shop-review",children:[e.jsxs("strong",{children:[$.title," · ",ua($.options)]}),e.jsxs("p",{children:["On hand ",$.on_hand,", reserved ",$.reserved,", available"," ",$.available]}),e.jsxs("label",{className:"member-input-label",children:["Quantity",e.jsx(Ds,{className:"member-input",type:"number",min:"0",value:F[$.variant_uuid]??"",onChange:le=>A({...F,[$.variant_uuid]:le.target.value})})]}),e.jsx("button",{className:"member-btn is-neutral",disabled:ke||F[$.variant_uuid]===void 0,onClick:()=>{At(async()=>{await T.shop.request("inventory",{request_key:crypto.randomUUID(),changes:[{variant_id:$.variant_id,location_id:$.location_id,quantity:Number(F[$.variant_uuid]),reason:D,version:$.version}]},!0);const le=await T.shop.request(`inventory?location_id=${$.location_id}`,void 0,!0);U(le.rows),A({}),ce(null),Ne(le.next_cursor),J("Stock updated.")})},children:"Save adjustment"})]},$.variant_uuid))]}),me&&["catalogue","counter","inventory"].includes(c)||me&&c==="orders"&&!u?e.jsx("button",{className:"member-btn is-neutral",disabled:fe,onClick:()=>ce(me),children:"Load more"}):null]})]}),d&&rt!==void 0&&e.jsx(Ff,{open:!0,product:rt,config:d,onClose:()=>Lt(void 0),onSaved:$=>{const le=rt===null;Lt(void 0),p(Ve=>Ve?.uuid===$.uuid?$:Ve),J($.status==="draft"?"Draft saved. Finish this product in Admin before publishing.":"Product updated."),le&&kt("draft"),es(Ve=>Ve+1)}}),d&&Ft&&e.jsx(Wf,{open:!0,product:Ft,config:d,onClose:()=>Pt(null),onSaved:$=>{Pt(null),p($),J("Stock updated."),es(le=>le+1)}})]})}function $i(t){return`${t.childFirstName} ${t.childLastName}`.trim()||"Child profile"}function Tl(t){const s=`${t??""}`.trim().toLowerCase();return s==="training_pack"?"Training pack":s==="pass"?"Pass":s==="trial"?"Trial":"Membership"}function zf(t){const s=t.trim()||"Member";return`${s}${s.toLowerCase().endsWith("s")?"'":"'s"} membership`}function Gf(){const{user:t}=Ge(),s=T.tenant.getTenantTimezone(),[n,a]=r.useState(null),[i,o]=r.useState([]),[l,c]=r.useState([]),[u,d]=r.useState(""),[h,m]=r.useState(!0),[f,b]=r.useState(!1),[p,g]=r.useState(!1),v=wa(()=>g(!1)),[N,x]=r.useState(""),k=r.useCallback(async _=>{m(!0),x("");try{const[W,H,ne]=await Promise.all([T.me.getProfile({signal:_}),T.membership.listManagedStatuses({signal:_}),T.me.listDependants({signal:_}).catch(()=>[])]);a(W),o(H),c(ne),d(K=>H.some(de=>de.personUuid===K)||ne.some(de=>de.id===K)?K:H.find(de=>de.isSelf)?.personUuid||H[0]?.personUuid||ne[0]?.id||"")}catch(W){x(re(W,"Unable to load membership details."))}finally{m(!1)}},[]);r.useEffect(()=>{const _=new AbortController;return k(_.signal),()=>_.abort()},[k]);const j=ka(n?.member??null)?l:[],I=r.useMemo(()=>new Set(i.map(_=>_.personUuid)),[i]),S=r.useMemo(()=>j.filter(_=>!I.has(_.id)),[I,j]),M=r.useMemo(()=>i.find(_=>_.personUuid===u)??null,[i,u]),y=r.useMemo(()=>S.find(_=>_.id===u)??null,[S,u]),P=M?.membership??null,U=M?.upcomingMembership??null,F=M?.conversionCta??y?.conversionCta??null,A=P?.plan?.planType==="trial"||y?.currentPlanType==="trial",D=M?.isSelf===!0,R=i.length+S.length;async function w(){if(!(!F?.enabled||!F.trialAccessUuid||p)){g(!0),x("");try{const _=await T.trials.createConversionLink(F.trialAccessUuid);if(!_.url)throw new Error("Missing conversion link");v(_.url)}catch(_){x(re(_,"Unable to open membership choices.")),g(!1)}}}return e.jsxs(Ye,{standardUI:!0,title:"Membership",subtitle:"Your current plan, dates, and status.",activeTab:"membership",backTo:"/account",onRefresh:k,children:[h?e.jsxs("div",{className:"member-panel-loading",children:[e.jsx(Te,{name:"crescent"}),e.jsx("span",{children:"Loading membership..."})]}):null,!h&&N?e.jsx("div",{className:"member-panel-error",children:N}):null,!h&&!N?e.jsxs(e.Fragment,{children:[R>1?e.jsxs(e.Fragment,{children:[e.jsxs("button",{type:"button",className:"member-profile-picker","aria-haspopup":"dialog","aria-expanded":f,onClick:()=>b(!0),children:[e.jsxs("span",{children:[e.jsx("small",{children:"Membership for"}
2),e.jsx("strong",{children:D?"Me":M?.displayName||(y?$i(y):"Choose profile")})]}),e.jsx(V,{icon:Xr})]}),e.jsx(ci,{isOpen:f,title:"Choose profile",actions:[...i.map(_=>({key:_.personUuid,label:_.isSelf?"Me":_.displayName,mode:"select",selected:u===_.personUuid,onSelect:()=>d(_.personUuid)})),...S.map(_=>({key:_.id,label:$i(_),mode:"select",selected:u===_.id,onSelect:()=>d(_.id)}))],onClose:()=>b(!1)})]}):null,e.jsxs("section",{className:"member-panel-card member-membership-summary-card",children:[e.jsxs("div",{className:"member-row-main",children:[e.jsx("h2",{children:D?"My membership":zf(M?.displayName||(y?$i(y):"Member"))}),e.jsx(V,{icon:ti})]}),P?e.jsxs("div",{className:"member-panel-list member-list--divided",children:[e.jsxs("div",{className:"member-panel-row",children:[e.jsxs("div",{className:"member-row-main",children:[e.jsx("strong",{children:P.plan?.label||"No current plan"}),e.jsx("span",{className:"member-pill is-accent",children:gt(P.status,"No membership")})]}),P.plan?.planType?e.jsxs("p",{children:["Type: ",Tl(P.plan.planType)]}):null,e.jsxs("p",{children:["Starts: ",gs(P.billing.startsAt,s)]}),P.plan?.planType==="trial"?e.jsxs("p",{children:["Trial ends: ",gs(P.billing.currentPeriodEnd,s)]}):e.jsxs(e.Fragment,{children:[e.jsxs("p",{children:["Next payment: ",gs(P.billing.nextPaymentDate,s)]}),P.summary.amountMinor!=null?e.jsxs("p",{children:["Plan price: ",Vr(P.summary.amountMinor,P.summary.currency)]}):null]})]}),(P.plan?.creditsPerCycle??0)>0?e.jsxs("div",{className:"member-panel-row",children:[e.jsxs("div",{className:"member-row-main",children:[e.jsx("strong",{children:"Training credits"}),e.jsxs("span",{className:"member-pill",children:[P.credits.available," available"]})]}),e.jsxs("p",{children:["Total: ",P.credits.total]}),P.credits.held>0?e.jsxs("p",{children:["Held for bookings: ",P.credits.held]}):null]}):null,P.cancellation.cancelScheduled?e.jsxs("div",{className:"member-panel-row",children:[e.jsxs("div",{className:"member-row-main",children:[e.jsx("strong",{children:"Membership ending"}),e.jsx("span",{className:"member-pill is-warning",children:"Scheduled"})]}),e.jsxs("p",{children:["Final active date: ",gs(P.cancellation.finalActiveDate,s)]})]}):null]}):null,U?e.jsx("div",{className:"member-panel-list member-list--divided",children:e.jsxs("div",{className:"member-panel-row",children:[e.jsxs("div",{className:"member-row-main",children:[e.jsx("strong",{children:"Upcoming membership"}),e.jsx("span",{className:"member-pill is-accent",children:"Scheduled"})]}),e.jsxs("p",{children:["Plan: ",U.planName]}),e.jsxs("p",{children:["Starts: ",gs(U.startsAt,s)]}),e.jsxs("p",{children:["First payment: ",gs(U.nextPaymentDate,s)]}),U.amountMinor!=null?e.jsxs("p",{children:["Plan price: ",Vr(U.amountMinor,U.currency)]}):null]})}):null,!P&&!y?e.jsx("p",{children:"Membership details are not available yet."}):null,y?e.jsx("div",{className:"member-panel-list member-list--divided",children:e.jsxs("div",{className:"member-panel-row",children:[e.jsxs("div",{className:"member-row-main",children:[e.jsx("strong",{children:y.currentPlanLabel||"No current plan"}),e.jsx("span",{className:"member-pill",children:gt(y.membershipStatus,"No membership")})]}),y.currentPlanType?e.jsxs("p",{children:["Type: ",Tl(y.currentPlanType)]}):null,y.currentPlanType==="trial"?e.jsxs("p",{children:["Trial ends: ",gs(y.trialEndsAt,s)]}):null]})}):null,A&&F?.enabled?e.jsx("div",{className:"member-panel-list member-list--divided",children:e.jsxs("div",{className:"member-panel-row member-membership-conversion-row",children:[e.jsx("strong",{children:"Ready to become a member?"}),e.jsx("p",{children:"Choose a membership now. The trial stays active until the membership starts."}),e.jsxs("button",{type:"button",className:"member-btn is-solid",disabled:p,onClick:()=>{w()},children:[p?e.jsx(Te,{name:"crescent"}):e.jsx(V,{icon:ri}),p?"Opening membership choices...":"Choose a membership"]})]})}):null,A&&!U&&F&&!F.enabled&&F.reason?e.jsx("div",{className:"member-panel-list member-list--divided",children:e.jsxs("div",{className:"member-panel-row",children:[e.jsx("strong",{children:"Membership choices"}),e.jsx("p",{children:F.reason})]})}):null]}),e.jsxs("section",{className:"member-panel-card member-membership-help-card",children:[e.jsx("h2",{children:"Need help with your membership?"}
2),e.jsx("p",{children:"Contact the gym team to discuss changing your plan, upgrading, or cancelling your membership."})]})]}):null,t?.memberType==="child"?e.jsx("p",{children:"Child accounts cannot manage membership billing."}):null]})}function Kf(t){const s=t.brand?t.brand.toUpperCase():"CARD",n=t.last4?`**** ${t.last4}`:"****",a=t.expMonth&&t.expYear?`${`${t.expMonth}`.padStart(2,"0")}/${t.expYear}`:"N/A";return`${s} ${n} (exp ${a})`}function Yf(){const{user:t}=Ge(),s=mt(),n=po(),[a,i]=r.useState(null),[o,l]=r.useState([]),[c,u]=r.useState(!0),[d,h]=r.useState(!1),m=wa(()=>h(!1)),[f,b]=r.useState(""),[p,g]=r.useState(""),v=t?.memberType==="child",N=r.useMemo(()=>{const S=new URLSearchParams(s.search);return S.get("card")==="updated"?`${S.get("session_id")??""}`.trim():""},[s.search]),x=r.useCallback(async S=>{const M=await T.membership.listPaymentMethods({signal:S});l(M)},[]),k=r.useCallback(async S=>{u(!0),b("");try{!v&&N&&(await T.membership.confirmPaymentMethodSetupSession(N),n(s.pathname,{replace:!0}));const[M,y]=await Promise.all([T.me.getProfile({signal:S}),v?Promise.resolve([]):T.membership.listPaymentMethods({signal:S})]);i(M),l(y)}catch(M){const y=re(M,"Unable to load payment methods.");y&&b(y)}finally{u(!1)}},[v,s.pathname,n,N]);r.useEffect(()=>{const S=new AbortController;return k(S.signal),()=>{S.abort()}},[k]);const j=r.useMemo(()=>{const S=a?.member?.firstName??t?.firstName??"",M=a?.member?.lastName??t?.lastName??"";return`${S} ${M}`.trim()||"Member"},[a?.member?.firstName,a?.member?.lastName,t?.firstName,t?.lastName]);async function I(){if(!(d||v)){h(!0);try{const S=await T.membership.createPaymentMethodSetupSession();if(S.url){m(S.url);return}g("Payment method update session started."),await x()}catch(S){g(re(S,"Unable to start payment method update."))}finally{h(!1)}}}return e.jsxs(Ye,{standardUI:!0,title:"Payment Methods",subtitle:"View the cards used for membership payments and update them securely.",activeTab:"account",backTo:"/account",onRefresh:k,refresherDisabled:d,children:[c?e.jsxs("div",{className:"member-panel-loading",children:[e.jsx(Te,{name:"crescent"}),e.jsx("span",{children:"Loading payment methods..."})]}):null,!c&&f?e.jsx("div",{className:"member-panel-error",children:f}):null,!c&&!f?e.jsx(e.Fragment,{children:v?e.jsxs("section",{className:"member-panel-card",children:[e.jsx("h2",{children:"Access limited"}),e.jsx("p",{children:"Child accounts cannot manage payment methods."})]}):e.jsxs(e.Fragment,{children:[e.jsxs("section",{className:"member-panel-card",children:[e.jsxs("div",{className:"member-row-main",children:[e.jsx("h2",{children:"Payment account"}),e.jsx(V,{icon:ti})]}),e.jsx("p",{children:e.jsx("strong",{children:j})}),e.jsx("p",{children:"These cards are used for membership payments made through this account."}),e.jsx("p",{children:"You will use a secure Stripe page to add a new card. It will become the default for future payments. Membership changes and cancellations stay in SkullSystem."}),e.jsx("div",{className:"member-list-actions member-list-actions-full",children:e.jsxs("button",{type:"button",className:"member-btn is-solid",disabled:d,onClick:()=>{I()},children:[e.jsx(V,{icon:Vs}),"Update payment method"]})})]}),e.jsxs("section",{className:"member-panel-card",children:[e.jsx("h2",{children:"Saved cards"}),o.length===0?e.jsx("p",{children:"No payment methods found."}):null,o.length>0?e.jsx("div",{className:"member-panel-list member-list--divided",children:o.map(S=>{const M=S.id;return e.jsxs("div",{className:"member-panel-row",children:[e.jsxs("div",{className:"member-row-main",children:[e.jsx("strong",{children:Kf(S)}),e.jsx("span",{className:`member-pill${S.isDefault?" is-accent":""}`,children:S.isDefault?"Default":"Secondary"})]}),M?e.jsx("p",{children:"Stored securely by Stripe for future membership payments."}):null]},M??`${S.brand||"card"}-${S.last4||"none"}`)})}):null]})]})}):null,e.jsx(Dt,{isOpen:!!p,message:p,duration:2400,onDidDismiss:()=>g("")})]})}function Qf(){const t=tt(),s=mt(),a=`${r.useMemo(()=>new URLSearchParams(s.search),[s.search]).get("next")??""}`.trim()||"/account",i=/^\/onboarding\/(trial|membership)\/status\b/.test(a),[o,l]=r.useState(""),[c,u]=r.useState(""),[d,h]=r.useState(""),[m,f]=r.useState(""),[b,p]=r.useState(!1);async function g(v){if(v.preventDefault(),!b){if(!o||!c){h("Enter your new password in both fields.");return}if(o.length<8){h("Password must be at least 8 characters.");return}if(o!==c){h("Passwords do not match.");return}p(!0),h("");try{await T.me.initializePassword(o),f("Password created."),t.replace(a)}catch(N){h(re(N,"Unable to create your password right now."))}finally{p(!1)}}}return e.jsxs(Ye,{title:"Set Password",subtitle:"Create a password so you can sign back into the member app later.",activeTab:"account",backTo:i?null:"/account",hideBottomNav:i,hideMenu:i,allowHomeNavigation:!i,children:[e.jsx("section",{className:"member-panel-card",children:e.jsxs("form",{className:"member-password-form",onSubmit:g,noValidate:!0,children:[e.jsxs("label",{className:"member-input-label",children:[e.jsx("span",{children:"New password"}),e.jsx("input",{className:"member-input",type:"password",autoComplete:"new-password",value:o,onChange:v=>l(v.target.value),disabled:b})]}),e.jsxs("label",{className:"member-input-label",children:[e.jsx("span",{children:"Confirm password"}),e.jsx("input",{className:"member-input",type:"password",autoComplete:"new-password",value:c,onChange:v=>u(v.target.value),disabled:b})]}),d?e.jsx("p",{className:"member-password-error",children:d}):null,e.jsxs("div",{className:"member-list-actions",children:[e.jsx("button",{type:"submit",className:"member-btn is-solid",disabled:b,children:b?e.jsxs(e.Fragment,{children:[e.jsx(Te,{name:"crescent"}),"Saving..."]}):"Save password"}),i?null:e.jsx("button",{type:"button",className:"member-btn is-neutral",disabled:b,onClick:()=>t.replace(a),children:"Skip for now"})]})]})}),e.jsx(Dt,{isOpen:!!m,message:m,duration:2500,onDidDismiss:()=>f("")})]})}function Zf(){const{uuid:t=""}=Qs(),[s,n]=r.useState(null),[a,i]=r.useState(!0),[o,l]=r.useState(""),c=r.useCallback(async()=>{i(!0),l("");try{n(await T.people.getHouseholdDetail(t))}catch(u){l(re(u,"Unable to load household details.")),n(null)}finally{i(!1)}},[t]);return r.useEffect(()=>{c()},[c]),e.jsxs(Ye,{standardUI:!0,title:s?.householdName||"Household",subtitle:"Read-only household details for instructors and admins.",activeTab:"none",backTo:"/people/households",onRefresh:c,children:[a?e.jsxs("div",{className:"member-panel-loading",children:[e.jsx(Te,{name:"crescent"}),e.jsx("span",{children:"Loading household details..."})]}):null,!a&&o?e.jsx("div",{className:"member-panel-error",children:o}):null,!a&&s?e.jsxs(e.Fragment,{children:[e.jsxs("section",{className:"member-panel-card",children:[e.jsx("h2",{children:"Household summary"}),e.jsxs("div",{className:"member-panel-list member-list--divided",children:[e.jsxs("div",{className:"member-panel-row",children:[e.jsxs("div",{className:"member-row-main",children:[e.jsx("strong",{children:"Status"}),e.jsx("span",{className:"member-pill",children:gt(s.status)})]}),e.jsx("p",{children:s.householdNickname||"No nickname set"})]}),e.jsxs("div",{className:"member-panel-row",children:[e.jsx("div",{className:"member-row-main",children:e.jsx("strong",{children:"Primary payer"})}),e.jsxs("p",{children:[s.primaryPayerName||"No primary payer",s.primaryPayerEmail?` - ${s.primaryPayerEmail}`:""]})]})]})]}),e.jsxs("section",{className:"member-panel-card",children:[e.jsx("h2",{children:"Members"}),e.jsx("div",{className:"member-panel-list member-list--divided",children:s.members.map(u=>e.jsxs("div",{className:"member-panel-row",children:[e.jsxs("div",{className:"member-row-main",children:[e.jsx("strong",{children:u.fullName}),u.isPrimaryPayer?e.jsx("span",{className:"member-pill is-accent",children:"Primary payer"}):null]}),e.jsxs("p",{children:[u.householdRole," - ",u.memberType]}),e.jsx("p",{children:u.email||"No email recorded"})]},u.memberUuid))})]}),e.jsxs("section",{className:"member-panel-card",children:[e.jsx("h2",{children:"Qu
2ick notes"}),e.jsx("p",{children:"This household quick-notes area is under construction and will be active soon."})]})]}):null]})}function Uo({label:t,...s}){const n=r.useId();return e.jsxs("div",{className:"member-form-filled-wrap",children:[e.jsx("label",{className:"member-form-field-label",htmlFor:n,children:t}),e.jsx(on,{...s,id:n})]})}function Jf(){const t=tt(),[s,n]=r.useState([]),a=Xn({pageKey:"people-households-search",initialValue:{query:""}}),i=a.value.query,[o,l]=r.useState(!0),[c,u]=r.useState(""),d=r.useCallback(async()=>{l(!0),u("");try{n(await T.people.listHouseholds())}catch(m){u(re(m,"Unable to load households.")),n([])}finally{l(!1)}},[]);r.useEffect(()=>{d()},[d]);const h=$p(s,i);return e.jsxs(Ye,{standardUI:!0,title:"Households",subtitle:"Read-only household groups and primary payer details.",activeTab:"none",backTo:"/people",onRefresh:d,children:[e.jsxs("section",{className:"member-section",children:[e.jsx("h2",{children:"Search"}),e.jsx(Uo,{label:"Household, payer name, or email",ariaLabel:"Households",isSearching:o,value:i,onChange:m=>a.setValue({query:m}),placeholder:"Search households"}),i.trim().length>0&&i.trim().length<3?e.jsx("p",{className:"member-panel-help",children:"Type at least 3 letters."}):null]}),!o&&c?e.jsx("div",{className:"member-panel-error",children:c}):null,!o&&!c&&i.trim().length>=3&&h.length===0?e.jsx("div",{className:"member-panel-empty",children:"No households matched this search."}):null,!o&&!c&&h.length>0?e.jsxs("section",{className:"member-section",children:[e.jsx("h2",{children:"Households"}),e.jsx("div",{className:"member-panel-list member-list--divided",children:h.map(m=>e.jsxs("button",{type:"button",className:"member-panel-row",onClick:()=>t.push(`/people/households/${m.householdUuid}`),children:[e.jsxs("div",{className:"member-row-main",children:[e.jsx("strong",{children:m.householdName}),e.jsxs("span",{className:"member-pill",children:[m.memberCount," members"]})]}),e.jsxs("p",{children:[m.primaryPayerName||"No primary payer",m.primaryPayerEmail?` - ${m.primaryPayerEmail}`:""]})]},m.householdUuid))})]}):null]})}function Xf(){const t=tt(),{user:s}=Ge(),n=[...Kn(s)?[{label:"Members",description:"Read-only member profiles, emergency contacts, and quick notes.",path:"/people/members",icon:qs}]:[],...Yn(s)?[{label:"Prospects",description:"View lead and trial journeys, recent follow-up, and conversion state.",path:"/people/prospects",icon:As}]:[],...Zn(s)?[{label:"Households",description:"Open household groups, linked members, and primary payer details.",path:"/people/households",icon:xc}]:[]];return e.jsx(Ye,{standardUI:!0,title:"People",subtitle:"Instructor access to members, prospects, and households.",activeTab:"none",children:e.jsxs("section",{className:"member-section member-people-tools-card",children:[e.jsx("h2",{children:"People tools"}),e.jsx("div",{className:"member-panel-list member-list--divided",children:n.map(a=>e.jsxs("button",{type:"button",className:"member-panel-row",onClick:()=>t.push(a.path),children:[e.jsxs("div",{className:"member-row-main",children:[e.jsx("strong",{children:a.label}),e.jsx(V,{icon:a.icon})]}),e.jsx("p",{children:a.description})]},a.path))})]})})}function eg(t){const s=t.trim();if(!s||s.startsWith("data:")||s.startsWith("blob:"))return s;try{const n=/^https?:\/\//i.test(s),a=new URL(s,"https://profile-photo.local");return a.searchParams.delete("variant"),n?a.toString():`${a.pathname}${a.search}${a.hash}`}catch{return s}}function Du({src:t,alt:s,className:n="",fullSizeSrc:a}){const[i,o]=r.useState(!1),l=["member-profile-photo-preview",n].filter(Boolean).join(" "),c=a?.trim()||eg(t);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:l,children:[e.jsx("div",{className:"member-profile-photo-preview-image",children:e.jsx("img",{src:t,alt:s})}),e.jsx("button",{type:"button",className:"member-profile-photo-preview-trigger","aria-label":"View larger profile photo","aria-haspopup":"dialog","aria-expanded":i,onClick:()=>o(!0),children:e.jsx(V,{icon:bc,"aria-hidden":"true"})})]}),e.jsx(at,{className:"member-profile-photo-preview-modal",isOpen:i,onDidDismiss:()=>o(!1),children:e.jsxs("div",{className:"member-modal-sheet member-profile-photo-preview-sheet",children:[e.jsxs("div",{className:"member-modal-header",children:[e.jsx("h2",{children:"Profile photo"}),e.jsx("p",{children:"Read only enlarged preview."})]}),e.jsx("div",{className:"member-profile-photo-preview-stage",children:e.jsx("img",{src:i?c:void 0,alt:s})}),e.jsx("div",{className:"member-profile-photo-preview-actions",children:e.jsx("button",{type:"button",className:"member-btn is-neutral",onClick:()=>o(!1),children:"Close"})})]})})]})}function tg(){const t=T.tenant.getTenantTimezone(),{uuid:s=""}=Qs(),n=mt(),a=new URLSearchParams(n.search).get("returnTo")||"",i=a.startsWith("/")&&!a.startsWith("//")?a:"/people/members",[o,l]=r.useState(null),[c,u]=r.useState([]),d=Xn({pageKey:`people-member-note:${s}`,initialValue:{draftNote:""}}),h=d.value.draftNote,[m,f]=r.useState(!0),[b,p]=r.useState(!1),[g,v]=r.useState(""),[N,x]=r.useState(null),[k,j]=r.useState(""),[I,S]=r.useState(""),M=r.useCallback(async()=>{f(!0),j("");try{const[w,_]=await Promise.all([T.people.getMemberDetail(s),T.people.listMemberQuickNotes(s)]);l(w),u(_)}catch(w){j(re(w,"Unable to load member details.")),l(null),u([])}finally{f(!1)}},[s]);r.useEffect(()=>{M()},[M]);const y=r.useCallback(async()=>{const w=h.trim();if(w){p(!0);try{await T.people.createMemberQuickNote(s,w),await d.clear(),await M()}catch(_){j(re(_,"Unable to save this profile note."))}finally{p(!1)}}},[h,M,s]),P=r.useCallback(async(w,_)=>{const W=await Gn(_);S(W?`${w} copied.`:`Unable to copy ${w.toLowerCase()} on this device.`)},[]),U=r.useCallback(async w=>{x(null),v(w.uuid),j("");try{await T.people.deleteMemberQuickNote(s,w.uuid),u(_=>_.filter(W=>W.uuid!==w.uuid)),S("Note removed.")}catch(_){j(re(_,"Unable to remove this profile note."))}finally{v("")}},[s]),F=o?.createdAt?new Date(o.createdAt).toLocaleDateString("en-GB",{month:"short",year:"numeric"}):null,A=o?bu(o):[],D=!!(o?.emergencyContact.name||o?.emergencyContact.relationship||o?.emergencyContact.phone),R=!!(o?.activeMemberships.length||o?.activeTrials.length);return e.jsxs(Ye,{standardUI:!0,title:o?.fullName||"Member",subtitle:"Read-only member details for instructors and staff.",activeTab:"none",backTo:i,onRefresh:M,children:[m?e.jsxs("div",{className:"member-panel-loading",children:[e.jsx(Te,{name:"crescent"}),e.jsx("span",{children:"Loading member details..."})]}):null,!m&&k?e.jsx("div",{className:"member-panel-error",children:k}):null,!m&&o?e.jsxs(e.Fragment,{children:[A.length?e.jsxs("section",{className:"instructor-profile-safety",children:[e.jsx(V,{icon:hc}),e.jsxs("div",{children:[e.jsx("h2",{children:"Safety flags"}),e.jsx(fu,{messages:A})]})]}):null,e.jsxs("section",{className:"member-panel-card instructor-profile-hero",children:[o.avatarUrl?e.jsx(Du,{src:o.avatarUrl,alt:`${o.fullName} profile photo`,className:"instructor-profile-photo-preview"}):e.jsx("span",{children:o.fullName.charAt(0).toUpperCase()}),e.jsx("h2",{children:o.fullName}),e.jsx("p",{children:F?`Member since ${F}`:o.memberIdDisplay}),e.jsxs("div",{className:"instructor-profile-pills",children:[e.jsx("span",{className:"member-pill is-accent",children:gt(o.status,"Member")}),o.gradingSummary.map(w=>e.jsx("span",{className:"member-pill",children:[w.programName,w.levelLabel].filter(
2Boolean).join(" . ")},`${w.programName}:${w.levelLabel}`))]}),e.jsxs("div",{className:"instructor-contact-actions",children:[o.phone?e.jsxs("a",{href:`tel:${o.phone}`,children:[e.jsx(V,{icon:Ho}),e.jsx("span",{children:"Call"})]}):null,o.phone?e.jsxs("a",{href:`sms:${o.phone}`,children:[e.jsx(V,{icon:Wn}),e.jsx("span",{children:"SMS"})]}):null,o.phone?e.jsxs("a",{href:`https://wa.me/${o.phone.replace(/\D/g,"")}`,target:"_blank",rel:"noreferrer",children:[e.jsx(V,{icon:Wn}),e.jsx("span",{children:"WhatsApp"})]}):null,o.email?e.jsxs("a",{href:`mailto:${o.email}`,children:[e.jsx(V,{icon:qn}),e.jsx("span",{children:"Email"})]}):null]}),o.phone||o.email?e.jsxs("div",{className:"instructor-contact-details","aria-label":"Contact details",children:[o.phone?e.jsxs("button",{type:"button",onClick:()=>{P("Phone number",o.phone||"")},children:[e.jsx("span",{children:"Phone"}),e.jsx("strong",{children:o.phone})]}):null,o.phone?e.jsxs("button",{type:"button",onClick:()=>{P("WhatsApp number",o.phone||"")},children:[e.jsx("span",{children:"WhatsApp"}),e.jsx("strong",{children:o.phone})]}):null,o.email?e.jsxs("button",{type:"button",onClick:()=>{P("Email address",o.email)},children:[e.jsx("span",{children:"Email"}),e.jsx("strong",{children:o.email})]}):null]}):null]}),e.jsxs("section",{className:"member-panel-card instructor-current-access-card",children:[e.jsx("h2",{children:"Current membership and trials"}),R?e.jsxs("div",{className:"member-panel-list member-list--divided",children:[o.activeMemberships.map(w=>e.jsxs("div",{className:"member-panel-row",children:[e.jsxs("div",{className:"member-row-main",children:[e.jsx("strong",{children:w.name}),e.jsx("span",{className:"member-pill is-accent",children:"Active membership"})]}),e.jsx("p",{children:w.endDate?`Active until ${new Date(`${w.endDate}T00:00:00`).toLocaleDateString("en-GB")}`:"Active with no set end date"})]},w.uuid)),o.activeTrials.map(w=>e.jsxs("div",{className:"member-panel-row",children:[e.jsxs("div",{className:"member-row-main",children:[e.jsx("strong",{children:w.name}),e.jsx("span",{className:"member-pill is-accent",children:w.status==="scheduled"?"Scheduled trial":"Active trial"})]}),e.jsx("p",{children:[w.endsAt?`Ends ${zs(w.endsAt,t)}`:null,w.classesRemaining==null?null:`${w.classesRemaining} classes remaining`].filter(Boolean).join(" | ")||"Trial is active"})]},w.uuid))]}):e.jsx("p",{className:"member-panel-help",children:"No active membership or trial."})]}),e.jsxs("section",{className:"member-panel-card",children:[e.jsx("h2",{children:"Emergency contact"}),e.jsxs("div",{className:"instructor-emergency-contact",children:[e.jsx("div",{children:D?e.jsxs(e.Fragment,{children:[o.emergencyContact.name?e.jsx("strong",{children:o.emergencyContact.name}):null,o.emergencyContact.relationship?e.jsx("span",{children:o.emergencyContact.relationship}):null,o.emergencyContact.phone?e.jsx("span",{children:o.emergencyContact.phone}):null]}):e.jsx("span",{className:"instructor-emergency-contact-empty",children:"Not provided"})}),o.emergencyContact.phone?e.jsx("a",{href:`tel:${o.emergencyContact.phone}`,"aria-label":`Call ${o.emergencyContact.name||"emergency contact"}`,children:e.jsx(V,{icon:Ho})}):null]})]}),e.jsxs("section",{className:"member-panel-card member-profile-notes-card",children:[e.jsx("h2",{children:"Notes"}),e.jsx("p",{className:"member-panel-help",children:"Visible to instructors and staff."}),e.jsxs("label",{className:"member-input-label member-quick-note-input",children:[e.jsx("span",{className:"sr-only",children:"Add a note"}),e.jsx("textarea",{className:"member-input member-textarea",value:h,onChange:w=>d.setValue({draftNote:w.target.value}),placeholder:"Injury, coaching adjustment, behaviour, support or follow up"})]}),e.jsx("div",{className:"member-list-actions member-list-actions-full",children:e.jsx("button",{type:"button",className:"member-btn is-solid",onClick:()=>{y()},disabled:b||h.trim()==="",children:b?"Saving...":"Save note"})}),c.length>0?e.jsx("div",{className:"member-panel-list member-list--divided",children:c.map(w=>e.jsxs("div",{className:"member-panel-row",children:[e.jsxs("div",{className:"member-row-main",children:[e.jsx("strong",{children:w.authorDisplayName||"Staff note"}),w.isPinned?e.jsx("span",{className:"member-pill is-accent",children:"Pinned"}):null]}),e.jsx("p",{children:w.body||"Empty note"}),e.jsx("p",{children:w.updatedAt||w.createdAt?`Added ${zs(w.updatedAt||w.createdAt,t)}`:"Added recently"}),e.jsx("div",{className:"member-list-actions",children:e.jsx("button",{type:"button",className:"member-btn is-danger",disabled:g===w.uuid,onClick:()=>x(w),children:g===w.uuid?"Removing...":"Remove note"})})]},w.uuid))}):null]})]}):null,e.jsx(Vn,{isOpen:N!==null,header:"Remove member note?",message:N?`This removes the staff only note: ${N.body.trim().replace(/\s+/g," ").slice(0,120)||"Empty note"}`:"",buttons:[{text:"Cancel",role:"cancel",handler:()=>x(null)},{text:"Remove note",role:"destructive",handler:()=>{N&&U(N)}}],onDidDismiss:()=>x(null)}),e.jsx(Dt,{isOpen:!!I,message:I,duration:2200,onDidDismiss:()=>S("")})]})}function sg(){const t=tt(),[s,n]=r.useState([]),a=Xn({pageKey:"people-members-search",initialValue:{query:""}}),i=a.value.query,[o,l]=r.useState(!1),[c,u]=r.useState(!1),[d,h]=r.useState(""),m=r.useRef(0),f=r.useCallback(async(b=i,p=++m.current)=>{l(!0),h("");try{const g=await T.people.listMembers(b);p===m.current&&(n(g),u(!0))}catch(g){p===m.current&&(h(re(g,"Unable to load members.")),n([]),u(!0))}finally{p===m.current&&l(!1)}},[i]);return r.useEffect(()=>{if(!a.isHydrated)return;const b=i.trim(),p=++m.current;if(l(!1),h(""),b.length<3){n([]),u(!1);return}u(!1);const g=window.setTimeout(()=>{f(b,p)},300);return()=>window.clearTimeout(g)},[f,i,a.isHydrated]),e.jsxs(Ye,{standardUI:!0,title:"Members",subtitle:"Basic member details with quick staff access.",activeTab:"none",backTo:"/people",onRefresh:()=>i.trim().length>=3?f(i.trim()):void 0,children:[e.jsxs("section",{className:"member-section",children:[e.jsx("h2",{children:"Search"}),e.jsx(Uo,{label:"Name, email, or member number",ariaLabel:"Members",
2isSearching:o,value:i,onChange:b=>a.setValue({query:b}),placeholder:"Search members"}),i.trim().length>0&&i.trim().length<3?e.jsx("p",{className:"member-panel-help",children:"Type at least 3 letters."}):null]}),!o&&d?e.jsx("div",{className:"member-panel-error",children:d}):null,!o&&c&&!d&&s.length===0?e.jsx("div",{className:"member-panel-empty",children:"No members matched this search."}):null,!o&&!d&&s.length>0?e.jsxs("section",{className:"member-section",children:[e.jsx("h2",{children:"Results"}),e.jsx("div",{className:"member-panel-list member-list--divided",children:s.map(b=>e.jsxs("button",{type:"button",className:"member-panel-row",onClick:()=>t.push(`/people/members/${b.uuid}`),children:[e.jsxs("div",{className:"member-row-main",children:[e.jsx("strong",{children:b.fullName}),e.jsx("span",{className:"member-pill",children:gt(b.status)})]}),e.jsxs("p",{children:[b.memberType," - ",b.memberIdDisplay]}),e.jsxs("p",{children:[b.email,b.phone?` - ${b.phone}`:""]})]},b.uuid))})]}):null]})}function ng(){const{uuid:t=""}=Qs(),[s,n]=r.useState(null),[a,i]=r.useState(!0),[o,l]=r.useState(""),c=r.useCallback(async()=>{i(!0),l("");try{n(await T.people.getProspectDetail(t))}catch(u){l(re(u,"Unable to load prospect details.")),n(null)}finally{i(!1)}},[t]);return r.useEffect(()=>{c()},[c]),e.jsxs(Ye,{standardUI:!0,title:s?.fullName||"Prospect",subtitle:"Read-only lead and trial details.",activeTab:"none",backTo:"/people/prospects",onRefresh:c,children:[a?e.jsxs("div",{className:"member-panel-loading",children:[e.jsx(Te,{name:"crescent"}),e.jsx("span",{children:"Loading prospect details..."})]}):null,!a&&o?e.jsx("div",{className:"member-panel-error",children:o}):null,!a&&s?e.jsxs(e.Fragment,{children:[e.jsxs("section",{className:"member-panel-card",children:[e.jsx("h2",{children:"Prospect details"}),e.jsxs("div",{className:"member-panel-list member-list--divided",children:[e.jsxs("div",{className:"member-panel-row",children:[e.jsxs("div",{className:"member-row-main",children:[e.jsx("strong",{children:"Status"}),e.jsx("span",{className:"member-pill",children:gt(s.status)})]}),e.jsx("p",{children:s.journeyStageLabel})]}),e.jsxs("div",{className:"member-panel-row",children:[e.jsx("div",{className:"member-row-main",children:e.jsx("strong",{children:"Contact"})}),e.jsxs("p",{children:[s.email||"No email",s.phone?` - ${s.phone}`:""]})]}),e.jsxs("div",{className:"member-panel-row",children:[e.jsx("div",{className:"member-row-main",children:e.jsx("strong",{children:"Trial"})}),e.jsxs("p",{children:[s.trialOfferName||"No current trial offer",s.trialEndsAt?` - Ends ${s.trialEndsAt}`:""]})]}),e.jsxs("div",{className:"member-panel-row",children:[e.jsx("div",{className:"member-row-main",children:e.jsx("strong",{children:"Checkout"})}),e.jsxs("p",{children:[s.requiresPayment?"Payment still required.":"No payment action pending.",s.checkoutExpiresAt?` - Expires ${s.checkoutExpiresAt}`:""]})]})]})]}),e.jsxs("section",{className:"member-panel-card",children:[e.jsx("h2",{children:"Quick notes"}),e.jsx("p",{children:"Prospect quick-note editing is under construction and will be active soon."}),e.jsx("div",{className:"member-panel-list member-list--divided",children:s.contacts.length===0?e.jsx("div",{className:"member-panel-row",children:e.jsx("p",{children:"No recent follow-up notes yet."})}):s.contacts.map(u=>e.jsxs("div",{className:"member-panel-row",children:[e.jsx("div",{className:"member-row-main",children:e.jsx("strong",{children:"Recent follow-up"})}),e.jsx("p",{children:u.body||"No note text recorded."}),e.jsx("p",{children:u.createdAt||"Saved recently"})]},u.uuid))})]})]}):null]})}function ag(){const t=tt(),[s,n]=r.useState([]),a=Xn({pageKey:"people-prospects-search",initialValue:{query:""}}),i=a.value.query,[o,l]=r.useState(!1),[c,u]=r.useState(!1),[d,h]=r.useState(""),m=r.useRef(0),f=r.useCallback(async(b=i,p=++m.current)=>{l(!0),h("");try{const g=await T.people.listProspects(b);p===m.current&&(n(g),u(!0))}catch(g){p===m.current&&(h(re(g,"Unable to load prospects.")),n([]),u(!0))}finally{p===m.current&&l(!1)}},[i]);return r.useEffect(()=>{if(!a.isHydrated)return;const b=i.trim(),p=++m.current;if(l(!1),h(""),b.length<3){n([]),u(!1);return}u(!1);const g=window.setTimeout(()=>{f(b,p)},300);return()=>window.clearTimeout(g)},[f,i,a.isHydrated]),e.jsxs(Ye,{standardUI:!0,title:"Prospects",subtitle:"Lead and trial progress for instructors.",activeTab:"none",backTo:"/people",onRefresh:()=>i.trim().length>=3?f(i.trim()):void 0,children:[e.jsxs("section",{className:"member-section",children:[e.jsx("h2",{children:"Search"}),e.jsx(Uo,{label:"Name, email, or phone",ariaLabel:"Prospects",isSearching:o,value:i,onChange:b=>a.setValue({query:b}),placeholder:"Search prospects"}),i.trim().length>0&&i.trim().length<3?e.jsx("p",{className:"member-panel-help",children:"Type at least 3 letters."}):null]}),!o&&d?e.jsx("div",{className:"member-panel-error",children:d}):null,!o&&c&&!d&&s.length===0?e.jsx("div",{className:"member-panel-empty",children:"No prospects matched this search."}):null,!o&&!d&&s.length>0?e.jsxs("section",{className:"member-section",children:[e.jsx("h2",{children:"Results"}),e.jsx("div",{className:"member-panel-list member-list--divided",children:s.map(b=>e.jsxs("button",{type:"button",className:"member-panel-row",onClick:()=>t.push(`/people/prospects/${b.uuid}`),children:[e.jsxs("div",{className:"member-row-main",children:[e.jsx("strong",{children:b.fullName}),e.jsx("span",{className:"member-pill",children:gt(b.status)})]}),e.jsx("p",{children:b.journeyStageLabel}),e.jsx("p",{children:b.email||b.phone||"No contact details recorded"})]},b.uuid))})]}):null]})}function $r(t){return t==="web"?"Web chat":t.replaceAll("_"," ").replace(/^./,s=>s.toUpperCase())}function Lu({name:t,channel:s}){const n=s==="web"?dm:s==="email"?qn:/ad|campaign|facebook/.test(s)?mm:Wn;return e.jsxs("span",{className:"lead-avatar","aria-hidden":"true",children:[t.trim().split(/\s+/).slice(0,2).map(a=>a[0]).join("").toUpperCase(),e.jsx(V,{icon:n})]})}function Iu({active:t}){return e.jsx("span",{className:`lead-ai-icon${t?" is-active":" is-paused"}`,children:e.jsx(V,{icon:or})})}function $u(t,s=!1){if(!t)return"";const n=new Date(t);return Number.isNaN(n.getTime())?"":s||n.toDateString()===new Date().toDateString()?n.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):n.toLocaleDateString([],{day:"numeric",month:"short"})}function rg(){const t=tt(),s=mt(),[n,a]=r.useState([]),[i,o]=r.useState(!0),[l,c]=r.useState(""),[u,d]=r.useState(""),[h,m]=r.useState("all"),f=eu(),b=r.useCallback(async()=>{try{a(await T.leadConversations.list()),c("")}catch(v){c(re(v,"Unable to load lead conversations."))}finally{o(!1)}},[]);r.useEffect(()=>{if(s.pathname!=="/leads")return;b();const v=window.setInterval(()=>{document.visibilityState==="visible"&&b()},3e4);return()=>window.clearInterval(v)},[b,s.pathname]);const p=u.trim().toLowerCase(),g=n.filter(v=>(h==="all"||v.channel===h)&&[v.contactName,v.contactEmail,v.contactPhone,v.lastMessagePreview].some(N=>N?.toLowerCase().includes(p)));return e.jsxs(Ye,{standardUI:!0,title:"Conversations",activeTab:"leads",onRefresh:b,headingAction:e.jsx("span",{className:"lead-unread","aria-label":`${f} unread messages`,children:f}),children:[e.jsx(on,{ariaLabel:"Search conversations",placeholder:"Search conversations",value:u,onChange:d}),e.jsx("div",{className:"lead-channels","aria-label":"Channels",children:["all",...new Set(n.map(v
2=>v.channel))].map(v=>e.jsx("button",{type:"button","aria-pressed":h===v,onClick:()=>m(v),children:v==="all"?"All":$r(v)},v))}),i?e.jsxs("div",{className:"member-panel-loading",children:[e.jsx(Te,{name:"crescent"}),e.jsx("span",{children:"Loading conversations..."})]}):null,l?e.jsx("div",{className:"member-panel-error",role:"alert",children:l}):null,e.jsx("div",{className:"lead-inbox",children:g.map(v=>e.jsxs("button",{type:"button",className:`lead-inbox-row${v.unreadCount?" is-unread":""}`,onClick:()=>t.push(`/leads/${v.uuid}`),children:[e.jsx(Lu,{name:v.contactName,channel:v.channel}),e.jsxs("span",{className:"lead-inbox-copy",children:[e.jsx("strong",{children:v.contactName}),e.jsx("span",{className:"lead-preview",children:v.lastMessagePreview||v.contactPhone||v.contactEmail||$r(v.channel)}),e.jsx("span",{className:"lead-channel-label",children:$r(v.channel)})]}),e.jsxs("span",{className:"lead-inbox-meta",children:[e.jsx("time",{dateTime:v.lastMessageAt||void 0,children:$u(v.lastMessageAt)}),e.jsxs("span",{className:"lead-row-indicators",children:[e.jsx("span",{"aria-label":v.aiState==="active"?"AI active":"AI paused",children:e.jsx(Iu,{active:v.aiState==="active"})}),v.unreadCount>0?e.jsx("span",{className:"lead-unread","aria-label":`${v.unreadCount} unread messages`,children:v.unreadCount}):null]})]})]},v.uuid))}),!i&&!l&&g.length===0?e.jsx("div",{className:"member-panel-empty",children:n.length?"No matching conversations.":"No live conversations yet."}):null]})}function ig(){const{uuid:t=""}=Qs(),{user:s}=Ge(),a=mt().pathname===`/leads/${t}`,[i,o]=r.useState(null),[l,c]=r.useState([]),[u,d]=r.useState(""),[h,m]=r.useState(!1),[f,b]=r.useState(""),p=r.useRef(null),g=r.useRef(!0),v=r.useRef(0),N=r.useRef(""),x=r.useCallback(async()=>{const P=++v.current;try{const U=await T.leadConversations.detail(t);if(P!==v.current)return;o(U.conversation),c(U.messages),b("")}catch(U){P===v.current&&b(re(U,"Unable to load this conversation."))}},[t]);r.useEffect(()=>{if(o(null),c([]),d(""),N.current="",g.current=!0,!a)return;x();const P=window.setInterval(()=>{document.visibilityState==="visible"&&x()},15e3);return()=>{++v.current,window.clearInterval(P)}},[x,a]);const k=r.useCallback(async()=>{const P=l.at(-1);if(!(!a||!P||!g.current||document.visibilityState!=="visible"||N.current===P.uuid)){N.current=P.uuid;try{await T.leadConversations.markRead(t,P.uuid)}catch{N.current=""}}},[l,t,a]);r.useEffect(()=>{g.current&&p.current&&(p.current.scrollTop=p.current.scrollHeight),k()},[l,k]),r.useEffect(()=>{const P=()=>{document.visibilityState==="visible"&&k()};return document.addEventListener("visibilitychange",P),()=>document.removeEventListener("visibilitychange",P)},[k]),r.useEffect(()=>{const P=window.visualViewport,U=p.current?.closest(".lead-chat-page");if(!P||!U||!a)return;const F=()=>{U.style.height=`${P.height}px`,U.style.top=`${P.offsetTop}px`};return F(),P.addEventListener("resize",F),P.addEventListener("scroll",F),()=>{P.removeEventListener("resize",F),P.removeEventListener("scroll",F),U.style.removeProperty("height"),U.style.removeProperty("top")}},[a]);async function j(){if(!(!i||h)){m(!0);try{await T.leadConversations.setAiState(i.uuid,i.aiState==="active"?"paused":"active"),await x()}catch(P){b(re(P,"Unable to change AI state."))}finally{m(!1)}}}async function I(){if(!(!i||!u.trim()||h||i.provider!=="website_widget")){m(!0);try{await T.leadConversations.reply(i.uuid,u.trim()),d(""),g.current=!0,await x()}catch(P){b(re(P,"Unable to send your reply."))}finally{m(!1)}}}const S=Ys(s,"lead_ai_control"),M=Ys(s,"lead_conversations_reply"),y=i?.aiState==="active";return e.jsxs(Ye,{title:i?.contactName||"Conversation",hideHeading:!0,activeTab:"leads",backTo:"/leads",suppressInstallPrompt:!0,pageClassName:"lead-chat-page",mainClassName:"lead-chat-main",headerContent:i?e.jsxs("div",{className:"lead-contact",children:[e.jsx(Lu,{name:i.contactName,channel:i.channel}),e.jsxs("span",{className:"lead-contact-name",children:[e.jsx("strong",{children:i.contactName}),e.jsx("small",{children:$r(i.channel)})]}),e.jsx("button",{type:"button",className:"lead-ai-toggle","aria-label":S?y?"Pause AI":"Resume AI":y?"AI active":"AI paused","aria-pressed":y,disabled:h||!S,onClick:()=>{j()},children:e.jsx(Iu,{active:y})})]}):void 0,children:[f?e.jsx("div",{className:"member-panel-error",role:"alert",children:f}):null,!i&&!f?e.jsxs("div",{className:"member-panel-loading",children:[e.jsx(Te,{name:"crescent"}),e.jsx("span",{children:"Loading conversation..."})]}):null,e.jsxs("div",{className:"lead-chat-messages",ref:p,role:"log","aria-label":"Conversation messages",onScroll:()=>{const P=p.current;P&&(g.current=P.scrollHeight-P.scrollTop-P.clientHeight<60),g.current&&k()},children:[l.map((P,U)=>{const F=new Date(P.createdAt).toLocaleDateString([],{day:"numeric",month:"long",year:"numeric"}),A=U?new Date(l[U-1].createdAt).toLocaleDateString([],{day:"numeric",month:"long",year:"numeric"}):"";return e.jsxs("div",{className:"lead-message-group",children:[F!==A?e.jsx("div",{className:"lead-date-divider",children:F}):null,e.jsxs("div",{className:`lead-bubble is-${P.authorType}`,children:[P.authorType!=="system"?e.jsx("small",{className:"lead-message-author",children:P.authorType==="ai"?"Jack · AI":P.authorType==="staff"?"Staff":i?.contactName}):null,e.jsx("p",{children:P.body}),e.jsxs("span",{className:"lead-message-meta",children:[e.jsx("time",{dateTime:P.createdAt,children:$u(P.createdAt,!0)}),P.authorType==="staff"||P.authorType==="ai"?e.jsx("span",{children:P.deliveryStatus==="delivered"?"Delivered":P.deliveryStatus==="failed"?"Failed":P.deliveryStatus==="sent"?"Sent":""}):null]})]})]},P.uuid)}),i&&l.length===0?e.jsx("div",{className:"member-panel-empty",children:"No messages yet."}):null]}),i&&M?e.jsxs("form",{className:"lead-composer",onSubmit:P=>{P.preventDefault(),I()}
2,children:[e.jsxs("div",{className:"lead-composer-controls",children:[e.jsx("textarea",{"aria-label":"Reply to lead",rows:1,maxLength:5e3,value:u,onChange:P=>{d(P.target.value),P.target.style.height="auto",P.target.style.height=`${Math.min(P.target.scrollHeight,120)}px`},placeholder:"Message",disabled:h||i.provider!=="website_widget"}),e.jsx("button",{type:"submit","aria-label":"Send message",disabled:h||!u.trim()||i.provider!=="website_widget",children:e.jsx(V,{icon:mc})})]}),i.provider!=="website_widget"?e.jsx("small",{children:"Sending is not available for this channel yet."}):e.jsx("small",{children:"Your reply pauses Jack."})]}):null]})}function Ha(t){return t.currentLevel?.label||t.currentBelt?.label||"Not graded yet"}function og(t){const s=/^(\d{4})-(\d{2})-(\d{2})$/.exec(String(t||"").trim());if(!s)return"Date not recorded";const n=new Date(Date.UTC(Number(s[1]),Number(s[2])-1,Number(s[3]),12));return new Intl.DateTimeFormat("en-GB",{day:"numeric",month:"short",year:"numeric",timeZone:"UTC"}).format(n)}function lg({gradingSummary:t}){const[s,n]=r.useState(null);return e.jsxs(e.Fragment,{children:[e.jsxs("section",{className:"member-panel-card member-grading-card",children:[e.jsx("h2",{children:"Levels and grading"}),t.length===0?e.jsx("p",{children:"No grading progress recorded yet."}):e.jsx("div",{className:"member-grading-programmes",children:t.map(a=>{const i=a.program.gradingDisplayType==="patch",o=!i&&((a.currentLevel?.stripesPerLevel||0)>0||a.currentStripeCount>0),l=Es(a.currentLevel?.beltColourKey)||Es(a.currentBelt?.colourKey)||Es(a.currentLevel?.label)||Es(a.currentBelt?.label)||"#e5e7eb",c=a.stripeAwards.slice(0,a.currentStripeCount).reverse();return e.jsxs("article",{className:`member-grading-programme${i?" is-patch":""}`,children:[i?a.currentLevel?.patchUrl?e.jsx("div",{className:"member-grading-patch-stage",children:e.jsx("img",{src:a.currentLevel.patchUrl,alt:`${Ha(a)} patch`})}):e.jsx("div",{className:"member-grading-patch-empty",role:"img","aria-label":`${Ha(a)} patch has no image`,children:"No patch image"}):e.jsxs("div",{className:"member-grading-belt",style:{backgroundColor:l},role:"img","aria-label":o?`${Ha(a)} belt with ${a.currentStripeCount} ${a.currentStripeCount===1?"stripe":"stripes"}`:`${Ha(a)} belt`,children:[e.jsx("span",{className:"member-grading-belt-band","aria-hidden":"true"}),o?e.jsx("span",{className:"member-grading-belt-stripes","aria-hidden":"true",children:Array.from({length:a.currentStripeCount}).map((u,d)=>e.jsx("span",{style:{backgroundColor:Es(c[d]?.colourKey)||"#ffffff"}},d))}):null]}),e.jsxs("div",{className:"member-grading-description",children:[e.jsx("strong",{children:a.program.name}),e.jsxs("span",{children:["Level: ",Ha(a)]}),o?e.jsxs("span",{children:[a.currentStripeCount," ",a.currentStripeCount===1?"stripe":"stripes"]}):null]}),o?e.jsx("button",{type:"button",className:"member-btn is-neutral member-grading-history-button",onClick:()=>n(a),children:"Stripe history"}):null]},a.program.uuid)})})]}),e.jsx(at,{className:"member-grading-history-modal",isOpen:s!==null,onDidDismiss:()=>n(null),children:e.jsxs("div",{className:"member-modal-sheet member-grading-history-sheet",children:[e.jsxs("div",{className:"member-modal-header",children:[e.jsx("h2",{children:"Stripe history"}),e.jsx("p",{children:s?.program.name||"Programme"})]}),e.jsx("div",{className:"member-grading-history-list",children:s?.stripeAwards.length?s.stripeAwards.map(a=>e.jsxs("div",{className:"member-grading-history-row",children:[e.jsx("span",{className:"member-grading-history-colour",style:{backgroundColor:Es(a.colourKey)||"#d4d4d4"},"aria-hidden":"true"}),e.jsxs("span",{className:"member-grading-history-copy",children:[e.jsx("strong",{children:a.label}),e.jsx("small",{children:a.source==="manual"?"Added by staff":"Class attendance"})]}),e.jsx("time",{dateTime:a.awardedOn||void 0,children:og(a.awardedOn)})]},a.uuid)):e.jsx("p",{className:"member-grading-history-empty",children:"No individual stripe awards have been recorded."})}),e.jsx("div",{className:"member-profile-photo-preview-actions",children:e.jsx("button",{type:"button",className:"member-btn is-neutral",onClick:()=>n(null),children:"Close"})})]})})]})}function cg({src:t,alt:s,onSelect:n}){return e.jsxs("div",{className:"member-profile-photo-editor",children:[t?e.jsx(Du,{src:t,alt:s}):e.jsx("div",{className:"member-profile-photo-preview",children:e.jsx(V,{icon:qs})}),e.jsxs("label",{className:"member-profile-photo-preview-trigger member-profile-photo-change",children:[e.jsx(V,{icon:yo,"aria-hidden":"true"}),e.jsx("input",{type:"file",accept:"image/png,image/jpeg,image/webp,image/gif","aria-label":"Change profile photo",onChange:a=>{const i=a.currentTarget.files?.[0];i&&n(i),a.currentTarget.value=""}})]})]})}function ug(t){return`${t.childFirstName} ${t.childLastName}`.trim()||"Child profile"}function dg(t,s){const n=[{value:"self",label:"Me",isSelf:!0}];if(!t)return n;for(const a of s)n.push({value:a.id,label:ug(a),isSelf:!1});return n}function _l(t){if(!t)return"Not set";const s=new Date(t);return Number.isNaN(s.getTime())?"Not set":new Intl.DateTimeFormat("en-GB",{timeZone:T.tenant.getTenantTimezone(),day:"numeric",month:"long",year:"numeric"}).format(s)}function mg(t){const s=t.trim().toLowerCase();return s?s.charAt(0).toUpperCase()+s.slice(1).replaceAll("_"," "):"Trial"}function hg(){const t=mt(),s=tt(),n=r.useMemo(()=>new URLSearchParams(t.search),[t.search]),a=n.get("required")==="phone",i=n.get("profile_member_uuid")??"",o=iu(n.get("next")),l=r.useRef(null),[c,u]=r.useState(null),[d,h]=r.useState([]),[m,f]=r.useState("self"),[b,p]=r.useState(!1),[g,v]=r.useState(!0),[N,x]=r.useState(!1),[k,j]=r.useState(""),[I,S]=r.useState(""),[M,y]=r.useState(""),[P,U]=r.useState(""),[F,A]=r.useState(""),[D,R]=r.useState(""),[w,_]=r.useState(""),[W,H]=r.useState(""),[ne,K]=r.useState(""),[ye,de]=r.useState(""),[O,L]=r.useState(""),[Z,ce]=r.useState(""),[me,Ne]=r.useState(""),[ve,xe]=r.useState(""),[G,J]=r.useState("United Kingdom"),[ke,Be]=r.useState(null),[fe,Ae]=r.useState(null),lt=r.useCallback(async ie=>{const[Xe,ct]=await Promise.all([T.me.getProfile({signal:ie}),T.me.listDependants({signal:ie}).catch(()=>[])]);
2return u(Xe),h(ct),{meProfile:Xe,dependantRows:ct}},[]),be=r.useCallback(async ie=>{v(!0),j("");try{await lt(ie)}catch(Xe){const ct=re(Xe,"Unable to load profile.");ct&&j(ct)}finally{v(!1)}},[lt]);r.useEffect(()=>{const ie=new AbortController;return be(ie.signal),()=>{ie.abort()}},[be]);const We=c?.member??null,Fe=We?.trialAccess??null,Ke=ka(We),ue=r.useMemo(()=>dg(Ke,d),[Ke,d]),Se=kp(i,We?.uuid,ue.filter(ie=>!ie.isSelf).map(ie=>ie.value));r.useEffect(()=>{t.pathname!=="/profile"||!a||!Se||(f(Se),p(!1),g||l.current?.focus())},[Se,g,t.key,t.pathname,a]);const pe=ue.find(ie=>ie.value===m)??ue[0],ae=r.useMemo(()=>ue.map(ie=>({key:ie.value,label:ie.label,mode:"select",selected:ie.value===m,onSelect:()=>f(ie.value)})),[m,ue]);r.useEffect(()=>{if(!ue.some(Xe=>Xe.value===m)){f("self");return}if(m==="self"){y(We?.firstName||""),U(We?.lastName||""),A(We?.email||""),R(We?.phone||""),_(We?.dob||""),H(We?.emergencyContact.name||""),K(We?.emergencyContact.phone||""),de(We?.emergencyContact.relationship||""),L(We?.address.street||""),ce(We?.address.suburb||""),Ne(We?.address.city||""),xe(We?.address.postcode||""),J(We?.address.country||"United Kingdom"),Be(We?.avatarUrl||null),Ae(null);return}const ie=d.find(Xe=>Xe.id===m)??null;ie&&(y(ie.childFirstName||""),U(ie.childLastName||""),_(ie.dob||""),A(""),R(ie.phone||""),H(ie.emergencyContact.name||""),K(ie.emergencyContact.phone||""),de(ie.emergencyContact.relationship||""),L(ie.address.street||""),ce(ie.address.suburb||""),Ne(ie.address.city||""),xe(ie.address.postcode||""),J(ie.address.country||"United Kingdom"),Be(ie.avatarUrl||null),Ae(null))},[d,We,m,ue]);const ge=d.find(ie=>ie.id===m)??null,qe=m==="self",Me=qe?We?.gradingSummary||[]:ge?.gradingSummary||[];async function Ie(){if(!N){if(a&&(Se!==m||!D.trim())){S(Se?"Enter a phone number before returning to your booking.":"Ask the contact person or your gym to add their phone number."),l.current?.focus();return}x(!0);try{const ie=qe?We?.uuid:ge?.id;let Xe;fe&&ie&&(Xe=(await T.me.uploadProfileImage(fe,ie)).id);const ct={street:O,suburb:Z,city:me,postcode:ve,country:G};if(qe){await T.me.patchProfile({firstName:M.trim(),lastName:P.trim(),email:F.trim(),mobile:D.trim(),dob:w.trim(),avatarMediaUuid:Xe,address:ct,emergencyContactName:W.trim(),emergencyContactPhone:ne.trim(),emergencyContactRelationship:ye.trim()});const xt=await lt();if(a){xt.meProfile.member?.phone?.trim()?s.replace(o):S("Your phone number was not saved. Please try again.");return}S("Profile updated.");return}if(!ge){S("Select a dependant profile first.");return}await T.me.updateDependant(ge.id,{childFirstName:M.trim(),childLastName:P.trim(),dob:w.trim(),phone:D.trim(),avatarMediaUuid:Xe,address:ct,emergencyContactName:W.trim(),emergencyContactPhone:ne.trim(),emergencyContactRelationship:ye.trim()});const st=await lt();if(a){st.dependantRows.find(xt=>xt.id===m)?.phone?.trim()?s.replace(o):S("Your phone number was not saved. Please try again.");return}S("Dependant profile updated.")}catch(ie){S(re(ie,"Unable to save profile changes."))}finally{x(!1)}}}return e.jsxs(Ye,{standardUI:!0,title:"Profile",subtitle:"Manage profile and emergency contact details.",activeTab:"account",backTo:a?o:"/timetable",hideBottomNav:b,onRefresh:be,refresherDisabled:N,children:[g?e.jsxs("div",{className:"member-panel-loading",children:[e.jsx(Te,{name:"crescent"}),e.jsx("span",{children:"Loading profile..."})]}):null,!g&&k?e.jsx("div",{className:"member-panel-error",children:k}):null,!g&&!k?e.jsxs(e.Fragment,{children:[a?e.jsxs("section",{className:"member-panel-card",role:"status","aria-live":"polite",children:[e.jsx("h2",{children:"Phone number needed"}),e.jsx("p",{id:"booking-phone-message",children:Se?"Add a phone number to this profile before booking. Save your changes to return to your class.":"The contact profile for this booking needs a phone number. Ask the contact person or your gym to add it."})]}):null,ue.length>1&&!a?e.jsxs("button",{type:"button",className:"member-profile-picker","aria-haspopup":"dialog","aria-expanded":b,onClick:()=>p(!0),children:[e.jsxs("span",{children:[e.jsx("small",{children:"Viewing profile"}),e.jsx("strong",{children:pe?.label||"Me"})]}),e.jsx(V,{icon:Xr})]}):null,qe&&Fe?e.jsxs("section",{className:"member-panel-card member-trial-summary-card",children:[e.jsxs("div",{className:"member-row-main",children:[e.jsxs("div",{children:[e.jsx("p",{className:"member-trial-summary-kicker",children:"Your trial"}),e.jsx("h2",{children:Fe.offerName})]}),e.jsx(V,{icon:Ut})]}),e.jsx("span",{className:`member-trial-status is-${Fe.status.trim().toLowerCase()||"trial"}`,children:mg(Fe.status)}),e.jsxs("div",{className:"member-trial-summary-grid",children:[e.jsxs("div",{children:[e.jsx("span",{children:"Starts"}),e.jsx("strong",{children:_l(Fe.startsAt)})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Ends"}),e.jsx("strong",{children:_l(Fe.endsAt)})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Classes remaining"}),e.jsx("strong",{children:Fe.classesRemaining??"Unlimited"})]})]}),e.jsx("p",{className:"member-trial-summary-note",children:Fe.status==="scheduled"?"Your trial is paid and scheduled. You can reserve classes within these dates when each class booking window opens.":"Your trial is active. Choose an eligible class from the timetable."})]}):null,e.jsxs("section",{className:"member-panel-card",children:[e.jsxs("div",{className:"member-row-main",children:[e.jsx("h2",{children:qe?"My profile":"Dependant profile"}),e.jsx(V,{icon:qs})]}),e.jsx(cg,{src:ke||"",alt:`${pe?.label||"Profile"} photo`,onSelect:ie=>{Ae(ie),Be(URL.createObjectURL(ie))}}),e.jsxs("div",{className:"member-input-group",children:[e.jsxs("label",{className:"member-input-label",children:[e.jsx("span",{children:"First name"}),e.jsx("input",{className:"member-input",value:M,onChange:ie=>y(ie.target.value)})]}),e.jsxs("label",{className:"member-input-label",children:[e.jsx("span",{children:"Last name"}),e.jsx("input",{className:"member-input",value:P,onChange:ie=>U(ie.target.value)})]}),e.jsx(ao,{id:"member-profile-date-of-birth",label:"Date of birth",presentation:"date",value:w,max:new Date().toISOString().slice(0,10),onChange:_}),e.jsxs("label",{className:"member-input-label",children:[e.jsx("span",{children:"Phone"}),e.jsx("input",{className:"member-input",type:"tel",ref:l,"aria-describedby":a?"booking-phone-message":void 0,required:a,inputMode:"numeric",pattern:"[0-9]*",autoComplete:"tel",value:D,onChange:ie=>R(ie.target.value.replace(/\D/g,""))})]}),qe?e.jsx(e.Fragment,{children:e.jsxs("label",{className:"member-input-label",children:[e.jsx("span",{children:"Email"}),e.jsx("input",{className:"member-input",type:"email",value:F,onChange:ie=>A(ie.target.value)})]})}):null]})]}),e.jsx(lg,{gradingSummary:Me}),e.jsxs("section",{className:"member-panel-card",children:[e.jsx("h2",{children:"Emergency contact"}),e.jsxs("div",{className:"member-input-group",children:[e.jsxs("label",{className:"member-input-label",children:[e.jsx("span",{children:"Name"}),e.jsx("input",{className:"member-input",value:W,onChange:ie=>H(ie.target.value)})]}),e.jsxs("label",{className:"member-input-label",children:[e.jsx("span",{children:"Phone"}),e.jsx("input",{className:"member-input",type:"tel",inputMode:"numeric",pattern:"[0-9]*",autoComplete:"tel",value:ne,onChange:ie=>K(ie.target.value.replace(/\D/g,""))})]}),e.jsxs("label",{className:"member-input-label",children:[e.jsx("span",{children:"Relationship"}),e.jsx("input",{className:"member-input",value:ye,onChange:ie=>de(ie.target.value)})]})]})]}),e.jsxs("section",{className:"member-panel-card",children:[e.jsx("h2",{children:"Address"}),e.jsxs("div",{className:"member-input-group",children:[e.jsxs("label",{className:"member-input-label",children:[e.jsx("span",{children:"Street address"}),e.jsx("input",{className:"member-input",value:O,onChange:ie=>L(ie.target.value)})]}),e.jsxs("label",{className:"member-input-label",children:[e.jsx("span",{children:"Area"}),e.jsx("input",{className:"member-input",value:Z,onChange:ie=>ce(ie.target.value)})]}),e.jsxs("label",{className:"member-input-label",children:[e.jsx("span",{children:"Town or city"}),e.jsx("input",{className:"member-input",value:me,onChange:ie=>Ne(ie.target.value)})]}),e.jsxs("label",{className:"member-input-label",children:[e.jsx("span",{children:"Postcode"}),e.jsx("input",{className:"member-input",value:ve,onChange:ie=>xe(ie.target.value)})]}),e.jsxs("label",{className:"member-input-label",children:[e.jsx("span",{children:"Country"}),e.jsx("input",{className:"member-input",value:G,onChange:ie=>J(ie.target.value)})]})]})]}),e.jsx("div",{className:"member-page-primary-action",children:e.jsx("button",{type:"button",className:"member-btn is-solid",disabled:N,onClick:()=>{Ie()},children:N?"Saving...":"Save profile"})})]}
2):null,e.jsx(ci,{isOpen:b,title:"Choose profile",actions:ae,onClose:()=>p(!1)}),e.jsx(Dt,{isOpen:!!I,message:I,duration:2500,onDidDismiss:()=>S("")})]})}function pg(){const t=tt(),{acceptIssuedSession:s}=Ge(),[n,a]=r.useState(""),[i,o]=r.useState(""),[l,c]=r.useState(""),[u,d]=r.useState(""),[h,m]=r.useState(""),[f,b]=r.useState(""),[p,g]=r.useState(""),[v,N]=r.useState(""),[x,k]=r.useState(!1),j=M=>M instanceof cn||M instanceof Error?M.message:"Account recovery is not available right now.",I=async M=>{M.preventDefault(),N(""),g("");try{k(!0);const y=await T.auth.requestRecoveryCode({firstName:n,lastName:i,phone:l});d(y.challengeId),m(y.deliveryHint),g(y.message)}catch(y){N(j(y))}finally{k(!1)}},S=async M=>{M.preventDefault(),N("");try{k(!0);const y=await T.auth.verifyRecoveryCode(u,f);await s(y,{rememberMe:!0}),t.replace("/timetable")}catch(y){N(j(y))}finally{k(!1)}};return e.jsxs(mr,{children:[u?e.jsxs("form",{onSubmit:S,noValidate:!0,className:"member-login-form",children:[e.jsxs("p",{className:"member-login-status",children:[p,h?` Check ${h}.`:""]}),e.jsxs("label",{className:"member-login-field",children:[e.jsx("span",{className:"member-login-label",children:"Recovery code"}),e.jsx("input",{type:"text",className:"member-login-input",inputMode:"numeric",autoComplete:"one-time-code",maxLength:6,value:f,onChange:M=>b(M.target.value.replace(/\D+/g,"").slice(0,6)),disabled:x})]}),v?e.jsx("p",{className:"member-login-error",children:v}):null,e.jsx(vt,{className:"member-login-submit",expand:"block",type:"submit",disabled:x||f.length!==6,children:x?"CHECKING...":"RECOVER ACCOUNT"})]}):e.jsxs("form",{onSubmit:I,noValidate:!0,className:"member-login-form",children:[e.jsx("p",{className:"member-login-status",children:"Use the name and phone number already saved on your account."}),e.jsxs("label",{className:"member-login-field",children:[e.jsx("span",{className:"member-login-label",children:"First name"}),e.jsx("input",{className:"member-login-input",autoComplete:"given-name",value:n,onChange:M=>a(M.target.value),disabled:x})]}),e.jsxs("label",{className:"member-login-field",children:[e.jsx("span",{className:"member-login-label",children:"Last name"}),e.jsx("input",{className:"member-login-input",autoComplete:"family-name",value:i,onChange:M=>o(M.target.value),disabled:x})]}),e.jsxs("label",{className:"member-login-field",children:[e.jsx("span",{className:"member-login-label",children:"Phone number"}),e.jsx("input",{className:"member-login-input",type:"tel",autoComplete:"tel",value:l,onChange:M=>c(M.target.value),disabled:x})]}),v?e.jsx("p",{className:"member-login-error",children:v}):null,e.jsx(vt,{className:"member-login-submit",expand:"block",type:"submit",disabled:x,children:x?"SENDING...":"SEND RECOVERY CODE"})]}),e.jsx("button",{type:"button",className:"member-login-forgot",onClick:()=>t.replace("/login"),disabled:x,children:"Back to sign in"})]})}function bg(t){return`${t.childFirstName} ${t.childLastName}`.trim()||"Child"}function fg(t){return t.currentBelt?t.currentBelt.label||t.currentBelt.colourKey||"Current belt":"Not graded yet"}function gg(){const t=T.tenant.getTenantTimezone(),[s,n]=r.useState(null),[a,i]=r.useState([]),[o,l]=r.useState("self"),[c,u]=r.useState(!0),[d,h]=r.useState(""),m=r.useCallback(async N=>{u(!0),h("");try{const[x,k]=await Promise.all([T.me.getProfile({signal:N}),T.me.listDependants({signal:N}).catch(()=>[])]);n(x),i(k)}catch(x){const k=re(x,"Unable to load progress details.");k&&h(k)}finally{u(!1)}},[]);r.useEffect(()=>{const N=new AbortController;return m(N.signal),()=>{N.abort()}},[m]);const f=s?.member??null,b=ka(f),p=r.useMemo(()=>{const N=[{value:"self",label:"Me",isSelf:!0}];if(!b)return N;for(const x of a)N.push({value:x.id,label:bg(x),isSelf:!1});return N},[b,a]);r.useEffect(()=>{p.some(N=>N.value===o)||l("self")},[o,p]);const g=o==="self",v=f?.gradingSummary??[];return e.jsxs(Ye,{standardUI:!0,title:"Training Progress",subtitle:"Programme grading and next targets.",activeTab:"none",backTo:"/training",onRefresh:m,children:[c?e.jsxs("div",{className:"member-panel-loading",children:[e.jsx(Te,{name:"crescent"}),e.jsx("span",{children:"Loading progress..."})]}):null,!c&&d?e.jsx("div",{className:"member-panel-error",children:d}):null,!c&&!d?e.jsxs(e.Fragment,{children:[p.length>1?e.jsx(Hn,{value:o,className:"member-tab-switch",onIonChange:N=>{const x=`${N.detail.value??""}`;x&&l(x)},children:p.map(N=>e.jsx(Ps,{value:N.value,children:e.jsx("span",{children:N.label})},N.value))}):null,g?e.jsxs("section",{className:"member-panel-card",children:[e.jsxs("div",{className:"member-row-main",children:[e.jsx("h2",{children:"Programme progress"}),e.jsx(V,{icon:Jr})]}),v.length===0?e.jsx("p",{children:"No grading progress recorded yet."}):null,v.length>0?e.jsx("div",{className:"member-panel-list member-list--divided",children:v.map(N=>e.jsxs("div",{className:"member-panel-row",children:[e.jsxs("div",{className:"member-row-main",children:[e.jsx("strong",{children:N.program.name}),e.jsx("span",{className:"member-pill is-accent",children:fg(N)})]}),e.jsxs("p",{children:["Stripes: ",N.currentStripeCount]}),e.jsxs("p",{children:["Last update: ",gs(N.lastUpdatedAt,t)]})]},N.program.uuid))}):null]}):e.jsxs("section",{className:"member-panel-card",children:[e.jsx("h2",{children:"Child progress"}),e.jsx("p",{children:"This child progress area is under construction and will be active soon."})]})]}):null]})}function xg(){const t=mt();return r.useMemo(()=>{const s=new URLSearchParams(t.search);return{key:s.get("key")?.trim()??"",login:s.get("login")?.trim()??""}},[t.search])}function jg(){const t=tt(),{key:s,login:n}=xg(),[a,i]=r.useState(""),[o,l]=r.useState(""),[c,u]=r.useState(!1),[d,h]=r.useState(""),[m,f]=r.useState(""),[b,p]=r.useState(!1),g=s!==""&&n!=="",v=()=>g?!a||!o?(h("Enter your new password in both fields."),!1):a.length<8?(h("New password must be at least 8 characters."),!1):a!==o?(h("Passwords do not match."),!1):(h(""),!0):(h("That password reset link is invali
2d or expired."),!1),N=async x=>{if(x.preventDefault(),f(""),!!v())try{p(!0),await T.auth.resetPassword({key:s,login:n,password:a,passwordConfirm:o}),t.replace("/login?reset=1")}catch(k){k instanceof cn||k instanceof Error?f(k.message):f("Unable to update your password right now.")}finally{p(!1)}};return e.jsxs(mr,{children:[e.jsxs("form",{onSubmit:N,noValidate:!0,className:"member-login-form",children:[e.jsxs("label",{className:"member-login-field",children:[e.jsx("span",{className:"member-login-label",children:"New Password"}),e.jsxs("span",{className:"member-login-password-input-wrap",children:[e.jsx("input",{type:c?"text":"password",className:"member-login-password-input",autoComplete:"new-password",value:a,onChange:x=>i(x.target.value),disabled:b||!g}),e.jsx("button",{type:"button",className:"member-login-password-toggle",onClick:()=>u(x=>!x),"aria-label":c?"Hide password":"Show password",disabled:b||!g,children:e.jsx(V,{icon:c?Hr:ar})})]})]}),e.jsxs("label",{className:"member-login-field",children:[e.jsx("span",{className:"member-login-label",children:"Confirm Password"}),e.jsxs("span",{className:"member-login-password-input-wrap",children:[e.jsx("input",{type:c?"text":"password",className:"member-login-password-input",autoComplete:"new-password",value:o,onChange:x=>l(x.target.value),disabled:b||!g}),e.jsx("button",{type:"button",className:"member-login-password-toggle",onClick:()=>u(x=>!x),"aria-label":c?"Hide password":"Show password",disabled:b||!g,children:e.jsx(V,{icon:c?Hr:ar})})]})]}),d?e.jsx("p",{className:"member-login-error",children:d}):null,m?e.jsx("p",{className:"member-login-error",children:m}):null,e.jsx(vt,{className:"member-login-submit",expand:"block",type:"submit",disabled:b||!g,children:b?"UPDATING...":"UPDATE PASSWORD"})]}),e.jsx("button",{type:"button",className:"member-login-forgot",onClick:()=>t.replace("/login"),disabled:b,children:"Back to sign in"})]})}const yg={uuid:"",title:"",description:"",type:"external_link",url:"",published:!1,sectionUuid:"",pendingFile:null,ruleMode:"allow_all",originalRuleMode:"",ruleConfig:{}};function Ml(t,s,n){const a=[...t],[i]=a.splice(s,1);return i!==void 0&&a.splice(n,0,i),a}function vg({isOpen:t,onDismiss:s,onChanged:n}){const[a,i]=r.useState(null),[o,l]=r.useState(null),[c,u]=r.useState(null),[d,h]=r.useState(null),[m,f]=r.useState(null),[b,p]=r.useState(!1),[g,v]=r.useState(!1),[N,x]=r.useState(""),[k,j]=r.useState(20),I=r.useCallback(async()=>{p(!0),x("");try{const[w,_]=await Promise.all([T.resources.getManagedInstructorHub(),T.resources.getUploadLimits()]);i(w),j(_.videoMb)}catch(w){x(re(w,"Unable to load the Instructor Hub."))}finally{p(!1)}},[]);r.useEffect(()=>{t&&I()},[t,I]);const S=r.useMemo(()=>a?[...a.sections.flatMap(w=>w.resources),...a.unsectioned]:[],[a]);async function M(w,_){v(!0),x("");try{const[W,H]=await Promise.all([T.resources.listManagedMedia(w.uuid),T.resources.getManagedAccessRule(w.uuid)]),ne=W[0];l({uuid:w.uuid,title:w.title,description:w.description||"",type:w.type,url:ne?.embedUrl||ne?.externalUrl||"",published:w.status==="published",sectionUuid:_,pendingFile:null,ruleMode:H.ruleMode,originalRuleMode:H.ruleMode,ruleConfig:H.rules})}catch(W){x(re(W,"Unable to open this resource."))}finally{v(!1)}}async function y(){if(!o?.title.trim()){x("Add a resource title.");return}if(o.url&&!/^https:\/\//i.test(o.url)){x("Use a secure https URL.");return}if(o.type==="private_media"&&!o.pendingFile&&!o.uuid){x("Choose a video to upload.");return}v(!0),x("");try{const w={title:o.title.trim(),description:o.description.trim()||null,type:o.type,status:o.published?"published":"draft",placement:"hub",category_uuid:null,audience:"inherit",sort_order:S.length+1},_=o.uuid?await T.resources.updateManagedResource(o.uuid,w):await T.resources.createManagedResource(w),W=o.uuid?await T.resources.listManagedMedia(_.uuid):[],H=o.pendingFile?await T.resources.uploadManagedFile(o.pendingFile,o.type==="private_media"?"resource_video":"document"):null,ne=H?.url||o.url.trim(),K=W[0]?.embedUrl||W[0]?.externalUrl||"";
2(H||ne!==K)&&(ne&&(o.type==="private_media"&&H?.s3Key?await T.resources.attachManagedMedia(_.uuid,{provider:"s3",s3_key:H.s3Key,mime_type:H.mimeType,size_bytes:H.sizeBytes,thumbnail_url:H.thumbnailUrl}):o.type==="video_embed"?await T.resources.attachManagedMedia(_.uuid,{provider:/vimeo/i.test(ne)?"vimeo":"youtube",embed_url:ne}):await T.resources.attachManagedMedia(_.uuid,{provider:"external",external_url:ne,mime_type:H?.mimeType,size_bytes:H?.sizeBytes})),await Promise.all(W.map(ye=>T.resources.deleteManagedMedia(_.uuid,ye.uuid)))),await T.resources.setManagedInstructorPlacement(_.uuid,o.sectionUuid||null),await T.resources.setManagedAccessRule(_.uuid,o.ruleMode,o.originalRuleMode===o.ruleMode?o.ruleConfig:{}),l(null),await I(),n()}catch(w){x(re(w,"Unable to save this resource."))}finally{v(!1)}}async function P(){if(d){v(!0);try{await T.resources.removeManagedInstructorPlacement(d.uuid),h(null),await I(),n()}catch(w){x(re(w,"Unable to remove this resource from the Instructor Hub."))}finally{v(!1)}}}async function U(){if(!c?.name.trim()){x("Add a section name.");return}v(!0);try{c.uuid?await T.resources.updateManagedHubSection(c.uuid,c.name.trim()):await T.resources.createManagedHubSection(c.name.trim(),(a?.sections.length||0)+1),u(null),await I(),n()}catch(w){x(re(w,"Unable to save this section."))}finally{v(!1)}}async function F(){if(m){v(!0);try{await T.resources.deleteManagedHubSection(m.uuid),f(null),await I(),n()}catch(w){x(re(w,"Unable to delete this section."))}finally{v(!1)}}}async function A(w){if(!a)return;const _=a,W={...a,sections:Ml(a.sections,w.detail.from,w.detail.to)};w.detail.complete(),i(W);try{await T.resources.saveManagedInstructorLayout(W),n()}catch(H){i(_),x(re(H,"Unable to change section order."))}}async function D(w,_,W){if(!a)return;const H=a,ne=Ml(_,W.detail.from,W.detail.to),K={...a,sections:a.sections.map(ye=>ye.uuid===w?{...ye,resources:ne}:ye),unsectioned:w===null?ne:a.unsectioned};W.detail.complete(),i(K);try{await T.resources.saveManagedInstructorLayout(K),n()}catch(ye){i(H),x(re(ye,"Unable to change resource order."))}}const R=(w,_)=>w.length===0?e.jsx("p",{className:"member-panel-help",children:"No resources in this section."}):e.jsx($o,{disabled:g||w.length<2,onIonItemReorder:W=>{D(_,w,W)},className:"member-panel-list",children:w.map(W=>e.jsxs(pt,{lines:"none",children:[e.jsx(Oo,{slot:"start",className:"instructor-drag-handle",children:e.jsx(V,{icon:Vo})}),e.jsx(yt,{children:e.jsxs("article",{className:"member-panel-row instructor-resource-card",children:[e.jsxs("div",{className:"member-row-main",children:[e.jsx("strong",{children:W.title}),e.jsx("span",{className:"member-pill is-accent",children:gt(W.status)})]}),e.jsx("p",{children:gt(W.type,"Resource")}),e.jsxs("div",{className:"member-list-actions instructor-resource-row-actions",children:[e.jsxs("button",{className:"member-btn",type:"button",onClick:()=>{M(W,_||"")},children:[e.jsx(V,{icon:ai}),"Edit"]}),e.jsx("button",{className:"member-btn is-danger",type:"button",onClick:()=>h(W),children:"Remove"})]})]})})]},W.uuid))});return e.jsxs(at,{isOpen:t,onDidDismiss:s,children:[e.jsxs("div",{className:"member-modal-sheet instructor-resource-manager",children:[e.jsx("nav",{className:"member-modal-nav instructor-resource-nav",children:e.jsx("button",{type:"button","aria-label":"Go back",onClick:s,children:e.jsx(V,{icon:Hs})})}),e.jsxs("header",{className:"member-modal-header",children:[e.jsx("h2",{children:"Manage Instructor Hub"}),e.jsx("p",{children:"Sections and resources here are only for authorised instructors."})]}),N?e.jsx("div",{className:"member-panel-error",children:N}):null,b?e.jsxs("div",{className:"member-panel-loading",children:[e.jsx(Te,{name:"crescent"}),e.jsx("span",{children:"Loading..."})]}):null,b?null:e.jsxs("section",{className:"member-panel-card instructor-resource-management-card",children:[e.jsx($o,{disabled:g||(a?.sections.length||0)<2,onIonItemReorder:w=>{A(w)},className:"instructor-resource-groups",children:a?.sections.map(w=>e.jsxs("section",{className:"instructor-resource-group",children:[e.jsxs("div",{className:"instructor-resource-group-header",children:[e.jsx(Oo,{className:"instructor-drag-handle",children:e.jsx(V,{icon:Vo})}),e.jsx("h3",{children:w.name}),e.jsxs("div",{className:"instructor-resource-category-actions",children:[e.jsx("button",{type:"button",onClick:()=>u({uuid:w.uuid,name:w.name}),children:"Edit"}),e.jsx("button",{type:"button",onClick:()=>f({uuid:w.uuid,name:w.name}),children:"Delete"})]})]}),R(w.resources,w.uuid)]},w.uuid))}),e.jsxs("section",{className:"instructor-resource-group",children:[e.jsx("div",{className:"instructor-resource-group-header",children:e.jsx("h3",{children:"No section"})}),R(a?.unsectioned||[],null)]}),e.jsxs("div",{className:"instructor-resource-footer-actions",children:[e.jsxs("button",{className:"member-btn is-solid",type:"button",onClick:()=>l({...yg}),children:[e.jsx(V,{icon:Yi}),"Add resource"]}),e.jsxs("button",{className:"member-btn",type:"button",onClick:()=>u({uuid:"",name:""}),children:[e.jsx(V,{icon:Yi}),"Add section"]})]})]})]}
2),e.jsx(at,{isOpen:o!==null,onDidDismiss:()=>l(null),children:e.jsxs("div",{className:"member-modal-sheet instructor-resource-form",children:[e.jsx("nav",{className:"member-modal-nav instructor-resource-nav",children:e.jsx("button",{type:"button","aria-label":"Go back",onClick:()=>l(null),disabled:g,children:e.jsx(V,{icon:Hs})})}),e.jsx("header",{className:"member-modal-header",children:e.jsx("h2",{children:o?.uuid?"Edit resource":"Add resource"})}),e.jsxs("div",{className:"member-form-fields",children:[e.jsx(Bt,{label:"Title",value:o?.title||"",onChange:w=>l(_=>_&&{..._,title:w})}),e.jsx(vn,{label:"Description",value:o?.description||"",onChange:w=>l(_=>_&&{..._,description:w})}),e.jsx(rs,{label:"Type",value:o?.type||"external_link",onChange:w=>l(_=>_&&{..._,type:w,pendingFile:null,url:""}),options:[{value:"external_link",label:"External link"},{value:"video_embed",label:"Embedded video"},{value:"document",label:"Document"},{value:"private_media",label:"Hosted video"}]}),e.jsx(rs,{label:"Section",helpText:"Hub access is fixed. This only controls organisation.",value:o?.sectionUuid||"",onChange:w=>l(_=>_&&{..._,sectionUuid:w}),options:[{value:"",label:"No section"},...(a?.sections||[]).map(w=>({value:w.uuid,label:w.name}))]}),o?.type==="private_media"||o?.type==="document"?e.jsx(Au,{label:o.type==="private_media"?"Video file":"Document",hint:o.type==="private_media"?`MP4, WebM or MOV, up to ${k} MB`:"PDF or image, up to 12 MB",accept:o.type==="private_media"?"video/mp4,video/webm,video/quicktime":"application/pdf,image/jpeg,image/png,image/webp",camera:!1,onFiles:w=>l(_=>_&&{..._,pendingFile:w[0]||null,url:""})}):e.jsx(Bt,{label:o?.type==="video_embed"?"Video URL":"URL",type:"url",inputMode:"url",value:o?.url||"",onChange:w=>l(_=>_&&{..._,url:w})}),e.jsxs(pt,{className:"member-toggle-row instructor-resource-toggle",lines:"none",children:[e.jsxs(yt,{children:[e.jsx("h3",{children:"Published"}),e.jsx("p",{children:"Draft resources are hidden from instructors"})]}),e.jsx(js,{slot:"end",checked:o?.published||!1,onIonChange:w=>l(_=>_&&{..._,published:w.detail.checked})})]}),e.jsxs("details",{children:[e.jsx("summary",{children:"Advanced availability"}),e.jsx(rs,{label:"Rule",value:o?.ruleMode||"allow_all",onChange:w=>l(_=>_&&{..._,ruleMode:w}),options:[{value:"allow_all",label:"No extra restriction"},{value:"staff_only",label:"Staff only"},{value:"members_only",label:"Active members only"},{value:"trials_only",label:"Active trials only"}]})]})]}),e.jsxs("div",{className:"instructor-resource-form-actions",children:[e.jsx("button",{className:"member-btn is-neutral",type:"button",onClick:()=>l(null),children:"Cancel"}),e.jsx("button",{className:"member-btn is-solid",disabled:g,type:"button",onClick:()=>{y()},children:g?"Saving...":"Save resource"})]})]})}),e.jsx(at,{isOpen:c!==null,onDidDismiss:()=>u(null),children:e.jsxs("div",{className:"member-modal-sheet instructor-resource-form",children:[e.jsx("nav",{className:"member-modal-nav instructor-resource-nav",children:e.jsx("button",{type:"button","aria-label":"Go back",onClick:()=>u(null),children:e.jsx(V,{icon:Hs})})}),e.jsx("header",{className:"member-modal-header",children:e.jsx("h2",{children:c?.uuid?"Edit section":"Add section"})}),e.jsx("div",{className:"member-form-fields",children:e.jsx(Bt,{label:"Name",value:c?.name||"",onChange:w=>u(_=>_&&{..._,name:w})})}),e.jsxs("div",{className:"instructor-resource-form-actions",children:[e.jsx("button",{className:"member-btn is-neutral",type:"button",onClick:()=>u(null),children:"Cancel"}),e.jsx("button",{className:"member-btn is-solid",disabled:g,type:"button",onClick:()=>{U()},children:g?"Saving...":"Save section"})]})]})}),e.jsx(ho,{isOpen:d!==null,title:"Remove from Instructor Hub?",message:`${d?.title||"This resource"} will stay in the Resource Catalog and any other placements.`,confirmLabel:"Remove",busy:g,onCancel:()=>h(null),onConfirm:()=>{P()}}),e.jsx(ho,{isOpen:m!==null,title:"Delete section?",message:`Resources in ${m?.name||"this section"} will move to No section in the Instructor Hub.`,confirmLabel:"Delete",busy:g,onCancel:()=>f(null),onConfirm:()=>{F()}})]})}const Oi={member:{title:"Member Hub",subtitle:"Training guides, videos, FAQs and resources for members."},parent:{title:"Parent Hub",subtitle:"Guides, videos, FAQs and resources for parents."},instructor:{title:"Instructor Hub",subtitle:"Teaching guides, lesson resources and useful links for instructors."}};function Bi({hub:t}){const{user:s}=Ge(),n=t==="instructor"&&Qe(s),a=T.tenant.getTenantTimezone(),[i,o]=r.useState("resources"),[l,c]=r.useState([]),[u,d]=r.useState(null),[h,m]=r.useState([]),[f,b]=r.useState(null),[p,g]=r.useState(null),[v,N]=r.useState(!0),[x,k]=r.useState(!1),[j,I]=r.useState(""),[S,M]=r.useState(""),[y,P]=r.useState(""),[U,F]=r.useState(""),[A,D]=r.useState(!1),[R,w]=r.useState("all"),[_,W]=r.useState(""),[H,ne]=r.useState(0),[K,ye]=r.useState(""),de=r.useRef(0),[O,L]=r.useState({}),[Z,ce]=r.useState(""),me=r.useRef({});r.useEffect(()=>()=>{de.current+=1},[t]);const Ne=r.useCallback(async ue=>{N(!0),I(""),M("");const[Se,pe]=await Promise.allSettled([T.resources.getHub(t,{signal:ue}),T.quickLinks.listQuickLinks({signal:ue})]);if(ue?.aborted)return;const ae=Se.status==="fulfilled"?Se.value:null;d(ae),c(ae?[...ae.sections.flatMap(ge=>ge.resources),...ae.unsectioned]:[]),m(pe.status==="fulfilled"?pe.value.data:[]),Se.status==="rejected"&&pe.status==="rejected"?I(re(Se.reason,"Unable to load resources or useful links.")):Se.status==="rejected"?(M("Library resources are unavailable. Your Useful Links are still available."),o("links")):pe.status==="rejected"&&M("Useful Links are unavailable. Library resources are still available."),N(!1)},[t]);r.useEffect(()=>{const ue=new AbortController;return Ne(ue.signal),()=>{ue.abort()}},[Ne]);const ve=r.useMemo(()=>h.flatMap(Se=>Se.items.map(pe=>({uuid:pe.uuid,label:pe.label,url:pe.url}))),[h]),xe=r.useMemo(()=>
2{if(!u)return[];const ue=u.sections.map(pe=>[pe.name,pe.resources]);u.unsectioned.length>0&&ue.push(["Other resources",u.unsectioned]);const Se=_.trim().toLocaleLowerCase();return ue.filter(([pe])=>R==="all"||pe===R).map(([pe,ae])=>[pe,ae.filter(ge=>!Se||`${ge.title} ${ge.description||""} ${pe}`.toLocaleLowerCase().includes(Se))]).filter(([,pe])=>pe.length>0)},[u,R,_]),G=l,J=r.useMemo(()=>u?[...u.sections.map(ue=>ue.name),...u.unsectioned.length>0?["Other resources"]:[]]:[],[u]);async function ke(ue){const Se=++de.current;b(null),ye(""),L({}),ce(""),ne(0),me.current={},g(ue),k(!0);try{const pe=await T.resources.getResource(ue,{hub:t});Se===de.current&&b(pe)}catch{Se===de.current&&ye("Unable to load this resource. Please try again.")}finally{Se===de.current&&k(!1)}}async function Be(ue,Se){const pe=await Gn(Se);P(pe?`${ue} link copied.`:"Unable to copy this link on this device.")}async function fe(ue){if(!f||Z)return;const Se=de.current;ce(ue);try{const pe=await T.resources.getResourceSignedUrl(f.resource.uuid,ue,{hub:t});if(!pe)throw new Error("No video link was returned.");Se===de.current&&L(ae=>({...ae,[ue]:pe}))}catch{Se===de.current&&P("Unable to open this media right now. Please try again.")}finally{Se===de.current&&ce("")}}function Ae(ue,Se){if(!f)return;const pe=me.current[ue]??0,ae=Math.floor(Se/30)*30;if(ae<=pe)return;const ge=Math.min(300,ae-pe);me.current[ue]=ae,T.resources.recordResourceViewing(f.resource.uuid,ge,{hub:t}).catch(()=>{})}function lt(){de.current+=1,g(null),b(null),L({}),ce(""),k(!1),ye("")}const be=f?.media[H],We=f?.resource.type==="image"||be?.mimeType?.startsWith("image/"),Fe=f?.resource.type==="video_embed"||be?.mimeType?.startsWith("video/")||f?.resource.type==="private_media"&&!be?.mimeType,Ke=be?O[be.uuid]||(f?.resource.type==="private_media"&&be.provider==="s3"?null:be.externalUrl||be.embedUrl):null;return e.jsxs(Ye,{standardUI:!0,title:Oi[t].title,subtitle:Oi[t].subtitle,activeTab:"none",onRefresh:Ne,children:[n?e.jsx("div",{className:"member-page-primary-action",children:e.jsxs("button",{type:"button",className:"member-btn is-solid",onClick:()=>D(!0),children:[e.jsx(V,{icon:ai}),"Manage resources"]})}):null,e.jsxs("div",{className:"member-tab-switch",role:"tablist","aria-label":`${Oi[t].title} content`,children:[e.jsx("button",{type:"button",role:"tab","aria-selected":i==="resources",className:i==="resources"?"is-active":"",onClick:()=>o("resources"),children:"Resources"}),e.jsx("button",{type:"button",role:"tab","aria-selected":i==="links",className:i==="links"?"is-active":"",onClick:()=>o("links"),children:"Useful Links"})]}),v?e.jsxs("div",{className:"member-panel-loading",children:[e.jsx(Te,{name:"crescent"}),e.jsx("span",{children:"Loading resources..."})]}):null,!v&&j?e.jsx("div",{className:"member-panel-error",children:j}):null,!v&&!j&&S?e.jsx("section",{className:"member-panel-card",children:e.jsx("p",{className:"member-panel-help",children:S})}):null,!v&&!j&&i==="resources"?e.jsxs("section",{className:"member-section",children:[e.jsx(on,{className:"resource-search",ariaLabel:"Search resources",placeholder:"Search videos, images and guides",value:_,onChange:W}),J.length>1?e.jsxs("div",{className:"member-category-filter",children:[e.jsx("button",{type:"button",className:R==="all"?"is-active":"",onClick:()=>w("all"),children:"All sections"}),J.map(ue=>e.jsx("button",{type:"button",className:R===ue?"is-active":"",onClick:()=>w(ue),children:ue},ue))]}):null,G.length===0?e.jsxs("div",{className:"resource-empty",children:[e.jsx(V,{icon:wr}),e.jsx("h2",{children:"Your library is empty"}),e.jsx("p",{children:"Resources shared with you will appear here."})]}):null,G.length>0&&xe.length===0?e.jsxs("div",{className:"resource-empty",children:[e.jsx("h2",{children:"No matching resources"}),e.jsx("p",{children:"Try a different search or section."}),e.jsx("button",{type:"button",className:"member-btn",onClick:()=>{W(""),w("all")},children:"Clear filters"})]}):null,G.length>0?xe.map(([ue,Se])=>e.jsxs("div",{className:"member-resource-group",children:[e.jsx("h3",{children:ue}),e.jsx("div",{className:"resource-gallery",children:Se.map(pe=>e.jsxs("button",{type:"button",className:"resource-tile",onClick:()=>{ke(pe.uuid)},"aria-label":`Open ${pe.title||"resource"}`,children:[e.jsxs("span",{className:"resource-thumbnail",children:[e.jsx(V,{className:"resource-thumbnail-fallback",icon:pe.type==="image"?wr:pe.type==="video_embed"||pe.type==="private_media"?wi:Wr,"aria-hidden":"true"}),pe.thumbnailUrl?e.jsx("img",{src:pe.thumbnailUrl,alt:"",loading:"lazy",onError:ae=>{ae.currentTarget.hidden=!0}}):null,e.jsx("span",{className:"resource-type",children:pe.type==="image"?"Image":pe.type==="video_embed"?"Video":pe.type==="private_media"?"Media":pe.type==="external_link"?"Link":"Guide"})]}),e.jsx("span",{className:"resource-tile-title",children:pe.title||"Resource"}),pe.description?e.jsx("span",{className:"resource-tile-description",children:pe.description}):null,pe.updatedAt?e.jsxs("span",{className:"resource-tile-date",children:["Updated ",gs(pe.updatedAt,a)]}):null]},pe.uuid))})]},ue)):null]}):null,!v&&!j&&i==="links"?e.jsxs("section",{className:"member-section",children:[e.jsx("h2",{children:"Useful Links"}),ve.length===0?e.jsxs("div",{className:"resource-empty",children:[e.jsx(V,{icon:Vs}),e.jsx("h3",{children:"No links yet"}),e.jsx("p",{children:"Useful links from your school will appear here."}),e.jsx("button",{type:"button",className:"member-btn",onClick:()=>o("resources"),children:"Browse resources"})]}):null,ve.length>0?e.jsx("div",{className:"member-panel-list member-list--divided",children:ve.map(ue=>e.jsxs("article",{className:"member-panel-row",children:[e.jsx("strong",{children:ue.label}),e.jsxs("div",{className:"member-list-actions staff-sales-link-actions",children:[e.jsxs("button",{type:"button",className:"member-btn",onClick:()=>Ks(ue.url),children:[e.jsx(V,{icon:Vs})," Open"]}),e.jsxs("button",{type:"button",className:"member-btn is-solid",onClick:()=>{Be(ue.label,ue.url)},children:[e.jsx(V,{icon:kn})," Copy"]}),e.jsx("button",{type:"button",className:"member-btn is-icon-only",onClick:()=>F(Se=>Se===ue.uuid?"":ue.uuid),"aria-label":U===ue.uuid?`Hide QR code for ${ue.label}`:`Show QR code for ${ue.label}`,"aria-expanded":U===ue.uuid,title:U===ue.uuid?"Hide QR code":"Show QR code",children:e.jsx(V,{icon:ja})})]}),U===ue.uuid?e.jsxs("div",{className:"staff-sales-link-qr",children:[e.jsx("img",{src:ya(ue.url,240),alt:`QR code for ${ue.label}`}),e.jsx("span",{children:"Scan to open this link."})]}):null]},ue.uuid))}):null]}):null,e.jsx(at,{className:"resource-viewer-modal",isOpen:p!==null,onDid
2Dismiss:lt,children:e.jsxs("div",{className:"resource-viewer",children:[e.jsxs("header",{className:"resource-viewer-toolbar",children:[e.jsxs("button",{type:"button",onClick:lt,"aria-label":"Close resource viewer",children:[e.jsx(V,{icon:jc}),"Back to library"]}),f&&f.media.length>1?e.jsxs("span",{children:[H+1," / ",f.media.length]}):null]}),e.jsxs("div",{className:"resource-viewer-scroll",children:[x?e.jsxs("div",{className:"member-panel-loading",children:[e.jsx(Te,{name:"crescent"}),e.jsx("span",{children:"Loading resource..."})]}):null,K?e.jsxs("div",{className:"resource-empty",role:"alert",children:[e.jsx("h2",{children:"Resource unavailable"}),e.jsx("p",{children:K}),e.jsx("button",{type:"button",className:"member-btn",onClick:()=>p&&void ke(p),children:"Try again"})]}):null,!x&&f?e.jsxs("section",{children:[be?e.jsxs("div",{className:"resource-media-stage",children:[f.resource.type==="video_embed"&&be.embedUrl?e.jsx("iframe",{src:be.embedUrl,title:f.resource.title,allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0}):null,We&&Ke?e.jsx("img",{src:Ke,alt:f.resource.title,onError:()=>P("This image could not be loaded. Please reopen the resource to try again.")}):null,Fe&&f.resource.type!=="video_embed"&&Ke?e.jsx("video",{controls:!0,playsInline:!0,autoPlay:!0,preload:"metadata","aria-label":f.resource.title,src:Ke,poster:be.thumbnailUrl||void 0,onError:()=>{L(ue=>{const Se={...ue};return delete Se[be.uuid],Se}),P("This video could not be loaded. Please try again.")},onTimeUpdate:ue=>Ae(be.uuid,ue.currentTarget.currentTime)}):null,f.resource.type==="private_media"&&be.provider==="s3"&&!Ke?be.processing?.status==="failed"?e.jsx("p",{role:"status",children:"This media could not be prepared. Please contact the school."}):be.processing?.status&&be.processing.status!=="ready"?e.jsx("p",{role:"status",children:"This media is being prepared. Please check back shortly."}):e.jsxs("button",{type:"button",className:"resource-play",onClick:()=>{fe(be.uuid)},disabled:!!Z,children:[be.thumbnailUrl?e.jsx("img",{src:be.thumbnailUrl,alt:""}):null,e.jsxs("span",{children:[e.jsx(V,{icon:Fe?wi:We?wr:Wr}),Z?"Opening...":Fe?"Play video":"View media"]})]}):null,!We&&!Fe&&Ke?e.jsxs("button",{type:"button",className:"member-btn",onClick:()=>Ks(Ke),children:[e.jsx(V,{icon:Vs}),"Open ",f.resource.type==="external_link"?"link":"document"]}):null]},be.uuid):e.jsx("div",{className:"resource-empty",children:e.jsx("p",{children:"No media is attached to this resource."})}),e.jsxs("div",{className:"resource-viewer-details",children:[e.jsx("h1",{children:f.resource.title||"Resource"}),f.resource.updatedAt?e.jsxs("p",{className:"resource-tile-date",children:["Updated ",gs(f.resource.updatedAt,a)]}):null,f.resource.description?e.jsx("p",{children:f.resource.description}):null,f.media.length>1?e.jsx("nav",{className:"resource-media-picker","aria-label":"Resource media",children:f.media.map((ue,Se)=>e.jsxs("button",{type:"button","aria-pressed":H===Se,onClick:()=>ne(Se),children:[ue.thumbnailUrl?e.jsx("img",{src:ue.thumbnailUrl,alt:""}):e.jsx(V,{icon:ue.mimeType?.startsWith("image/")?wr:wi}),e.jsxs("span",{children:["Media ",Se+1]})]},ue.uuid))}):null]})]}):null]})]})}),e.jsx(Dt,{isOpen:!!y,message:y,duration:2200,onDidDismiss:()=>P("")}),n?e.jsx(vg,{isOpen:A,onDismiss:()=>D(!1),onChanged:()=>{Ne()}}):null]})}function Ng(){const t=tt(),{user:s}=Ge(),{appearance:n}=ln(),[a,i]=r.useState(null),[o,l]=r.useState(null),[c,u]=r.useState(()=>Xa()),[d,h]=r.useState(!0),[m,f]=r.useState(!1),[b,p]=r.useState(""),[g,v]=r.useState(""),[N,x]=r.useState(()=>Ld()),[k,j]=r.useState(null),[I,S]=r.useState([]),M=$c(),y=s?.accessPolicy?.memberExperienceMode==="booking_beta",P=Xt(s),U=r.useCallback(async R=>{h(!0),p("");try{const[w,_,W,H]=await Promise.all([T.me.getPreferences({signal:R}).catch(()=>null),M?T.chatPush.getSettings({signal:R}).catch(()=>null):Promise.resolve(null),P&&(s?.featureFlags?.strengthTrackingEnabled||s?.featureFlags?.curriculumTrackingEnabled||s?.featureFlags?.strengthLeaderboardsEnabled)?T.training.getPreferences(R).catch(()=>null):Promise.resolve(null),P&&s?.featureFlags?.curriculumTrackingEnabled?T.curriculum.listPrograms({signal:R,includeHidden:!0}).catch(()=>null):Promise.resolve(null)]);i(w),l(_),j(W?.preferences??null),S(H?.rows??[])}catch(w){const _=re(w,"Unable to load app settings.");_&&p(_)}finally{h(!1)}},[M,P,s?.featureFlags?.curriculumTrackingEnabled,s?.featureFlags?.strengthLeaderboardsEnabled,s?.featureFlags?.strengthTrackingEnabled]);async function F(R,w){if(!(!k||m)){f(!0);try{const _=await T.training.savePreferences(R);j(_),v(w)}catch(_){v(re(_,"Unable to update training settings."))}finally{f(!1)}}}r.useEffect(()=>{const R=new AbortController;return U(R.signal),()=>{R.abort()}},[U]),r.useCallback(R=>{const w=au(R);u(w)},[]);const A=r.useCallback(R=>{x(R),Id(R)},[]);async function D(R,w){if(!(!a||m)){f(!0);try{const _=await T.me.updatePreferences({[R]:w});i(_),v("Email preference saved.")}catch(_){v(re(_,"Unable to update email preference."))}finally{f(!1)}}}
2return o&&o.preference,e.jsxs(Ye,{standardUI:!0,title:"App Settings",subtitle:y?"Choose how the app looks on this device.":"Theme, notifications, and device preferences.",activeTab:"settings",backTo:y?"/timetable":"/account",onRefresh:U,refresherDisabled:m,suppressReadOnlyNotice:!0,suppressInstallPrompt:!0,children:[d?e.jsxs("div",{className:"member-panel-loading",children:[e.jsx(Te,{name:"crescent"}),e.jsx("span",{children:"Loading app settings..."})]}):null,!d&&b?e.jsx("div",{className:"member-panel-error",children:b}):null,!d&&!b?e.jsxs(e.Fragment,{children:[n.modeSupport==="both"?e.jsxs("section",{className:"member-panel-card member-settings-appearance",children:[e.jsx("h2",{children:"Appearance"}),e.jsxs(pt,{className:"member-toggle-row member-setting-info",lines:"none",children:[e.jsx(V,{slot:"start",icon:hm}),e.jsxs(yt,{children:[e.jsx("h3",{children:"Theme"}),e.jsx("p",{children:"Choose how the member app looks on this device."})]})]}),e.jsxs(Hn,{className:"member-compact-segment",value:N,onIonChange:R=>A(R.detail.value||"system"),children:[e.jsx(Ps,{value:"system",children:e.jsx(yt,{children:"System"})}),e.jsx(Ps,{value:"light",children:e.jsx(yt,{children:"Light"})}),e.jsx(Ps,{value:"dark",children:e.jsx(yt,{children:"Dark"})})]})]}):null,e.jsxs("section",{className:"member-panel-card",children:[e.jsxs(pt,{className:"member-toggle-row member-setting-info",lines:"none",children:[e.jsx(V,{slot:"start",icon:yc}),e.jsxs(yt,{children:[e.jsx("h3",{children:"Install the app"}),e.jsx("p",{children:"Add this app to your phone, tablet or computer for faster access."})]})]}),e.jsx("button",{type:"button",className:"member-panel-action",onClick:()=>t.push("/install-app"),children:"View installation steps"})]}),e.jsxs("section",{className:"member-section",children:[e.jsx("h2",{children:"Marketing emails"}),e.jsx("p",{children:"You can stop promotional and follow up emails at any time. Account, payment, booking and safety emails are service messages and are not affected."}),e.jsx("div",{className:"member-panel-list",children:e.jsxs(pt,{className:"member-toggle-row",lines:"none",children:[e.jsx(V,{slot:"start",icon:qn}),e.jsxs(yt,{children:[e.jsx("h3",{children:"Marketing and follow up emails"}),e.jsx("p",{children:"Allow the gym to send offers and follow up campaigns."})]}),e.jsx(js,{slot:"end","aria-label":"Marketing and follow up emails",checked:a?.marketingOptIn??!1,disabled:!a||m,onIonChange:R=>{D("marketingOptIn",R.detail.checked)}})]})})]}),e.jsxs("section",{className:"member-section",children:[e.jsx("h2",{children:"Booking emails"}),e.jsx("p",{children:"Choose which emails you receive when you make changes yourself. Staff updates are always emailed."}),e.jsxs("div",{className:"member-panel-list",children:[e.jsxs(pt,{className:"member-toggle-row",lines:"none",children:[e.jsx(V,{slot:"start",icon:qn}),e.jsxs(yt,{children:[e.jsx("h3",{children:"Booking confirmations"}),e.jsx("p",{children:"Email me when I book a class."})]}),e.jsx(js,{slot:"end","aria-label":"Booking confirmations",checked:a?.selfBookingConfirmationEmails??!0,disabled:!a||m,onIonChange:R=>{D("selfBookingConfirmationEmails",R.detail.checked)}})]}),e.jsxs(pt,{className:"member-toggle-row",lines:"none",children:[e.jsx(V,{slot:"start",icon:qn}),e.jsxs(yt,{children:[e.jsx("h3",{children:"Cancellation confirmations"}),e.jsx("p",{children:"Email me when I cancel my own booking."})]}),e.jsx(js,{slot:"end","aria-label":"Cancellation confirmations",checked:a?.selfBookingCancellationEmails??!0,disabled:!a||m,onIonChange:R=>{D("selfBookingCancellationEmails",R.detail.checked)}})]})]})]}),e.jsxs("section",{className:"member-panel-card",children:[e.jsxs(pt,{className:"member-toggle-row member-setting-info",lines:"none",children:[e.jsx(V,{slot:"start",icon:or}),e.jsxs(yt,{children:[e.jsx("h3",{children:"Connect your AI"}),e.jsx("p",{children:"Use ChatGPT, Claude, Grok, Gemini or another compatible assistant with your SkullSystem account."})]})]}),e.jsx("button",{type:"button",className:"member-panel-action",onClick:()=>t.push("/ai-connections"),children:"View connection options"})]}),e.jsxs("section",{className:"member-panel-card",children:[e.jsx("h2",{children:"Service reminders"}),e.jsx("p",{children:"Manage one way class, trial, payment, form and progress reminders for this device."}),e.jsx("button",{type:"button",className:"member-panel-action",onClick:()=>t.push("/notifications"),children:"Manage notifications"})]}),y?null:e.jsxs("section",{className:"member-section",children:[e.jsx("h2",{children:"Notifications"}),e.jsx("p",{children:"Messages are not enabled for this account."}),null]}),P&&k?e.jsxs("section",{className:"member-section",children:[e.jsx("h2",{children:"Training"}),e.jsxs("div",{className:"member-panel-list",children:[s?.featureFlags?.strengthTrackingEnabled?e.jsxs(pt,{className:"member-toggle-row",lines:"none",children:[e.jsxs(yt,{children:[e.jsx("h3",{children:"Show Strength Tracker"}),e.jsx("p",{children:"Hide this if you do not use strength tracking."})]}),e.jsx(js,{slot:"end",checked:k.show_strength_tracker,disabled:m,onIonChange:R=>{F({show_strength_tracker:R.detail.checked},"Strength Tracker preference saved.")}})]}
2):null,s?.featureFlags?.strengthLeaderboardsEnabled?e.jsxs(pt,{className:"member-toggle-row",lines:"none",children:[e.jsxs(yt,{children:[e.jsx("h3",{children:"Join strength leaderboards"}),e.jsx("p",{children:"Only staff verified benchmark results are shown. Your name appears as first name and last initial."})]}),e.jsx(js,{slot:"end",checked:k.leaderboard_opt_in,disabled:m,onIonChange:R=>{F({leaderboard_opt_in:R.detail.checked},"Leaderboard preference saved.")}})]}):null,I.map(R=>{const w=!k.hidden_programme_uuids.includes(R.uuid);return e.jsxs(pt,{className:"member-toggle-row",lines:"none",children:[e.jsxs(yt,{children:[e.jsxs("h3",{children:["Show ",R.name]}),e.jsx("p",{children:"Hide this curriculum from your app only."})]}),e.jsx(js,{slot:"end",checked:w,disabled:m,onIonChange:_=>{const W=_.detail.checked?k.hidden_programme_uuids.filter(H=>H!==R.uuid):[...new Set([...k.hidden_programme_uuids,R.uuid])];F({hidden_programme_uuids:W},"Curriculum preference saved.")}})]},R.uuid)})]})]}):null]}):null,e.jsx(Dt,{isOpen:!!g,message:g,duration:2300,onDidDismiss:()=>v("")})]})}function kg({value:t,onChange:s,disabled:n}){const[a,i]=r.useState(!1),[o,l]=r.useState(""),c=r.useRef(null),u=r.useRef(t);u.current=t;const d=r.useRef(s);d.current=s;const h=window,m=h.SpeechRecognition||h.webkitSpeechRecognition;if(r.useEffect(()=>()=>{c.current&&(c.current.onresult=null,c.current.onend=null,c.current.onerror=null,c.current.abort())},[]),r.useEffect(()=>{n&&c.current?.stop()},[n]),!m||!window.isSecureContext)return e.jsx("p",{className:"member-form-note",children:"You can also use your phone keyboard microphone to dictate."});function f(){if(a){c.current?.stop();return}const b=new m;c.current=b,b.lang=navigator.language||"en-GB",b.continuous=!1,b.interimResults=!1,b.onresult=p=>{for(let g=p.resultIndex;g<p.results.length;g++){const v=p.results[g];v.isFinal&&v[0]?.transcript&&(u.current=`${u.current.trim()} ${v[0].transcript}`.trim().slice(0,6e3),d.current(u.current))}},b.onend=()=>i(!1),b.onerror=()=>{i(!1),l("Dictation could not continue. You can keep typing or use the keyboard microphone.")};try{l(""),b.start(),i(!0)}catch{l("Microphone unavailable. You can keep typing.")}}return e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",className:"member-btn is-neutral",disabled:n,"aria-pressed":a,onClick:f,children:a?"Stop dictation":"Dictate"}),o?e.jsx("p",{role:"status",children:o}):null]})}function wg(){const{user:t}=Ge(),s=mt(),n=tt(),a=Gs(t),[i,o]=r.useState("plan"),[l,c]=r.useState(""),[u,d]=r.useState([]),[h,m]=r.useState([]),[f,b]=r.useState([]),[p,g]=r.useState({edit:!1,templates:!1,chat:!1}),[v,N]=r.useState(null),[x,k]=r.useState(!0),[j,I]=r.useState(!1),[S,M]=r.useState(""),[y,P]=r.useState(""),{value:U,setValue:F,isHydrated:A,flush:D}=Xn({pageKey:`class-plans:${s.search}`,initialValue:{draft:null,saved:""},enabled:a,debounceMs:0,maxAgeMs:1440*60*1e3}),{draft:R,saved:w}=U,_=B=>F(Y=>({...Y,draft:typeof B=="function"?B(Y.draft):B})),W=B=>F(Y=>({...Y,saved:B}));r.useEffect(()=>()=>{D()},[D]);const[H,ne]=r.useState(0),[K,ye]=r.useState("plan"),[de,O]=r.useState(""),[L,Z]=r.useState([]),[ce,me]=r.useState(null),[Ne,ve]=r.useState(""),[xe,G]=r.useState(""),[J,ke]=r.useState([]),[Be,fe]=r.useState(""),[Ae,lt]=r.useState(!1),[be,We]=r.useState(""),[Fe,Ke]=r.useState([]),[ue,Se]=r.useState(null),pe=r.useRef(0),ae=!!R&&JSON.stringify(R)!==w,ge=p.edit&&!!R?.can_edit;function qe(B){M(B instanceof Error?B.message:"Unable to complete this action.")}async function Me(B){I(!0),M(""),P("");try{await B()}catch(Y){qe(Y)}finally{I(!1)}}function Ie(B){_(B),W(JSON.stringify(B)),ne(0),O(""),Z([]),me(null)}function ie(B){ae?Se({title:"Discard unsaved changes?",action:B}):B()}async function Xe(B=0){const Y=++pe.current;k(!0),M("");try{if(i==="activity"){const[oe,Ue]=await Promise.all([ds.activities(l,B),ds.list("plan")]);if(pe.current!==Y)return;g({edit:Ue.can_edit,templates:Ue.can_manage_templates,chat:Ue.can_chat}),m(_e=>B?[..._e,...oe.items]:oe.items),N(oe.next_cursor)}else{const oe=await ds.list(i==="template"?"template":"plan",l,B);if(pe.current!==Y)return;d(Ue=>B?[...Ue,...oe.items]:oe.items),N(oe.next_cursor),g({edit:oe.can_edit,templates:oe.can_manage_templates,chat:oe.can_chat})}}catch(oe){pe.current===Y&&qe(oe)}finally{pe.current===Y&&k(!1)}}r.useEffect(()=>(a&&Xe(),()=>{pe.current++}
2),[i,a]),r.useEffect(()=>{if(!a||!A)return;ds.programmes().then(oe=>b(oe.data)).catch(qe);const B=new URLSearchParams(s.search);if(ye(B.get("mode")==="record"?"record":"plan"),U.draft&&JSON.stringify(U.draft)!==U.saved){P("Your unsaved plan has been restored.");return}const Y=B.get("plan")||B.get("version")||U.draft?.uuid;Y?Me(async()=>Ie(await ds.read(Y))):B.get("programme_uuid")&&Ie(rl(B.get("programme_uuid")))},[a,s.search,A]),r.useEffect(()=>{if(!ae)return;const B=Y=>Y.preventDefault();return window.addEventListener("beforeunload",B),()=>window.removeEventListener("beforeunload",B)},[ae]),r.useEffect(()=>{let B=!0;if(fe(""),ke([]),Ke([]),!!R?.programme_uuid)return lt(!0),ds.classes(R.programme_uuid).then(Y=>{if(B){ke(Y.items);const oe=new URLSearchParams(s.search).get("occurrence_uuid");oe&&Y.items.some(Ue=>Ue.uuid===oe)&&fe(oe)}}).catch(qe).finally(()=>{B&<(!1)}),()=>{B=!1}},[R?.programme_uuid]);function ct(B){_(Y=>Y&&{...Y,...B}),me(null)}function st(B,Y){R&&ct({sections:R.sections.map((oe,Ue)=>Ue===B?{...oe,...Y}:oe)})}function xt(B,Y){R&&_({...R,curriculum_item_uuids:Y?[...new Set([...R.curriculum_item_uuids,B])]:R.curriculum_item_uuids.filter(oe=>oe!==B)})}async function Et(B){R&&await Me(async()=>{const Y=await ds.save({...R,status:B});_(Y),W(JSON.stringify(Y)),P("Class plan saved.")})}async function q(){if(!R||!de.trim())return;const B=[...L,{role:"user",content:de.trim()}];await Me(async()=>{const Y=await ds.chat(ce?.draft??R,K,B);Z([...B,{role:"assistant",content:Y.message}]),O(""),me(Y)})}const te="member-btn is-neutral";return e.jsxs(Ye,{title:"Class Plans",activeTab:"none",backTo:"/staff-tools",suppressReadOnlyNotice:!0,children:[a?e.jsxs(e.Fragment,{children:[S?e.jsx("p",{role:"alert",children:S}):null,y?e.jsx("p",{role:"status",children:y}):null,j?e.jsx(Te,{"aria-label":"Working"}):null,R?e.jsxs(e.Fragment,{children:[e.jsx("button",{className:te,disabled:j,onClick:()=>ie(()=>{_(null),Xe()}),children:"Back to library"}),e.jsx("button",{className:te,disabled:j||!p.edit,onClick:()=>ie(()=>Ie(zp(R))),children:R.resource_kind==="template"?"Use as a new plan":"Make a copy"}),ge?null:e.jsx("p",{children:"This plan is read only. Make a copy to adapt it."}),e.jsxs("fieldset",{className:"member-class-plan-fields",disabled:j||!ge,children:[e.jsxs(Un,{stepKey:"plan-details",children:[e.jsx(Bt,{label:"Plan title",value:R.title,onChange:B=>ct({title:B})}),R.uuid?e.jsx("p",{children:f.find(B=>B.uuid===R.programme_uuid)?.name}):e.jsx(rs,{label:"Programme",value:R.programme_uuid,options:f.map(B=>({value:B.uuid,label:B.name})),defaultToFirstOption:!1,onChange:B=>ct({programme_uuid:B,curriculum_item_uuids:[]})}),e.jsx(vn,{label:"Class focus",value:R.objective,onChange:B=>ct({objective:B})})]}),R.sections.map((B,Y)=>e.jsxs(Un,{stepKey:`section-${Y}`,children:[e.jsx("button",{type:"button",className:"member-panel-row","aria-expanded":H===Y,onClick:()=>ne(H===Y?-1:Y),children:e.jsxs("strong",{children:[Y+1,". ",B.title||"Section"]})}),H===Y?e.jsxs(e.Fragment,{children:[e.jsx(Bt,{label:"Section title",value:B.title,onChange:oe=>st(Y,{title:oe})}),e.jsx(vn,{label:"Notes",rows:5,value:B.notes,onChange:oe=>st(Y,{notes:oe})}),e.jsxs("details",{className:"member-input-group",children:[e.jsx("summary",{className:"member-btn is-neutral",children:"Timing, exercises, activities and sharing"}),e.jsx(Bt,{label:"Minutes (optional)",type:"number",min:"1",max:"480",value:B.minutes===null?"":String(B.minutes),onChange:oe=>st(Y,{minutes:oe===""?null:Number(oe)})}),e.jsx(rs,{label:"Format",value:B.format,options:Vp.map(oe=>({value:oe,label:Gp(oe)})),onChange:oe=>st(Y,{format:oe})}),B.format!=="free_text"?e.jsxs(e.Fragment,{children:[e.jsx(Bt,{label:"Rounds (optional)",type:"number",min:"1",value:String(B.structure.rounds??""),onChange:oe=>st(Y,{structure:{...B.structure,rounds:oe?Number(oe):void 0}})}),e.jsx(Bt,{label:"Timing (optional)",value:String(B.structure.duration??""),onChange:oe=>st(Y,{structure:{...B.structure,duration:oe}})}),(B.structure.exercises||[]).map((oe,Ue)=>e.jsxs("div",{children:[e.jsx(Bt,{label:`Exercise ${Ue+1}`,value:oe.movement,onChange:_e=>st(Y,{structure:{...B.structure,exercises:B.structure.exercises?.map((He,kt)=>Ue===kt?{...He,movement:_e}:He)}})}),e.jsx(Bt,{label:"Reps",value:String(oe.reps??""),onChange:_e=>st(Y,{structure:{...B.structure,exercises:B.structure.exercises?.map((He,kt)=>Ue===kt?{...He,reps:_e}:He)}})}),e.jsx(Bt,{label:"Load",value:oe.load??"",onChange:_e=>st(Y,{structure:{...B.structure,exercises:B.structure.exercises?.map((He,kt)=>Ue===kt?{...He,load:_e}:He)}})}),e.jsx("button",{className:te,onClick:()=>st(Y,{structure:{...B.structure,exercises:B.structure.exercises?.filter((_e,He)=>He!==Ue)}}),children:"Remove exercise"}),["side","duration","note"].map(_e=>e.jsx(Bt,{label:_e==="side"?"Side":_e==="duration"?"Duration":"Exercise notes",value:String(oe[_e]??""),onChange:He=>st(Y,{structure:{...B.structure,exercises:B.structure.exercises?.map((kt,rt)=>
2rt===Ue?{...kt,[_e]:He}:kt)}})},_e))]},Ue)),e.jsx("button",{className:te,onClick:()=>st(Y,{structure:{...B.structure,exercises:[...B.structure.exercises||[],{movement:""}]}}),children:"Add exercise"})]}):null,B.activities.map((oe,Ue)=>e.jsxs("div",{children:[e.jsx(vn,{label:oe.title,value:oe.notes,onChange:_e=>st(Y,{activities:B.activities.map((He,kt)=>Ue===kt?{...He,notes:_e}:He)})}),e.jsx("button",{className:te,onClick:()=>st(Y,{activities:B.activities.filter((_e,He)=>He!==Ue)}),children:"Remove activity"})]},Ue)),e.jsx(Bt,{label:"Find an activity",value:l,onChange:c}),e.jsx("button",{className:te,onClick:()=>{Me(async()=>m((await ds.activities(l)).items))},children:"Find reusable activities"}),h.length?e.jsx(rs,{label:"Add activity",value:"",defaultToFirstOption:!1,options:h.map(oe=>({value:oe.uuid,label:oe.title})),onChange:oe=>{const Ue=h.find(_e=>_e.uuid===oe);Ue&&st(Y,{activities:[...B.activities,{title:Ue.title,notes:Ue.content_text||""}]})}}):null,e.jsx(js,{checked:B.member_visible,onIonChange:oe=>st(Y,{member_visible:oe.detail.checked}),children:"Share with members"}),e.jsx(js,{checked:B.public_visible,onIonChange:oe=>st(Y,{public_visible:oe.detail.checked}),children:"Show on public workout display"}),e.jsx("p",{children:"Public display content is visible to anyone when enabled by your school."}),B.member_visible||B.public_visible?e.jsx(vn,{label:"Member instructions",value:B.member_instructions,onChange:oe=>st(Y,{member_instructions:oe})}):null]}),e.jsx("button",{className:te,disabled:Y===0,onClick:()=>{_(il(R,Y,-1)),ne(Y-1)},children:"Move up"}),e.jsx("button",{className:te,disabled:Y===R.sections.length-1,onClick:()=>{_(il(R,Y,1)),ne(Y+1)},children:"Move down"}),e.jsx("button",{className:te,onClick:()=>Se({title:"Remove this section?",action:()=>ct({sections:R.sections.filter((oe,Ue)=>Ue!==Y)})}),children:"Remove section"}),e.jsx("button",{className:te,onClick:()=>{Me(async()=>{await ds.saveActivity({title:B.title,content_text:B.notes,programme_uuids:[R.programme_uuid],status:"published"}),P("Activity saved to library.")})},children:"Save notes as activity"})]}):e.jsx("p",{style:{whiteSpace:"pre-wrap"},children:B.notes})]},B.uuid||Y)),e.jsx("button",{className:te,onClick:()=>{ct({sections:[...R.sections,gu("New section")]}),ne(R.sections.length)},children:"Add section"}),e.jsxs(Un,{stepKey:"curriculum",children:[e.jsx("h2",{children:"Curriculum"}),e.jsxs("p",{children:[R.curriculum_item_uuids.length," points selected. This is planned coverage, not confirmed delivery."]}),e.jsx(Bt,{label:"Search curriculum",value:be,onChange:We}),e.jsx("button",{className:te,disabled:!R.programme_uuid,onClick:()=>{Me(async()=>Ke((await ds.curriculum(R.programme_uuid,be)).data))},children:"Find curriculum points"}),Fe.map(B=>e.jsxs(js,{checked:R.curriculum_item_uuids.includes(B.uuid),onIonChange:Y=>xt(B.uuid,Y.detail.checked),children:[B.code," ",B.title]},B.uuid))]}),p.chat?e.jsxs(Un,{stepKey:"corner",children:[e.jsx("h2",{children:"Corner"}),e.jsx(rs,{label:"Drafting mode",value:K,options:[{value:"plan",label:"Plan ahead"},{value:"record",label:"Record this class"}],onChange:B=>{ye(B),Z([]),me(null)}}),e.jsx("div",{role:"log","aria-live":"polite",children:L.map((B,Y)=>e.jsxs("p",{style:{whiteSpace:"pre-wrap"},children:[e.jsxs("strong",{children:[B.role==="user"?"You":"Corner",":"]})," ",B.content]},Y))}),e.jsx(vn,{label:"Message Corner",value:de,onChange:B=>O(B.slice(0,6e3)),placeholder:K==="record"?"Describe what actually happenedâ¦":"Describe the class you want to teachâ¦"}),e.jsx(kg,{value:de,onChange:O,disabled:j}),e.jsx("button",{className:"member-btn",disabled:!de.trim()||!R.programme_uuid||j,onClick:()=>{q()},children:"Send"}),ce?.draft?e.jsxs(e.Fragment,{children:[e.jsx("h3",{children:"Proposed draft"}),ce.draft.sections.map((B,Y)=>e.jsxs("p",{style:{whiteSpace:"pre-wrap"},children:[e.jsx("strong",{children:B.title}),e.jsx("br",{}),B.notes]},Y)),e.jsx("button",{className:"member-btn",onClick:()=>{ce.draft&&(_({...ce.draft,curriculum_item_uuids:R.curriculum_item_uuids}),me({...ce,draft:null}))},children:"Apply draft changes"}),e.jsx("button",{className:te,onClick:()=>me(null),children:"Keep current draft"})]}):null,ce?.suggested_curriculum.map(B=>e.jsxs(js,{checked:R.curriculum_item_uuids.includes(B.uuid),onIonChange:Y=>xt(B.uuid,Y.detail.checked),children:["Suggested: ",B.code," ",B.title]},B.uuid))]}):null,e.jsx("button",{className:te,onClick:()=>{Et("draft")},children:"Save draft"}),e.jsx("button",{className:"member-btn",onClick:()=>{Et("published")},children:"Save ready"})]}),e.jsx("fieldset",{disabled:j||!p.edit,children:R.resource_kind==="plan"?e.jsxs(Un,{stepKey:"class",children:[e.jsx("h2",{children:"Use for a class"}),e.jsx("p",{children:"Assignment creates an independent class copy. Confirm what was delivered in class closeout."}),Ae?e.jsx("p",{children:"Loading classesâ¦"}
2):e.jsx(rs,{label:"Class",value:Be,defaultToFirstOption:!1,options:J.map(B=>({value:B.uuid,label:`${B.title} · ${B.start_at} · ${B.status}`})),onChange:fe}),e.jsx("button",{className:"member-btn",disabled:!Be||!R.uuid||R.status!=="published"||ae||J.find(B=>B.uuid===Be)?.status!=="scheduled",onClick:()=>Se({title:"Assign this plan and replace the existing class plan?",action:()=>{Me(async()=>{const B=await ds.assign(R.uuid,Be,J.find(Y=>Y.uuid===Be)?.assigned_plan_uuid||"");ke(Y=>Y.map(oe=>oe.uuid===Be?{...oe,assigned_plan_uuid:B.lesson_plan.uuid}:oe)),P("Independent plan copy assigned.")})}}),children:"Assign to class"}),Be?e.jsx("button",{className:te,onClick:()=>ie(()=>n.push(`/instructor/classes?occurrence=${encodeURIComponent(Be)}&view=debrief${R.uuid&&!ae?`&classPlan=${encodeURIComponent(J.find(B=>B.uuid===Be)?.assigned_plan_uuid||R.uuid)}`:""}`)),children:"Open class and confirm delivery"}):null]}):null})]}):e.jsxs(e.Fragment,{children:[e.jsx(rs,{label:"Library",value:i,options:[{value:"plan",label:"Plans"},{value:"activity",label:"Activities"},{value:"template",label:"Templates"}],onChange:o}),e.jsx(Bt,{label:"Search library",value:l,onChange:c}),e.jsx("button",{className:te,disabled:x,onClick:()=>{Xe()},children:"Search"}),i!=="activity"?e.jsx("button",{className:"member-btn",disabled:!p.edit||i==="template"&&!p.templates,onClick:()=>Ie(rl("",i==="template"?"template":"plan")),children:i==="template"?"New template":"New plan"}):null,x?e.jsx("p",{role:"status",children:"Loading libraryâ¦"}):i==="activity"?h.length?h.map(B=>e.jsxs(Un,{stepKey:B.uuid,children:[e.jsx("h2",{children:B.title}),e.jsx("p",{style:{whiteSpace:"pre-wrap"},children:B.content_text}),e.jsx("button",{className:te,onClick:()=>{ve(`${B.title} copy`),G(B.content_text||"")},children:"Copy activity"})]},B.uuid)):e.jsx("p",{children:"No activities found."}):u.length?u.map(B=>e.jsxs("button",{className:"member-panel-row",disabled:j,onClick:()=>{Me(async()=>Ie(await ds.read(B.uuid)))},children:[e.jsx("strong",{children:B.title}),e.jsx("p",{children:B.status==="published"?"Ready":"Draft"})]},B.uuid)):e.jsx("p",{children:"No plans found. Start with a few key points."}),v!==null?e.jsx("button",{className:te,disabled:x,onClick:()=>{Xe(v)},children:"Load more"}):null,i==="activity"&&p.edit?e.jsxs(Un,{stepKey:"new-activity",children:[e.jsx("h2",{children:"New activity"}),e.jsx(Bt,{label:"Activity title",value:Ne,onChange:ve}),e.jsx(vn,{label:"Instructions",value:xe,onChange:G}),e.jsx("button",{className:"member-btn",disabled:j||!Ne.trim(),onClick:()=>{Me(async()=>{await ds.saveActivity({title:Ne,content_text:xe,programme_uuids:[],status:"published"}),ve(""),G(""),await Xe(),P("Activity saved.")})},children:"Save activity"})]}):null]})]}):e.jsx("p",{children:"Staff class planning access is required."}),e.jsx(Vn,{isOpen:ue!==null,header:ue?.title,onDidDismiss:()=>Se(null),buttons:[{text:"Cancel",role:"cancel"},{text:"Confirm",handler:()=>{const B=ue?.action;Se(null),B?.()}}]})]})}function Cg(t){return t.split(/[_\-\s]+/).map(s=>s.trim()).filter(Boolean).map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join(" ")}function Sg(t){if(!t)return"Not recorded";const s=new Date(t);return Number.isNaN(s.getTime())?t:new Intl.DateTimeFormat("en-GB",{dateStyle:"medium",timeStyle:"short"}).format(s)}function Ul(t){return t?t.blocks.reduce((s,n)=>s+Math.max(0,n.plannedMinutes||0),0):0}function Pg(t){const s=new URLSearchParams(t),n=s.get("print"),a=s.get("download");return n==="1"||a==="1"||a==="pdf"}function Rg(){const t=tt(),s=mt(),{lessonPlanUuid:n=""}=Qs(),[a,i]=r.useState(null),[o,l]=r.useState(!0),[c,u]=r.useState(""),d=r.useMemo(()=>Pg(s.search),[s.search]);r.useEffect(()=>{let m=!0;return(async()=>{l(!0),u("");try{const b=await T.lessonPlans.getLessonPlanVersion(n);if(!m)return;i(b)}catch(b){if(!m)return;const p=re(b,"Unable to load the lesson plan document.")||"Unable to load the lesson plan document. Refresh and try again.";u(p),i(null)}finally{m&&l(!1)}})(),()=>{m=!1}},[n]),r.useEffect(()=>{a&&(document.title=`${a.title||"Lesson plan"} - lesson plan`)},[a]),r.useEffect(()=>{if(!d||o||!a)return;const m=window.setTimeout(()=>{window.print()},240);return()=>window.clearTimeout(m)},[d,a,o]);const h=r.useMemo(()=>a?[...a.blocks].sort((m,f)=>m.sortOrder-f.sortOrder):[],[a]);return e.jsx(Cn,{className:"lesson-plan-document-page",children:e.jsx(wn,{className:"lesson-plan-document-content",fullscreen:!0,forceOverscroll:!1,children:e.jsxs("div",{className:"lesson-plan-document-shell",children:[e.jsxs("div",{className:"lesson-plan-document-toolbar print-hidden",children:[e.jsxs("button",{type:"button",className:"member-btn is-neutral",onClick:()=>t.push(`/staff-tools/lesson-plans?version=${encodeURIComponent(n)}`),children:[e.jsx(V,{icon:jc}),e.jsx("span",{children:"Back to lesson plan"})]}),e.jsxs("div",{className:"lesson-plan-document-toolbar-actions",children:[e.jsxs("button",{type:"button",className:"member-btn is-neutral",onClick:()=>window.print(),disabled:o,children:[e.jsx(V,{icon:pm}),e.jsx("span",{children:"Print"})]}),e.jsxs("button",{type:"button",className:"member-btn is-neutral",onClick:()=>Ks(T.lessonPlans.getLessonPlanDocumentPath(n,"pdf")),disabled:o,children:[e.jsx(V,{icon:yc}),e.jsx("span",{children:"Download PDF"})]}),e.jsxs("button",{type:"button",className:"member-btn is-neutral",onClick:()=>{nc("error_recovery"),window.location.reload()},disabled:o,children:[e.jsx(V,{icon:pc}),e.jsx("span",{children:"Refresh"})]})]})]}),e.jsxs("article",{className:"lesson-plan-document-card",children:[o?e.jsxs("div",{className:"lesson-plan-document-state",children:[e.jsx(Te,{name:"crescent"}),e.jsx("span",{children:"Loading lesson document..."})]}):null,!o&&c?e.jsx("div",{className:"lesson-plan-document-state is-error",children:c}):null,!o&&!c&&!a?e.jsx("div",{className:"lesson-plan-document-state is-error",children:"Unable to load the lesson plan document. Refresh and try again."}):null,!o&&!c&&a?e.jsxs(e.Fragment,{children:[e.jsxs("section",{className:"lesson-plan-document-header",children:[e.jsxs("div",{className:"lesson-plan-document-identity",children:[e.jsx("span",{className:"lesson-plan-document-e
2yebrow",children:"Lesson Plan"}),e.jsx("h1",{children:a.title}),e.jsxs("div",{className:"lesson-plan-document-pills",children:[e.jsx("span",{className:"member-pill is-accent",children:Cg(a.status)}),e.jsx("span",{className:"member-pill",children:`Version ${a.versionNumber}`}),a.programmeNames.map(m=>e.jsx("span",{className:"member-pill",children:m},m))]})]}),e.jsxs("div",{className:"lesson-plan-document-metadata",children:[e.jsxs("div",{className:"lesson-plan-document-metadata-row",children:[e.jsx("span",{children:"Updated"}),e.jsx("strong",{children:Sg(a.updatedAt)})]}),e.jsxs("div",{className:"lesson-plan-document-metadata-row",children:[e.jsx("span",{children:"Blocks"}),e.jsx("strong",{children:h.length})]}),e.jsxs("div",{className:"lesson-plan-document-metadata-row",children:[e.jsx("span",{children:"Planned time"}),e.jsxs("strong",{children:[Ul(a)," min"]})]})]})]}),a.description?e.jsx("section",{className:"lesson-plan-document-copy",children:e.jsx("p",{children:a.description})}):null,a.objective?e.jsxs("section",{className:"lesson-plan-document-objective",children:[e.jsx("span",{className:"lesson-plan-document-section-label",children:"Objective"}),e.jsx("p",{children:a.objective})]}):null,e.jsxs("section",{className:"lesson-plan-document-blocks",children:[e.jsxs("div",{className:"lesson-plan-document-section-head",children:[e.jsx("h2",{children:"Blocks"}),e.jsx("span",{children:`Total planned time ${Ul(a)} min`})]}),h.length===0?e.jsx("div",{className:"lesson-plan-document-empty",children:"No lesson blocks were added to this version yet."}):null,h.map((m,f)=>e.jsxs("article",{className:"lesson-plan-document-block",children:[e.jsxs("div",{className:"lesson-plan-document-block-head",children:[e.jsxs("div",{children:[e.jsx("span",{className:"lesson-plan-document-section-label",children:`Block ${f+1}`}),e.jsx("h3",{children:m.title})]}),e.jsx("span",{className:"member-pill",children:m.plannedMinutes?`${m.plannedMinutes} min`:"Time not set"})]}),e.jsx("div",{className:"lesson-plan-document-body",dangerouslySetInnerHTML:{__html:m.renderedHtml||m.contentHtml||"<p>No block content provided.</p>"}})]},m.uuid))]})]}):null]})]})})})}function Tg(t,s){try{return new Intl.NumberFormat("en-GB",{style:"currency",currency:s||"GBP"}).format(t/100)}catch{return`${s||"GBP"} ${(t/100).toFixed(2)}`}}function _g(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`cash-${crypto.randomUUID()}`:`cash-${Date.now()}-${Math.random().toString(16).slice(2)}`}function Mg(){const[t,s]=r.useState(""),[n,a]=r.useState([]),[i,o]=r.useState(!1),[l,c]=r.useState(!1),[u,d]=r.useState(null),[h,m]=r.useState(!1),[f,b]=r.useState(""),[p,g]=r.useState([]),[v,N]=r.useState(12),x=r.useRef(!1),[k,j]=r.useState(""),[I,S]=r.useState(""),[M,y]=r.useState(""),[P,U]=r.useState(""),[F,A]=r.useState(""),[D,R]=r.useState(!1),[w,_]=r.useState(""),W=r.useRef(0),H=r.useCallback(async(L,Z)=>{o(!0);try{const ce=await T.people.listMembers(L);Z===W.current&&(a(ce.filter(me=>!["lead","trial"].includes(me.rawStatus))),c(!0))}catch(ce){Z===W.current&&(a([]),c(!0),_(re(ce,"Unable to search members.")))}finally{Z===W.current&&o(!1)}},[]);r.useEffect(()=>{const L=t.trim(),Z=++W.current;if(o(!1),L.length<3){a([]),c(!1);return}c(!1);const ce=window.setTimeout(()=>{H(L,Z)},300);return()=>window.clearTimeout(ce)},[t,H]);const ne=r.useCallback(()=>{D||(d(null),j(""),g([]),b(""),N(12),S(""),y(""),U(""),A(""))},[D]),K=r.useCallback(async L=>{m(!0);try{const Z=await T.cash.getOptions(L.uuid);d(Z),j(""),g([]),b(""),N(12),S(""),y(""),U(""),A(_g())}catch(Z){_(re(Z,"Unable to load cash options for this member."))}finally{m(!1)}},[]),ye=r.useCallback((L,Z)=>{const ce=u?.dueMemberships.find(ve=>ve.membershipUuid===L&&ve.dueDate===Z);if(!ce)return;k!==`membership:${L}`&&b("");const me=k===`membership:${L}`?p:[],Ne=me.includes(Z)?me.filter(ve=>ve!==Z):[...me,Z];j(Ne.length?`membership:${L}`:""),g(Ne),S((Ne.length*ce.amountMinor/100).toFixed(2)),y("")},[u,k,p]),de=r.useCallback(()=>{j("other"),g([]),b(""),S(""),y("")},[]),O=r.useCallback(async()=>{if(!u||x.current)return;if(!k){_("Select what the cash is for.");return}const L=Number(I);if(!Number.isFinite(L)||L<=0){_("Enter the cash amount collected.");return}if(k==="other"&&M.trim()===""){_("Describe what the cash is for.");return}x.current=!0,R(!0);try{const Z=k.startsWith("membership:")?k.slice(11):void 0;if(Z){const ce=u.dueMemberships.filter(me=>me.membershipUuid===Z&&p.includes(me.dueDate));if(!ce.length)throw new Error("Select a payment date.");if(ce.some(me=>me.scheduleMissing)&&(!f||ce.some(me=>me.dueDate<f)))throw new Error("Confirm the first unpaid payment date. It must be on or before every selected payment.");for(const me of ce)await T.cash.create({memberUuid:u.member.memberUuid,purposeType:"membership",membershipUuid:Z,dueDate:me.dueDate,firstUnpaidDate:f||void 0,amount:me.amountMinor/100,locationNote:P.trim()||void 0,idempotencyKey:`${F}-${Z.slice(0,8)}-${me.dueDate}`}),g(Ne=>Ne.filter(ve=>ve!==me.dueDate)),d(Ne=>Ne?{...Ne,dueMemberships:Ne.dueMemberships.filter(ve=>ve.membershipUuid!==Z||ve.dueDate!==me.dueDate)}:null),S(Ne=>Math.max(0,Number(Ne)-me.amountMinor/100).toFixed(2))}else await T.cash.create({memberUuid:u.member.memberUuid,purposeType:"other",amount:L,description:M.trim(),locationNote:P.trim()||void 0,idempotencyKey:F});d(null),j(""),g([]),b(""),N(12),S(""),y(""),U(""),A(""),_(`Cash logged for ${u.member.memberName}.`)}catch(Z){_(re(Z,"Unable to log this cash.")+" Saved payments were removed. Retry the remaining selection.")}finally{x.current=!1,R(!1)}},[I,M,F,P,u,k,p,f]);return e.jsxs(Ye,{standardUI:!0,title:"Log cash",subtitle:"Record cash received from a member.",activeTab:"none",backTo:"/staff-tools",children:[e.jsxs("section",{className:"member-section",children:[e.jsx("h2",{children:"Find member"}),e.jsxs("label",{className:"member-input-label",children:[e.jsx("span",{children:"Name, email, phone, or member number"}),e.jsx(on,{ariaLabel:"Search members",value:t,onChange:s,placeholder:"Search members",isSearching:i})]})]}),h?e.jsxs("div",{className:"member-panel-loading",children:[e.jsx(Te,{name:"crescent"}
2),e.jsx("span",{children:"Loading cash options"})]}):null,!i&&n.length>0?e.jsxs("section",{className:"member-section",children:[e.jsx("h2",{children:"Members"}),e.jsx("div",{className:"member-panel-list member-list--divided",children:n.map(L=>e.jsxs("button",{type:"button",className:"member-panel-row",onClick:()=>{K(L)},disabled:h,children:[e.jsxs("div",{className:"member-row-main",children:[e.jsx("strong",{children:L.fullName}),e.jsx("span",{className:"member-pill",children:gt(L.status)})]}),e.jsxs("p",{children:[L.memberIdDisplay,L.email?` · ${L.email}`:""]})]},L.uuid))})]}):null,!i&&l&&t.trim().length>=3&&n.length===0?e.jsx("div",{className:"member-panel-empty",children:"No members matched this search."}):null,e.jsx(at,{isOpen:!!u,onDidDismiss:ne,canDismiss:!D,children:e.jsxs("div",{className:"member-ui member-modal-sheet staff-cash-sheet",children:[e.jsxs("div",{className:"member-modal-header",children:[e.jsxs("h2",{children:["Log cash for ",u?.member.memberName||"member"]}),e.jsx("p",{children:"Select one or more payment dates, or choose something else."})]}),e.jsxs("div",{className:"staff-cash-purpose-list",children:[u?.dueMemberships.slice(0,v).map(L=>{const Z=k===`membership:${L.membershipUuid}`&&p.includes(L.dueDate);return e.jsxs("button",{type:"button",disabled:D,"aria-pressed":Z,className:`staff-cash-purpose${Z?" is-selected":""}`,onClick:()=>ye(L.membershipUuid,L.dueDate),children:[e.jsxs("span",{children:[e.jsx("strong",{children:L.scheduleMissing?"Payment date":L.status==="overdue"?"Overdue payment":L.status==="upcoming"?"Future payment":"Payment due today"}),e.jsxs("small",{children:[L.membershipName," · due ",L.dueDate]})]}),e.jsx("b",{children:Tg(L.amountMinor,L.currency)})]},`${L.membershipUuid}:${L.dueDate}`)}),(u?.dueMemberships.length??0)>v?e.jsx("button",{type:"button",className:"member-btn is-neutral",disabled:D,onClick:()=>N(L=>L+12),children:"Show more payment dates"}):null,e.jsx("button",{type:"button",disabled:D,className:`staff-cash-purpose${k==="other"?" is-selected":""}`,onClick:de,children:e.jsxs("span",{children:[e.jsx("strong",{children:"Something else"}),e.jsx("small",{children:"Clothing, equipment, or another cash payment"})]})})]}),u?.dueMemberships.some(L=>`membership:${L.membershipUuid}`===k&&L.scheduleMissing)?e.jsxs("label",{className:"member-input-label",children:["First unpaid payment date",e.jsx("input",{className:"member-input",type:"date",disabled:D,value:f,onChange:L=>b(L.target.value)}),e.jsx("small",{children:"No payment date is saved. Confirm the first unpaid date on this membership schedule. Earlier dates will not be marked as owed."})]}):null,k?e.jsxs(e.Fragment,{children:[e.jsxs("label",{className:"member-input-label",children:[k==="other"?"Amount collected":`Total for ${p.length} selected payments`,e.jsx(Ds,{"aria-label":"Amount collected",readOnly:k!=="other",disabled:D,className:"member-input",type:"number",min:"0.01",step:"0.01",inputMode:"decimal",value:I,onChange:L=>S(L.target.value)})]}),k==="other"?e.jsxs("label",{className:"member-input-label",children:["What is the cash for?",e.jsx("input",{className:"member-input",disabled:D,maxLength:255,value:M,onChange:L=>y(L.target.value),placeholder:"For example, club T shirt"})]}):null,e.jsxs("label",{className:"member-input-label",children:["Cash location",e.jsx("input",{className:"member-input",disabled:D,maxLength:255,value:P,onChange:L=>U(L.target.value),placeholder:"For example, office safe"}),e.jsx("small",{children:"Enter where the cash was left, such as the office safe. Leave blank if it was handed straight to the owner."})]})]}):null,e.jsxs("div",{className:"member-list-actions staff-cash-actions",children:[e.jsx("button",{type:"button",className:"member-btn is-neutral",onClick:ne,disabled:D,children:"Cancel"}),e.jsx("button",{type:"button",className:"member-btn is-solid",onClick:()=>{O()},disabled:D||!k||k!=="other"&&!p.length,children:D?e.jsxs(e.Fragment,{children:[e.jsx(Te,{name:"crescent"})," Saving"]}):"Confirm cash collected"})]})]})}),e.jsx(Dt,{isOpen:!!w,message:w,duration:2500,onDidDismiss:()=>_("")})]})}const El={trialWindows:[],membershipWindows:[]},Al={publicPages:[],items:[]};function Ou(t){return t==="child"?"Kids":"Adults"}function Ug(t){const s=(t||"").trim();return s?Su(`/links/${encodeURIComponent(s)}`):""}
2function Eg({item:t,isQrOpen:s,onCopy:n,onToggleQr:a}){return e.jsxs("article",{className:"member-panel-row staff-sales-link-card",children:[e.jsxs("div",{className:"member-row-main",children:[e.jsx("strong",{children:t.name}),e.jsx("span",{className:"member-pill is-accent",children:Ou(t.audience)})]}),e.jsx("p",{children:[t.priceDisplay,t.summary].filter(Boolean).join(" . ")}),e.jsxs("div",{className:"member-list-actions staff-sales-link-actions",children:[e.jsxs("a",{className:"member-btn",href:t.publicUrl,target:"_blank",rel:"noopener noreferrer external",children:[e.jsx(V,{icon:Vs})," Open"]}),e.jsxs("button",{type:"button",className:"member-btn is-solid",onClick:()=>n(t),children:[e.jsx(V,{icon:kn}),"Copy"]}),e.jsx("button",{type:"button",className:"member-btn is-icon-only",onClick:()=>a(t),"aria-label":s?`Hide QR code for ${t.name}`:`Show QR code for ${t.name}`,"aria-expanded":s,title:s?"Hide QR code":"Show QR code",children:e.jsx(V,{icon:ja})})]}),s?e.jsxs("div",{className:"staff-sales-link-qr",children:[e.jsx("img",{src:ya(t.publicUrl,240),alt:`QR code for ${t.name}`}),e.jsx("span",{children:"Scan to open this offer."})]}):null]})}function Dl(){Ub();const{user:t}=Ge(),{tenantName:s}=ln(),[n,a]=r.useState(El),[i,o]=r.useState(Al),[l,c]=r.useState(""),[u,d]=r.useState(!0),[h,m]=r.useState(""),[f,b]=r.useState(""),[p,g]=r.useState(""),[v,N]=r.useState(""),x=r.useCallback(async()=>{d(!0),m(""),b("");const[w,_]=await Promise.allSettled([T.salesLinks.list(),T.quickLinks.listStaffShareTools()]);a(w.status==="fulfilled"?w.value:El),o(_.status==="fulfilled"?_.value:Al),w.status==="rejected"&&_.status==="rejected"?m(re(_.reason,"Unable to load Share Tools.")):w.status==="rejected"?b("Trial and membership windows are unavailable. Your saved Share Tools are still available."):_.status==="rejected"&&b("Saved Share Tools are unavailable. Trial and membership windows are still available."),d(!1)},[]);r.useEffect(()=>{x()},[x]);const k=r.useCallback(async w=>{const _=await Gn(w.publicUrl);g(_?`${w.name} link copied.`:"Unable to copy this link on this device.")},[]),j=r.useCallback(w=>{const _=`${w.audience}:${w.uuid}`;N(W=>W===_?"":_)},[]),I=r.useCallback(w=>{N(_=>_===w?"":w)},[]),S=l.trim().toLowerCase(),M=i.items.filter(w=>!S||[w.label,w.category,w.bodyText,w.url].some(_=>_?.toLowerCase().includes(S))),y=i.publicPages.filter(w=>!S||[w.title,w.slug].some(_=>_?.toLowerCase().includes(S))),P=w=>w.filter(_=>!S||[_.name,_.summary,_.priceDisplay,Ou(_.audience)].some(W=>W?.toLowerCase().includes(S))),U=P(n.trialWindows),F=P(n.membershipWindows),A=w=>w.replaceAll("{{staff_first_name}}",t?.firstName||"Staff").replaceAll("{{gym_name}}",s||"the gym"),D=async(w,_)=>{const W=await Gn(_);g(W?`${w} copied.`:"Unable to copy this item on this device.")},R=(w,_,W)=>e.jsxs("section",{className:"member-section staff-sales-links-section",children:[e.jsx("h2",{children:w}),e.jsx("p",{className:"member-panel-help",children:_}),W.length===0?e.jsx("p",{children:"No available links."}):e.jsx("div",{className:"member-panel-list member-list--divided",children:W.map(H=>{const ne=`${H.audience}:${H.uuid}`;return e.jsx(Eg,{item:H,isQrOpen:v===ne,onCopy:k,onToggleQr:j},ne)})})]});return e.jsxs(Ye,{standardUI:!0,title:"Share Tools",subtitle:"Copy approved links and replies for members and prospects.",activeTab:"none",backTo:"/staff-tools",onRefresh:x,children:[u?e.jsxs("div",{className:"member-panel-loading",children:[e.jsx(Te,{name:"crescent"}),e.jsx("span",{children:"Loading Share Tools..."})]}):null,!u&&h?e.jsx("div",{className:"member-panel-error",children:h}):null,!u&&!h?e.jsxs(e.Fragment,{children:[f?e.jsx("section",{className:"member-section",children:e.jsx("p",{className:"member-panel-help",children:f})}):null,e.jsxs("section",{className:"member-section staff-sales-links-section",children:[e.jsx("h2",{children:"Find a share tool"}),e.jsx(on,{ariaLabel:"Search links and replies",value:l,onChange:c,placeholder:"Search links and replies"})]}),e.jsxs("section",{className:"member-section staff-sales-links-section",children:[e.jsx("h2",{children:"Handy links and replies"}),M.length===0?e.jsx("p",{children:"No saved links or replies found."}):e.jsx("div",{className:"member-panel-list member-list--divided",children:M.map(w=>{const _=`custom:${w.uuid}`,W=v===_;return e.jsxs("article",{className:"member-panel-row",children:[e.jsxs("div",{className:"member-row-main",children:[e.jsx("strong",{children:w.label}),w.category?e.jsx("span",{className:"member-pill is-accent",children:w.
2category}):null]}),w.itemType==="reply"?e.jsx("p",{children:A(w.bodyText||"")}):e.jsx("p",{children:w.url}),e.jsxs("div",{className:`member-list-actions ${w.itemType==="link"?"staff-sales-link-actions":""}`,children:[w.itemType==="link"?e.jsxs("a",{className:"member-btn",href:w.url,target:"_blank",rel:"noopener noreferrer external",children:[e.jsx(V,{icon:Vs})," Open"]}):null,e.jsxs("button",{className:"member-btn is-solid",type:"button",onClick:()=>{D(w.label,w.itemType==="reply"?A(w.bodyText||""):w.url)},children:[e.jsx(V,{icon:kn})," ",w.itemType==="reply"?"Copy reply":"Copy"]}),w.itemType==="link"?e.jsx("button",{className:"member-btn is-icon-only",type:"button",onClick:()=>I(_),"aria-label":W?`Hide QR code for ${w.label}`:`Show QR code for ${w.label}`,"aria-expanded":W,title:W?"Hide QR code":"Show QR code",children:e.jsx(V,{icon:ja})}):null]}),w.itemType==="link"&&W?e.jsxs("div",{className:"staff-sales-link-qr",children:[e.jsx("img",{src:ya(w.url,240),alt:`QR code for ${w.label}`}),e.jsx("span",{children:"Scan to open this link."})]}):null]},w.uuid)})})]}),y.length?e.jsxs("section",{className:"member-section staff-sales-links-section",children:[e.jsx("h2",{children:"Public pages"}),e.jsx("div",{className:"member-panel-list member-list--divided",children:y.map(w=>{const _=Ug(w.slug);if(!_)return null;const W=`public:${w.uuid}`,H=v===W;return e.jsxs("article",{className:"member-panel-row",children:[e.jsx("strong",{children:w.title}),e.jsxs("div",{className:"member-list-actions staff-sales-link-actions",children:[e.jsxs("a",{className:"member-btn",href:_,target:"_blank",rel:"noopener noreferrer external",children:[e.jsx(V,{icon:Vs})," Open"]}),e.jsxs("button",{className:"member-btn is-solid",type:"button",onClick:()=>{D(w.title,_)},children:[e.jsx(V,{icon:kn})," Copy"]}),e.jsx("button",{className:"member-btn is-icon-only",type:"button",onClick:()=>I(W),"aria-label":H?`Hide QR code for ${w.title}`:`Show QR code for ${w.title}`,"aria-expanded":H,title:H?"Hide QR code":"Show QR code",children:e.jsx(V,{icon:ja})})]}),H?e.jsxs("div",{className:"staff-sales-link-qr",children:[e.jsx("img",{src:ya(_,240),alt:`QR code for ${w.title}`}),e.jsx("span",{children:"Scan to open this page."})]}):null]},w.uuid)})})]}):null,R("Trial windows","Copy an approved trial intake link or show its QR code.",U),R("Membership windows","Copy an approved membership onboarding link or show its QR code.",F)]}):null,e.jsx(Dt,{isOpen:!!p,message:p,duration:2200,onDidDismiss:()=>g("")})]})}function Ag(){const t=tt(),{hasRole:s,user:n}=Ge(),{shopPermissions:a}=Hc(),i=s("instructor","admin","owner"),o=n?.role==="owner"||n?.staffCapabilities?.shop_edit_products===!0||a?.shop_edit_products===!0,l=Gs(n),c=[...Kn(n)?[{label:"Members",description:"Read-only member profiles, emergency contacts, and quick notes.",path:"/people/members",icon:qs}]:[],...Yn(n)?[{label:"Prospects",description:"Lead and trial visibility for instructors and staff.",path:"/people/prospects",icon:As}]:[],...Zn(n)?[{label:"Households",description:"Read-only household groups and payer context.",path:"/people/households",icon:xc}]:[]];return e.jsx(Ye,{standardUI:!0,title:"Staff Tools",subtitle:"Instructor and staff-only actions.",activeTab:"none",children:i?e.jsxs("section",{className:"member-section member-staff-tools-card",children:[e.jsx("h2",{children:"Available tools"}),e.jsxs("div",{className:"member-panel-list member-list--divided",children:[o&&e.jsxs("button",{type:"button",className:"member-panel-row",onClick:()=>t.push(sr),children:[e.jsxs("div",{className:"member-row-main",children:[e.jsx("strong",{children:"Shop products"}),e.jsx(V,{icon:Ka})]}),e.jsx("p",{children:"Add products, update product details and manage stock."})]}),a&&(a.shop_view_orders||a.shop_adjust_stock||a.shop_log_sales)&&e.jsxs("button",{type:"button",className:"member-panel-row",onClick:()=>t.push("/staff-tools/shop/"+(a.shop_view_orders?"orders":a.shop_adjust_stock?"inventory":"counter")),children:[e.jsxs("div",{className:"member-row-main",children:[e.jsx("strong",{children:"Shop operations"}),e.jsx(V,{icon:Ka})]}),e.jsx("p",{children:"View permitted orders, adjust stock or record a shop cash sale."})]}),e.jsxs("button",{type:"button",className:"member-panel-row",onClick:()=>t.push("/staff-tools/prompts"),children:[e.jsxs("div",{className:"member-row-main",children:[e.jsx("strong",{children:"Prompts"}),e.jsx(V,{icon:nr})]}),e.jsx("p",{children:"Preview saved Member App prompts on this device."})]}),e.jsxs("button",{type:"button",className:"member-panel-row",onClick:()=>t.push("/staff-tools/share-tools"),children:[e.jsxs("div",{className:"member-row-main",children:[e.jsx("strong",{children:"Share Tools"}),e.jsx(V,{icon:xo})]}),e.jsx("p",{children:"Copy approved links, public pages, QR codes, and saved replies."})]}),e.jsxs("button",{type:"button",className:"member-panel-row",onClick:()=>t.push("/staff-tools/log-cash"),children:[e.jsxs("div",{className:"member-row-main",children:[e.jsx("strong",{children:"Log cash"}),e.jsx(V,{icon:Ka})]}),e.jsx("p",{children:"Find a member and record membership or other cash."})]}),c.map(u=>e.jsxs("button",{type:"button",className:"member-panel-row",onClick:()=>t.push(u.path),children:[e.jsxs("div",{className:"member-row-main",children:[e.jsx("strong",{children:u.label}),e.jsx(V,{icon:u.icon})]}),e.jsx("p",{children:u.description})]},u.path)),e.jsxs("button",{type:"button",className:"member-panel-row",onClick:()=>t.push("/staff-tools/availability"),children:[e.jsxs("div",{className:"member-row-main",children:[e.jsx("strong",{children:"Availability"}),e.jsx(V,{icon:Ut})]}),e.jsx("p",{children:"Pick a week and mark each class as available, not available, or not set."})]}),e.jsxs("button",{type:"button",className:"member-panel-row",onClick:()=>t.push("/staff-tools/rota"),children:[e.jsxs("div",{className:"member-row-main",children:[e.jsx("strong",{children:"Instructor Rota"}),e.jsx(V,{icon:Ut})]}),e.jsx("p",{children:"View your teaching assignments or the whole instructor rota by week or month."})]}),e.jsxs("button",{type:"button",className:"member-panel-row",onClick:()=>t.push("/timetable"),children:[e.jsxs("div",{className:"member-row-main",children:[e.jsx("strong",{children:"Class Management"}),e.jsx(V,{icon:Ut})]}),e.jsx("p",{children:"Choose Manage on a timetable class for roster review and closeout."})]}),l?e.jsxs("button",{type:"button",className:"member-panel-row",onClick:()=>t.push("/staff-tools/lesson-plans"),children:[e.jsxs("div",{className:"member-row-main",children:[e.jsx("strong",{children:"Class Plans"}),e.jsx(V,{icon:da})]}),e.jsx("p",{children:"Plan any class, reuse activities or record what you taught."})]}):null]})]}):e.jsxs("section",{className:"member-section member-staff-tools-card",children:[e.jsxs("div",{className:"member-row-main",children:[e.jsx("h2",{children:"Staff access required"}),e.jsx(V,{icon:nr})]}),e.jsx("p",{children:"This account does not have instructor or staff tools enabled."})]})})}function Dg(){const[t,s]=r.useState([]),[n,a]=r.useState(0),[i,o]=r.useState(!1),[l,c]=r.useState(!0),[u,d]=r.useState(""),[h,m]=r.useState(0),[f,b]=r.useState(""),[p,g]=r.useState([]),[v,N]=r.useState(null),[x,k]=r.useState(!1),[j,I]=r.useState(""),[S,M]=r.useState(null),[y,P]=r.useState(""),[U,F]=r.useState(""),A=r.useRef(0);r.useEffect(()=>{let _=!1;return c(!0),d(""),T.staffPrompts.list(n).then(W=>{_||(s(H=>n===0?W:[...H,...W]),o(W.length===50))}).catch(W=>{_||d(re(W,"Unable to load prompts."))}).finally(()=>{_||c(!1)}),()=>{_=!0}},[n,h]),r.useEffect(()=>{let _=!1;k(!0),I("");const W=window.setTimeout(()=>{T.staffPrompts.recipients(f).then(H=>{_||g(H)}).catch(H=>{_||(g([]),I(re(H,"Unable to load members and trials.")))}).finally(()=>{_||k(!1)})},250);return()=>{_=!0,window.clearTimeout(W)}
2},[f]),r.useEffect(()=>()=>{A.current+=1},[]);function D(_){A.current+=1,F(""),M(null),P(""),N(p.find(W=>W.uuid===_)||(v?.uuid===_?v:null))}async function R(_){const W=++A.current;F(_.uuid),M(null),P("");try{const H=await T.staffPrompts.preview(_.uuid,v?.uuid||"");W===A.current&&M(H)}catch(H){W===A.current&&P(re(H,"Unable to open the preview."))}finally{W===A.current&&F("")}}const w=[...v?[v]:[],...p.filter(_=>_.uuid!==v?.uuid)];return e.jsxs(Ye,{standardUI:!0,title:"Prompts",subtitle:"Preview saved Member App prompts on this device.",activeTab:"none",backTo:"/staff-tools",children:[e.jsxs("section",{className:"member-section",children:[e.jsx("h2",{children:"Preview as"}),e.jsx("p",{children:"Choose a member or trial, or use your own account. Preview buttons do not change delivery history. Links open their real destination."}),e.jsxs("div",{className:"member-prompts-recipient-field",children:[e.jsx("label",{className:"member-input-label",htmlFor:"prompt-recipient-search",children:"Find a person"}),e.jsx(on,{id:"prompt-recipient-search",ariaLabel:"Find a person",placeholder:"Search members and trials",value:f,onChange:b,isSearching:x})]}),e.jsxs($n,{className:"member-picker","aria-label":"Preview as",interface:"alert",interfaceOptions:{cssClass:"member-picker-alert",header:"Preview as"},value:v?.uuid||"",disabled:x,onIonChange:_=>D(String(_.detail.value)),children:[e.jsx(Fs,{value:"",children:"My account"}),w.map(_=>e.jsxs(Fs,{value:_.uuid,children:[_.name," (",_.kind,_.memberType==="child"?", child":"",")"]},_.uuid))]}),x?e.jsx("p",{role:"status",children:"Loading members and trials..."}):j?e.jsx("p",{role:"alert",className:"member-panel-error",children:j}):p.length===0?e.jsx("p",{children:"No people found. Try another name."}):e.jsx("p",{children:"Search by name to find more people."})]}),e.jsxs("section",{className:"member-section",children:[u?e.jsxs("div",{role:"alert",children:[e.jsx("p",{className:"member-panel-error",children:u}),e.jsx("button",{type:"button",className:"member-btn is-neutral",onClick:()=>m(_=>_+1),children:"Try again"})]}):null,!l&&!u&&t.length===0?e.jsx("p",{children:"No prompts have been created yet."}):null,e.jsx("div",{className:"member-panel-list member-list--divided",children:t.map(_=>e.jsxs("div",{className:"member-panel-row",children:[e.jsxs("div",{className:"member-row-main",children:[e.jsx("strong",{children:_.name}),e.jsx(zc,{tone:_.status==="active"?"success":"neutral",children:gt(_.status)})]}),e.jsx("div",{className:"member-list-actions",children:e.jsx("button",{type:"button",className:"member-btn is-neutral",disabled:!!U,onClick:()=>{R(_)},children:U===_.uuid?"Opening preview...":"Preview prompt"})})]},_.uuid))}),l?e.jsx("p",{role:"status",children:"Loading prompts..."}):null,i&&!u?e.jsx("button",{type:"button",className:"member-btn is-neutral",disabled:l,onClick:()=>a(t[t.length-1].id),children:"Load more"}):null,y?e.jsx("p",{role:"alert",className:"member-panel-error",children:y}):null,S?e.jsxs("div",{role:"status",children:[e.jsxs("p",{children:["Preview for ",S.accountName]}),S.notes.map(_=>e.jsx("p",{children:_},_))]}):null]}),S?.prompt?e.jsx(Co,{memberUuid:"",promptCandidate:S.prompt,previewMode:!0,onPreviewClose:()=>M(null)}):null]})}const Lg="We could not save this. Please try again.";function Ig(t,s,n){return!t||!s?null:Qc(t,n)?s:null}async function $g(t,s,n){n(t);try{await s()}catch{}}async function Og(t){try{return await t(),null}catch{return Lg}}function Bg({memberUuid:t,promptCandidate:s}){const[n,a]=r.useState(null),i=r.useRef(null),[o,l]=r.useState(null),[c,u]=r.useState("");if(r.useEffect(()=>{if(n)return Kc()},[n]),r.useEffect(()=>{if(i.current?.memberUuid===t&&(n||i.current.prompt===s))return;let p=null;try{p=window.sessionStorage}catch{p=null}const g=Ig(t,s,p);g&&(i.current={memberUuid:t,prompt:s},a(g))},[t,s,n]),!n)return null;const d=`community-group-prompt-title-${n.groupUuid}`,h=`community-group-prompt-message-${n.groupUuid}`,m=n.platform==="other"?"Community":n.platform.charAt(0).toUpperCase()+n.platform.slice(1);async function f(){!n||o||(l("opened"),u(""),await $g(n.inviteUrl,()=>T.me.recordFlexibleCommunityGroupPromptAction(n.groupUuid,"opened"),Ks),a(null),l(null))}async function b(p){if(!n||o)return;l(p),u("");const g=await Og(()=>T.me.recordFlexibleCommunityGroupPromptAction(n.groupUuid,p));g===null?a(null):u(g),l(null)}return e.jsx(at,{className:"member-community-group-modal",isOpen:!0,backdropDismiss:!1,canDismiss:!1,"aria-labelledby":d,"aria-describedby":h,children:e.jsxs("section",{className:"member-modal-sheet member-community-group-sheet","aria-busy":!!o,children:[e.jsxs("div",{className:"member-community-group-copy",children:[e.jsxs("p",{className:"member-community-group-audience",children:[m," group"]}),e.jsxs("h2",{id:d,children:["Join ",n.name]}),e.jsx("p",{id:h,children:n.description||"Open the invitation to join this group and keep up with your gym community."})]}),c?e.jsx("p",{className:"member-panel-error",role:"alert",children:c}):null,e.jsxs("div",{className:"member-list-actions member-community-group-actions",children:[e.jsx("button",{type:"button",className:"member-btn is-solid",disabled:!!o,onClick:()=>{f()},children:o==="opened"?"Opening...":"Open group"}),e.jsx("button",{type:"button",className:"member-btn is-neutral",disabled:!!o,onClick:()=>{b("snoozed")},children:o==="snoozed"?"Saving...":"Not now"}),e.jsx("button",{type:"button",className:"member-btn is-neutral",disabled:!!o,onClick:()=>{b("dismissed_permanently")}
2,children:o==="dismissed_permanently"?"Saving...":"Don't show again"})]})]})})}function Fg({state:t,actionPath:s="/forms",hideAction:n=!1}){const a=tt(),i=kc(s,t);return e.jsxs("section",{className:"member-forms-banner",role:"status","aria-live":"polite",children:[e.jsxs("div",{className:"member-forms-banner-copy",children:[e.jsx("span",{className:"member-forms-banner-eyebrow",children:"Forms"}),e.jsx("strong",{children:wc(t)}),e.jsx("p",{children:Nc(t)})]}),n?null:e.jsx("button",{type:"button",className:"member-btn is-solid member-forms-banner-action",onClick:()=>a.push(i),children:t.incompleteCount===1?"Complete form":"Complete forms"})]})}function Wg(t,s){const n=t.find(a=>a.targetId===s);return!!(n&&!n.dob)}function qg(t){return t instanceof cn&&(t.reason==="member_dob_required"||t.code==="member_dob_required")}function Hg(t,s){const n=/^(\d{4})-(\d{2})-(\d{2})$/.exec(t.trim());if(!n||t>s)return!1;const a=Number(n[1]),i=Number(n[2]),o=Number(n[3]),l=new Date(Date.UTC(a,i-1,o));return l.getUTCFullYear()===a&&l.getUTCMonth()===i-1&&l.getUTCDate()===o}function Vg({isActive:t,previousRequestedDateKey:s,requestedDateKey:n,previousSelectedDateKey:a,selectedDateKey:i}){if(!t)return null;const o=n!==s,l=i!==a;return o&&!l?n&&n!==i?{type:"select-requested",dateKey:n}:null:l&&i&&n!==i?{type:"sync-url",dateKey:i}:null}async function zg(t,s){await t(),await s()}function Gg(t){const s=t.filter(n=>n.isBooked).length;return s===0?"BOOK":s===t.length?"CANCEL":"BOOK OR CANCEL"}function Bu(t,s=Date.now()){const n=new Date(t).getTime(),a=Number.isFinite(n)&&n<s;return{isPast:a,pastActionReason:a?"This class has finished. Past classes cannot be booked or cancelled.":null}}function Kg(t){return(t??[]).find(s=>s.role==="lead"||s.isLead===!0)??null}function Yg(t,s){const n=(t??[]).filter(o=>typeof o.displayName=="string"&&o.displayName.trim()!==""),a=Kg(n)??n[0]??null;if(a?.displayName)return{displayName:a.displayName.trim(),avatarUrl:typeof a.avatarUrl=="string"&&a.avatarUrl.trim()!==""?a.avatarUrl.trim():null};const i=typeof s=="string"?s.trim():"";return i?{displayName:i,avatarUrl:null}:null}function Qg(t){for(const s of[t.classTypeColorKey,t.programColorKey]){const n=(s??"").trim();if(/^#[0-9a-fA-F]{6}$/.test(n))return n.toLowerCase()}return"#9ca3af"}function Zg(t){const s=typeof t.ageMin=="number"&&Number.isFinite(t.ageMin)?Math.max(0,Math.round(t.ageMin)):null,n=typeof t.ageMax=="number"&&Number.isFinite(t.ageMax)?Math.max(0,Math.round(t.ageMax)):null;return s!==null&&n!==null?s===n?`Age ${s}`:n>=99?`Ages ${s}+`:`Ages ${s} to ${n}`:s!==null?`Ages ${s}+`:n!==null?`Up to age ${n}`:"All ages"}function Fi(t,s){return s?t.filter(n=>n.classTypeId===s):t}function Jg(t,s){return t.some(n=>n.classTypeId===s)}const Xg=/^(\d{4})-(\d{2})-(\d{2})$/,ex=2;function as(t,s){const n=Xg.exec(t.trim());if(!n)return t;const a=new Date(Date.UTC(Number(n[1]),Number(n[2])-1,Number(n[3])+s)),i=a.getUTCFullYear(),o=`${a.getUTCMonth()+1}`.padStart(2,"0"),l=`${a.getUTCDate()}`.padStart(2,"0");return`${i}-${o}-${l}`}function tx(t){const s=[];for(let n=1;n<=ex;n+=1)s.push(as(t,-n),as(t,n));return s}function sx(t){const s=new Map;let n=0;const a=()=>{n+=1;for(const o of s.values())o.controller.abort();s.clear()};return{dispose:a,ensure:o=>{if(t.isCached(o))return Promise.resolve(!0);const l=s.get(o);if(l)return l.promise;const c=n,u=new AbortController,d=t.load(o,u.signal).then(h=>u.signal.aborted||c!==n?!1:(t.isCached(o)||t.cache(o,h),!0)).catch(()=>!1).finally(()=>{s.get(o)?.controller===u&&s.delete(o)});return s.set(o,{controller:u,promise:d}),d},invalidate:a}}function Ll(t,s,n){const a=Number.isFinite(t)?Math.max(0,t):0,i=Number.isFinite(s)&&s>0?s:a,o=Number.isFinite(n)?Math.max(0,Math.min(1,n)):0;return a+(i-a)*o}function nx(t,s){let n=null,a=null,i=0;const o=(h,m)=>{h&&(h.style.height=`${Math.max(0,Math.ceil(m))}px`)},l=()=>{n!==null&&(s(n),n=null),a=null};return{cancel:l,clear:h=>{l(),h?.style.removeProperty("height"),h?.style.removeProperty("transition")},flush:(h,m,f=!1)=>{l(),h&&(h.style.transition=f?"height 220ms ease":"none",o(h,m))},queue:(h,m)=>{a=h,i=m,n===null&&(n=t(()=>{n=null;const f=a;a=null,o(f,i)}))}}}function ax(t){const s=Math.max(0,t.bookedCount),n=Math.min(s,Math.max(0,t.trialCount)),a=Math.max(0,s-n),i=Math.max(0,t.cancelledCount),o=Math.max(s,t.capacity);return{memberCapacityValue:o>0?`${a} / ${o}`:String(a),attendeeCapacityValue:o>0?`${s} / ${o}`:String(s),trialValue:String(n),cancelledValue:String(i)}}function rx(t,s){const n=new Map(s.map(o=>[o.occurrenceUuid,o])),a=t.map(o=>{const l=n.get(o.sessionId);return l&&(l.instructors?.length??0)>0?{...o,instructors:l.instructors}:o}),i=new Set(a.map(o=>o.sessionId));for(const o of s){if(o.status!=="closed"||i.has(o.occurrenceUuid)||!o.startAt||!o.endAt)continue;const l=Math.max(0,o.capacity),c=Math.max(0,o.bookedCount);a.push({sessionId:o.occurrenceUuid,title:o.className,startTime:o.startAt,endTime:o.endAt,locationName:o.locationName||"Location not set",programName:o.programName,instructorName:o.instructorName,instructors:o.instructors??[],isFreeTrialEligible:!1,requiresMembership:!0,spotsRemaining:Math.max(0,l-c),isFull:l>0&&c>=l,waitlistAvailable:!1,status:"closed"}),i.add(o.occurrenceUuid)}return a.sort((o,l)=>o.startTime.localeCompare(l.startTime))}function Fu(t,s){return`skullsystem:timetable-state:v1:${t||"unknown"}:${s||"unknown"}`}function ix(t,s){if(typeof window>"u")return null;try{const n=JSON.parse(window.sessionStorage.getItem(Fu(t,s))||"null");return!n||!Jn(String(n.selectedDateKey||""))?null:{selectedDateKey:String(n.selectedDateKey),selectedClassTypeId:String(n.selectedClassTypeId||""),scrollTop:Math.max(0,Number(n.scrollTop||0))}}catch{return null}}function ox(t){const s=t==="dark"?"#171719":"#ffffff";if(typeof window>"u")return s;const n=window.getComputedStyle(document.documentElement).getPropertyValue("--member-card-bg");return Ql(n)??s}const lx=["MON","TUE","WED","THU","FRI","SAT","SUN"],Il=320;function $l(t){return t.canBook||t.isBooked&&t.canCancel&&!!t.bookingUuid}function Jn(t){const s=/^(\d{4})-(\d{2})-(\d{2})$/.exec(t.trim());return s?{year:Number(s[1]),month:Number(s[2]),day:Number(s[3])}:null}function cx(t){return{rangeStart:as(t,-1),rangeEnd:as(t,1)}}function ux(t){if(!Jn(t.rangeStart)||!Jn(t.rangeEnd)||t.rangeEnd<t.rangeStart)return[];const s=[];let n=t.rangeStart;for(;n<=t.rangeEnd&&s.length<3;)s.push(n),n=as(n,1);return s}function Wi(t){const s=Jn(t);if(!s)return t;const i=(new Date(Date.UTC(s.year,s.month-1,s.day)).getUTCDay()+6)%7;return as(t,-i)}function dx(t){const n=(new URLSearchParams(t).get("date")??"").trim();return n&&Jn(n)?n:null}function Er(t){return Array.from({length:7},(s,n)=>
2as(t,n))}function mx(t){const s=t%100;if(s>=11&&s<=13)return`${t}th`;switch(t%10){case 1:return`${t}st`;case 2:return`${t}nd`;case 3:return`${t}rd`;default:return`${t}th`}}function hx(t){const s=Jn(t);if(!s)return t;const n=["January","February","March","April","May","June","July","August","September","October","November","December"];return`${mx(s.day)} ${n[s.month-1]} ${s.year}`}function Va(t){const s=new Intl.DateTimeFormat("en-GB",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(new Date),n=s.find(o=>o.type==="year")?.value??"1970",a=s.find(o=>o.type==="month")?.value??"01",i=s.find(o=>o.type==="day")?.value??"01";return`${n}-${a}-${i}`}function Wu(t){if(Array.isArray(t))return Wu(t[0]);const s=(t??"").trim();if(!s)return null;const n=/^(\d{4}-\d{2}-\d{2})$/.exec(s);if(n)return n[1];const a=/^(\d{4}-\d{2}-\d{2})T/.exec(s);if(a)return a[1];const i=new Date(s);return Number.isNaN(i.getTime())?null:i.toISOString().slice(0,10)}function ma(t,s){const n=new Date(t);if(Number.isNaN(n.getTime()))return null;const a=new Intl.DateTimeFormat("en-GB",{timeZone:s,year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(n),i=a.find(c=>c.type==="year")?.value,o=a.find(c=>c.type==="month")?.value,l=a.find(c=>c.type==="day")?.value;return!i||!o||!l?null:`${i}-${o}-${l}`}function px(t,s){const n=new Date(t.startTime),a=new Date(t.endTime);if(Number.isNaN(n.getTime())||Number.isNaN(a.getTime()))return`${t.startTime} - ${t.endTime}`;const i=new Intl.DateTimeFormat("en-GB",{timeZone:s,hour:"2-digit",minute:"2-digit",hour12:!1});return`${i.format(n)} - ${i.format(a)}`}function bx(t){const s=t.trim();return s&&s.split(/\s+/)[0]||"Member"}function fx(t){const s=(t??"").trim().toLowerCase();return s?/(eligib|membership|programme|program|age|household|gate|not allowed|not available for)/i.test(s):!1}function gx(t){const s=new Map;for(const n of t)!n.bookingUuid||!n.occurrenceUuid||!n.personUuid||s.set(`${n.occurrenceUuid}:${n.personUuid}`,n);return s}function xx(t){const s=new Map;for(const n of t)n.sessionId&&s.set(n.sessionId,n);return s}function jx(t){return new Map(Array.from(t.entries(),([s,n])=>[s,new Map(n)]))}function qi(t,s){const n=t.timezone||"UTC",a=t.instructorOccurrences.filter(c=>!!c.startAt&&ma(c.startAt??"",n)===s),i=(Array.isArray(t.timetable.items)?t.timetable.items:[]).filter(c=>ma(c.startTime,n)===s),o=rx(i,a);o.sort((c,u)=>c.startTime<u.startTime?-1:c.startTime>u.startTime?1:0);const l=new Map;for(const c of t.eventRegistrations){if(!o.some(d=>d.sessionId===c.occurrenceUuid))continue;const u=l.get(c.occurrenceUuid)??[];u.push(c),l.set(c.occurrenceUuid,u)}return{timezone:n,sessions:o,closures:Array.isArray(t.timetable.closures)?t.timetable.closures.filter(c=>c.startDate<=s&&c.endDate>=s):[],bookingsIndex:gx(t.bookings.data.filter(c=>!!c.startAt&&ma(c.startAt??"",n)===s)),availabilityByTarget:new Map(Object.entries(t.availabilityByTarget).map(([c,u])=>[c,xx(u.items.filter(d=>ma(d.startTime,n)===s))])),instructorOccurrences:new Map(a.map(c=>[c.occurrenceUuid,c])),eventRegistrationsByOccurrence:l}}function Hi(t,s,n,a,i,o,l=new Map,c=new Map,u=Date.now()){const d=u;return t.map(h=>{const m=h.status==="cancelled",f=h.status==="closed",b=new Date(h.startTime).getTime(),p=!m&&!f&&Number.isFinite(b)&&b<=d,g=s.map(j=>{const S=a.get(j.targetId)?.get(h.sessionId),M=n.get(`${h.sessionId}:${j.targetId}`)??null,y=M?.status??null,P=y==="booked"||y==="checked_in",{isPast:U,pastActionReason:F}=Bu(h.endTime,d),A=!m&&!f&&y==="booked"&&!U,D=pu(j,S,i,o),R=F||D.disabledReason,w=!i||fx(R);
2return{targetId:j.targetId,targetType:j.targetType,firstName:bx(j.displayName),canBook:!m&&!f&&!U&&!P&&D.canBook,eligibilityBlocked:w,isBooked:P,canCancel:A,isPast:U,disabledReason:R,bookingUuid:M?.bookingUuid??null,bookingWindowReason:S?.bookingWindowReason??null}}),v=g.filter(j=>j.isBooked).map(j=>j.firstName),N=v.length>0,x=!N&&g.length>0&&g.every(j=>!j.canBook),k=!f&&x&&g.every(j=>j.eligibilityBlocked);return{session:h,instructorSummary:l.get(h.sessionId)??null,actions:g,bookedNames:v,allUnavailable:x,compactUnavailable:k,hasJoined:N,bookingClosed:p||g.some(j=>j.bookingWindowReason==="class_started"),eventRegistrations:c.get(h.sessionId)??[]}})}function yx(t,s){return ma(t.startAt,s)??ma(t.endAt,s)}function vx(){const t=tt(),s=mt(),[n,a]=r.useState(()=>T.tenant.getTenantTimezone()),{themeMode:i}=ln(),{refreshSession:o,user:l}=Ge(),c=Qe(l),u=ii(l),d=l?.accessPolicy?.memberExperienceMode==="booking_beta",h=l?.id??null,m=un(l),f=l?.accessPolicy?.canBook!==!1,b=l?.accessPolicy?.bookingBlockedReason??null,p=r.useRef(null),g=r.useRef(null),v=r.useRef(null),N=r.useRef(null),x=r.useRef(null),k=r.useRef(null),j=r.useRef(null),I=r.useRef(null),S=r.useRef(null),M=r.useRef({previous:0,current:0,next:0}),y=r.useRef(new Map),P=r.useRef(""),U=r.useRef(0),F=r.useRef(0),A=r.useRef(Va(n)),D=r.useMemo(()=>ga(E=>window.requestAnimationFrame(E),E=>window.cancelAnimationFrame(E)),[]),R=r.useMemo(()=>ga(E=>window.requestAnimationFrame(E),E=>window.cancelAnimationFrame(E),"--member-calendar-selection-offset"),[]),w=r.useMemo(()=>ga(E=>window.requestAnimationFrame(E),E=>window.cancelAnimationFrame(E)),[]),_=r.useMemo(()=>nx(E=>window.requestAnimationFrame(E),E=>window.cancelAnimationFrame(E)),[]),W=r.useMemo(()=>Gr((E,X)=>window.setTimeout(E,X),E=>window.clearTimeout(E),Il),[]),H=r.useMemo(()=>Gr((E,X)=>window.setTimeout(E,X),E=>window.clearTimeout(E),Il),[]),ne=r.useMemo(()=>ox(i),[i]),K=r.useMemo(()=>dx(s.search),[s.search]),ye=r.useMemo(()=>ix(l?.tenantUuid,l?.id),[l?.id,l?.tenantUuid]),de=s.pathname==="/timetable",[O,L]=r.useState(()=>K??ye?.selectedDateKey??Va(n)),Z=r.useRef(ye?.scrollTop??0),ce=r.useRef(K),me=r.useRef(K),Ne=r.useRef(O),[ve,xe]=r.useState([]),[G,J]=r.useState([]),[ke,Be]=r.useState([]),[fe,Ae]=r.useState(()=>ye?.selectedClassTypeId??""),[lt,be]=r.useState([]),[We,Fe]=r.useState(new Map),[Ke,ue]=r.useState(new Map),[Se,pe]=r.useState(new Map),[ae,ge]=r.useState(new Map),[qe,Me]=r.useState(()=>Date.now()),[,Ie]=r.useState(0),ie=r.useMemo(()=>sx({cache:(E,X)=>{y.current.set(E,X),Ie(ee=>ee+1)},isCached:E=>y.current.has(E),load:async(E,X)=>{const ee=await T.timetable.getSnapshot({rangeStart:E,rangeEnd:E},{tenantUuid:l?.tenantUuid??null,memberUuid:l?.id??""},{signal:X,forceRefresh:!0});return qi(ee,E)}}),[l?.id,l?.tenantUuid]),[Xe,ct]=r.useState(null),st=Xc(),[xt,Et]=r.useState(null),te=r.useMemo(()=>ve.map(E=>E.targetId).filter(E=>E!==""),[ve]).join(","),[B,Y]=r.useState(!1),[oe,Ue]=r.useState(null),[_e,He]=r.useState(""),[kt,rt]=r.useState(""),[Lt,Ft]=r.useState(!1),[Pt,Rs]=r.useState(!0),[es,ht]=r.useState(!1),[vs,jt]=r.useState(""),[Kt,Rt]=r.useState(""),[Wt,Yt]=r.useState(null),Ts=r.useRef(null),At=r.useRef(0),is=r.useRef(null),[ts,os]=r.useState(0),[Zs,bt]=r.useState(!1),[hs,Js]=r.useState(0),[ps,Qt]=r.useState(null),[ls,qt]=r.useState(null),$=r.useRef(0),le=r.useRef(null),Ve=r.useRef(new Set),ot=r.useRef(0),[_t,Ns]=r.useState(0),[Xs,Ls]=r.useState(!1),[Ht,Q]=r.useState({isOpen:!1,sessionId:"",sessionTitle:"",actions:[]}),[je,we]=r.useState({open:!1,title:"",message:"",color:"medium"}),[Oe,ut]=r.useState({open:!1,message:""}),[Ze,Nt]=r.useState(null),wt=r.useRef(null);ce.current=K,r.useEffect(()=>{A.current=O},[O]);const Vt=r.useCallback(()=>{try{window.sessionStorage.setItem(Fu(l?.tenantUuid,l?.id),JSON.stringify({selectedDateKey:A.current,selectedClassTypeId:fe,scrollTop:Z.current}))}catch{}},[fe,l?.id,l?.tenantUuid]);r.useEffect(()=>{de&&Vt()},[de,Vt,O]),r.useEffect(()=>{!de||Pt||Z.current<=0||v.current?.scrollToPoint(0,Z.current,0)},[Pt,de]);const ks=r.useCallback(E=>{const X=Yd(E);U.current=X,Me(Date.now()+X)},[]);r.useEffect(()=>{if(!de)return;const E=window.setInterval(()=>{Me(Date.now()+U.current)},15e3);return()=>window.clearInterval(E)},[de]),r.useEffect(()=>{ku(v.current)},[O]),r.useEffect(()=>{if(!de)return;const E=new AbortController;return T.timetable.getTimetableFilters({signal:E.signal}).then(X=>{Be(Array.isArray(X.classTypes)?X.classTypes:[])}).catch(()=>{Be([])}),()=>E.abort()},[de]),r.useEffect(()=>{if(!de||!m){ct(null);return}const E=new AbortController,X=[void 0,...te===""?[]:te.split(",")];return Promise.allSettled(X.map(ee=>T.me.listForms({targetMemberUuid:ee,signal:E.signal}))).then(ee=>{const Pe=ee.flatMap(De=>De.status==="fulfilled"?[De.value]:[]);ct(Cm(Pe,{requiredOnly:d}))}).catch(()=>{ct(null)}),()=>{E.abort()}},[te,d,de,m]),r.useEffect(()=>{if(!de||!h){Et(null);return}const E=new AbortController;let X=!1;const ee=()=>{X||E.signal.aborted||(X=!0,T.me.getProfile({signal:E.signal}).then(De=>{E.signal.aborted||Et(De)}
2).catch(()=>{E.signal.aborted||Et(null)}).finally(()=>{X=!1}))};ee();const Pe=qh(ee);return()=>{Pe(),E.abort()}},[h,de]);const bs=r.useMemo(()=>{if(!d)return"/forms";const E=`${s.pathname}${s.search}${s.hash}`;return`/forms?scope=required&next=${encodeURIComponent(E)}`},[d,s.hash,s.pathname,s.search]);r.useEffect(()=>{const E=Vg({isActive:de,previousRequestedDateKey:me.current,requestedDateKey:K,previousSelectedDateKey:Ne.current,selectedDateKey:O});if(me.current=K,Ne.current=O,E?.type==="select-requested"){L(E.dateKey);return}if(E?.type!=="sync-url")return;const X=new URLSearchParams(s.search);X.set("date",E.dateKey),t.replace({pathname:s.pathname,search:`?${X.toString()}`})},[t,de,s.pathname,s.search,K,O]);const pr=r.useCallback(E=>{E&&we({open:!0,title:E.title,message:E.message,color:E.color,actionLabel:E.actionLabel,actionUrl:E.actionUrl})},[]),fs=r.useCallback(E=>{wt.current=E},[]),Pa=r.useCallback(()=>{const E=wt.current;E&&(wt.current=null,pr(E))},[pr]),Sn=r.useCallback(()=>{ie.invalidate(),y.current.clear(),Ie(E=>E+1)},[ie]),ss=r.useCallback(E=>{a(E.timezone),J(E.sessions),be(E.closures),ue(E.bookingsIndex),Fe(E.availabilityByTarget),pe(E.instructorOccurrences),ge(E.eventRegistrationsByOccurrence)},[]),ea=r.useCallback(E=>{const X=new Map(ux(E).map(ee=>[ee,qi(E,ee)]));for(const[ee,Pe]of X)y.current.set(ee,Pe);return xe(E.bookingTargets.items),Ie(ee=>ee+1),X},[]),dn=r.useCallback(async(E,X,ee=!1)=>{const Pe=await T.timetable.getSnapshot(cx(E),{tenantUuid:l?.tenantUuid??null,memberUuid:l?.id??""},{signal:X,forceRefresh:ee,onBackgroundRefresh:$e=>{const dt=ea($e),ze=A.current,et=dt.get(ze);et&&ss(et)}});return ea(Pe).get(E)??qi(Pe,E)},[ss,ea,l?.id,l?.tenantUuid]),en=r.useCallback(E=>ie.ensure(E),[ie]),mn=r.useCallback(E=>{Ve.current.has(E)||(Ve.current.add(E),en(E))},[en]),Pn=r.useCallback(async E=>{y.current.has(E)&&await Promise.all(tx(E).map(X=>en(X)))},[en]),hn=r.useCallback(async(E,X={},ee)=>{const Pe=X.preferCache??!0,De=X.silent??!1,$e=X.applyToView??!De,dt=X.showLoader??!De,ze=Pe?y.current.get(E):void 0;if(ze){$e&&(ss(ze),jt("")),dt&&ht(!1);return}dt&&(ht(!0),jt(""));try{const et=await dn(E,ee,!Pe),Ct={timezone:et.timezone,sessions:et.sessions.slice(),closures:et.closures.slice(),bookingsIndex:new Map(et.bookingsIndex),availabilityByTarget:jx(et.availabilityByTarget),instructorOccurrences:new Map(et.instructorOccurrences),eventRegistrationsByOccurrence:new Map(Array.from(et.eventRegistrationsByOccurrence.entries(),([Gt,cs])=>[Gt,cs.slice()]))};y.current.set(E,Ct),$e&&(ss(Ct),jt(""))}catch(et){const Ct=na(et,"We could not load the timetable. Please try again.");Ct&&$e&&(jt(Ct),J([]),be([]),ue(new Map),Fe(new Map),pe(new Map),ge(new Map))}finally{dt&&ht(!1)}},[ss,dn]),_s=r.useCallback(async(E,X={},ee)=>{y.current.delete(E),await hn(E,{preferCache:!1,applyToView:X.applyToView,silent:X.silent,showLoader:X.showLoader},ee)},[hn]),hi=r.useCallback(async()=>{const E=A.current;jt(""),Sn();const X=await dn(E,void 0,!0);ss(X)},[ss,Sn,dn]);r.useEffect(()=>{if(!de)return;const E=new AbortController,X=F.current+1;F.current=X;const ee=Va(n),De=ce.current??ee,$e=()=>F.current===X&&!E.signal.aborted;return Rs(!0),jt(""),(async()=>{try{Sn();const ze=await dn(De,E.signal);if(!$e())return;L(De),ss(ze)}catch(ze){if(!$e())return;const et=na(ze,"We could not load the timetable. Please try again.");et&&jt(et)}finally{$e()&&Rs(!1)}})(),()=>{E.abort()}},[ss,Sn,dn,de,n]),r.useEffect(()=>{if(!de||Pt)return;const E=new AbortController;return(async()=>(await hn(O,{preferCache:!0},E.signal),E.signal.aborted||await Pn(O)))(),()=>{E.abort()}},[ve,Pt,de,hn,Pn,O]),r.useEffect(()=>{if(!de||Pt)return;const E=Wi(O),X=as(E,6),ee=`${E}T00:00:00.000Z`,Pe=`${X}T23:59:59.999Z`;let De=!1;P.current="";const $e=new AbortController,dt=et=>new Promise(Ct=>{window.setTimeout(Ct,et)});return(async()=>{for(;!De&&!$e.signal.aborted;)try{const et=P.current.trim()!=="",Ct=await T.timetable.waitForTimetablePush({rangeStart:ee,rangeEnd:Pe,cursor:P.current||null,timeoutSec:20},{signal:$e.signal});if(De||$e.signal.aborted)return;if(typeof Ct.cursor=="string"&&Ct.cursor.trim()!==""&&(P.current=Ct.cursor.trim()),Ct.serverTime&&ks(Ct.serverTime),et&&Ct.changed&&Ct.events.length>0){const cs=A.current,sa=new Set(Er(Wi(cs))),sn=Array.from(new Set(Ct.events.map(Ot=>yx(Ot,n)).filter(Ot=>!!Ot).filter(Ot=>sa.has(Ot))));if(sn.length===0)continue;const Tt=sn.filter(Ot=>Ot===cs||y.current.has(Ot));if(Tt.length===0)continue;await Promise.all(Tt.map(Ot=>_s(Ot,{applyToView:Ot===cs,silent:Ot!==cs,showLoader:!1},$e.signal)))}}catch(et){if(et instanceof DOMException&&et.name==="AbortError"||et?.name==="AbortError"||De||$e.signal.aborted)return;await dt(1500)}})(),()=>{De=!0,$e.abort()}},[Pt,de,_s,O,n,ks]);const pn=r.useMemo(()=>Wi(O),[O]),pi=r.useMemo(()=>Er(as(pn,-7)),[pn]),br=r.useMemo(()=>Er(pn),[pn]),bn=r.useMemo(()=>Er(as(pn,7)),[pn]),Ra=r.useMemo(()=>Fi(G,fe),[fe,G]),Rn=r.useMemo(()=>Hi(Ra,ve,Ke,We,f,b,Se,ae,qe),[We,ve,Ke,qe,ae,Se,b,f,Ra]),Ta=r.useMemo(()=>as(O,-1),[O]),_a=r.useMemo(()=>as(O,1),[O]),Ce=y.current.get(Ta)??null,zt=y.current.get(_a)??null,tn=r.useMemo(()=>Ce?Hi(Fi(Ce.sessions,fe),ve,Ce.bookingsIndex,Ce.availabilityByTarget,f,b,Ce.instructorOccurrences,Ce.eventRegistrationsByO
2ccurrence,qe):[],[ve,qe,b,f,Ce,fe]),Ma=r.useMemo(()=>zt?Hi(Fi(zt.sessions,fe),ve,zt.bookingsIndex,zt.availabilityByTarget,f,b,zt.instructorOccurrences,zt.eventRegistrationsByOccurrence,qe):[],[ve,qe,b,f,zt,fe]),Tn=r.useCallback(E=>{Ue(E),He(""),rt("")},[]),_n=r.useCallback(async(E,X,ee,Pe)=>{const De=`book:${E}:${X}`,$e=G.find(dt=>dt.sessionId===E)??null;Rt(De),ut({open:!0,message:"Booking..."});try{await T.bookings.createBooking({classOccurrenceUuid:E,forMemberUuid:X}),sc(),await _s(O,{applyToView:!0,silent:!1,showLoader:!1}),fs(mu({sessionTitle:$e?.title??null,sessionStartTime:$e?.startTime??null,timezone:n,targetName:Pe,audience:ee}))}catch(dt){if(qg(dt)){Tn({sessionId:E,targetId:X,targetType:ee,targetName:Pe});return}const ze=ou(dt,`${s.pathname}${s.search}${s.hash}`);if(ze){t.push(ze);return}if(lu(dt)){t.push(cu(`${s.pathname}${s.search}${s.hash}`,ee==="child"?X:null,ee==="child"?ve.find(Gt=>Gt.targetId===X)?.displayName??Pe:null));return}const et=Cc(dt),Ct=du(dt,n);fs(et?{title:"Programme access",message:et.message,color:"warning",actionLabel:et.label,actionUrl:et.url}:Ct??er(na(dt,"We could not book this class. Please try again."),"danger"))}finally{ut({open:!1,message:""}),Rt("")}},[ve,t,s.hash,s.pathname,s.search,Tn,fs,_s,O,G,n]),Is=r.useCallback(async(E,X,ee,Pe)=>{if(Wg(ve,X)){Tn({sessionId:E,targetId:X,targetType:ee,targetName:Pe});return}await _n(E,X,ee,Pe)},[ve,Tn,_n]),bi=r.useCallback(async()=>{if(!oe||Lt)return;const E=_e.trim();if(!Hg(E,Va(n))){rt("Enter a valid date of birth that is not in the future.");return}Ft(!0),rt("");try{await T.me.updateBookingTargetDob(oe.targetId,E),xe(ee=>ee.map(Pe=>Pe.targetId===oe.targetId?{...Pe,dob:E}:Pe));const X=oe;Ue(null),He(""),await _n(X.sessionId,X.targetId,X.targetType,X.targetName)}catch(X){rt(na(X,"We could not save the date of birth. Please try again."))}finally{Ft(!1)}},[_e,Lt,oe,_n,n]),$s=r.useCallback(async(E,X,ee,Pe)=>{const De=`cancel:${X}`,$e=G.find(dt=>dt.sessionId===E)??null;Rt(De),ut({open:!0,message:"Cancelling..."});try{await T.bookings.cancelBooking(X),await zg(o,()=>_s(O,{applyToView:!0,silent:!1,showLoader:!1})),fs(hu({sessionTitle:$e?.title??null,sessionStartTime:$e?.startTime??null,timezone:n,targetName:Pe,audience:ee}))}catch(dt){fs(er(na(dt,"We could not cancel this booking. Please try again."),"danger"))}finally{ut({open:!1,message:""}),Rt("")}},[fs,_s,o,O,G,n]),fi=r.useCallback(async E=>{ut({open:!0,message:"Cancelling event registration..."});try{await T.commerce.cancelMemberWorkshopRegistration(E.registrationUuid,"Cancelled in member app"),await _s(O,{applyToView:!0,silent:!1,showLoader:!1}),fs({title:"Event registration cancelled",message:Dm({attendeeName:E.attendeeName,amountMinor:E.amountMinor,refundAvailable:E.cancellationRefundAvailable}),color:"success"})}catch(X){fs(er(na(X,"We could not cancel this event registration. Please try again."),"danger"))}finally{ut({open:!1,message:""})}},[fs,_s,O]),ta=r.useCallback((E,X,ee)=>{const Pe=ee.filter(De=>$l(De));Pe.length<=1||Q({isOpen:!0,sessionId:E,sessionTitle:X,actions:Pe})},[]),ws=r.useCallback(()=>{Q({isOpen:!1,sessionId:"",sessionTitle:"",actions:[]})},[]),Cs=r.useCallback(()=>{const E=ee=>Math.ceil(ee?.scrollHeight??0),X={previous:E(j.current),current:E(I.current),next:E(S.current)};return M.current=X,X},[]),fr=r.useMemo(()=>Ht.actions.map(E=>{const X=E.isBooked?`cancel:${E.bookingUuid??""}`:`book:${Ht.sessionId}:${E.targetId}`,Pe=Kt===X||(E.isBooked?!E.canCancel||!E.bookingUuid:!E.canBook);return{key:E.targetId,label:E.firstName.toUpperCase(),mode:E.isBooked?"cancel":"book",disabled:Pe,onSelect:()=>{if(E.isBooked){E.bookingUuid&&E.canCancel&&$s(Ht.sessionId,E.bookingUuid,E.targetType,E.firstName);return}E.canBook&&Is(Ht.sessionId,E.targetId,E.targetType,E.firstName)}}}),[Kt,Is,$s,Ht.actions,Ht.sessionId]),gr=r.useCallback((E,X)=>{if(W.isActive()||H.isActive())return;const ee=xs(g.current);ee!==null&&(os(ee),Yt(E),Ts.current=X,At.current=Date.now(),is.current=null,D.flush(g.current,0))},[H,D,W]),xr=r.useCallback(E=>{if(Wt===null||Ts.current===null)return;const X=E.clientX-Wt,ee=E.clientY-Ts.current,Pe=is.current??Kr(X,ee,Date.now()-At.current);if(is.current===null&&Pe!==null&&(is.current=Pe),Pe!=="x")return;E.currentTarget.hasPointerCapture(E.pointerId)||E.currentTarget.setPointerCapture(E.pointerId);const De=Math.max(120,ts*.95),$e=Math.max(-De,Math.min(De,X));D.queue(g.current,$e)},[Wt,D,ts]),fn=r.useCallback(E=>{if(E===0){g.current?.classList.remove("is-animating"),D.flush(g.current,0),bt(!1);return}const X=as(A.current,E*7),ee=y.current.get(X);xa.flushSync(()=>{ee?(ss(ee),jt(""),ht(!1)):(jt(""),ht(!0)),A.current=X,L(X),bt(!1)}),g.current?.classList.remove("is-animating"),D.flush(g.current,0)},[ss,D]),Ua=r.useCallback((E=!1)=>
2{if(Wt===null)return;const X=xs(g.current)??0,ee=D.getOffset(),Pe=Math.max(36,Math.min(84,X*.18)),De=is.current;let $e=0,dt=0;!E&&X>0&&De==="x"&&Math.abs(ee)>=Pe?($e=ee<0?1:-1,dt=$e===1?-X:X,Js(Date.now()+220)):De==="x"&&Js(Date.now()+180),Yt(null),Ts.current=null,is.current=null;const ze=De==="x"&&(Math.abs(ee)>0||$e!==0);if(bt(ze),!ze){D.flush(g.current,0);return}if(!W.start($e,fn)){D.flush(g.current,0),bt(!1);return}g.current?.classList.add("is-animating"),D.flush(g.current,dt)},[fn,Wt,D,W]),jr=r.useCallback(E=>{E.target!==E.currentTarget||E.propertyName!=="transform"||W.complete()},[W]),Mn=r.useCallback((E,X=!1)=>{const ee=(new Date(`${A.current}T12:00:00`).getDay()+6)%7,Pe=Nu(ee,E,X?xs(k.current)??_t:_t,X?xs(g.current)??ts:ts);p.current?.classList.toggle("is-selection-animating",X),g.current?.classList.toggle("is-animating",X),X?(R.flush(p.current,Pe.selectionOffset),D.flush(g.current,Pe.weekOffset)):(R.queue(p.current,Pe.selectionOffset),D.queue(g.current,Pe.weekOffset))},[_t,R,D,ts]),Ms=r.useCallback(()=>{p.current?.classList.remove("is-selection-animating"),g.current?.classList.remove("is-animating"),R.flush(p.current,0),D.flush(g.current,0)},[R,D]),yr=r.useCallback(E=>{if(H.isActive()||W.isActive()||Pt||es||E.pointerType==="mouse"&&E.button!==0)return;const X=E.target;if(!X||X.closest(".member-timetable-sticky-panel")||X.closest(".member-session-action-btn")||X.closest("a"))return;const ee=xs(k.current),Pe=xs(g.current);if(ee===null||Pe===null)return;Ns(ee),os(Pe),Qt(E.clientX),qt(E.clientY),$.current=Date.now(),le.current=null,Ve.current.clear(),w.flush(k.current,0);const De=Cs();_.flush(x.current,De.current)},[w,H,_,Pt,es,Cs,W]),gi=r.useCallback(E=>{if(ps===null||ls===null)return;const X=E.clientX-ps,ee=E.clientY-ls,Pe=le.current??Kr(X,ee,Date.now()-$.current);if(le.current===null&&Pe!==null&&(le.current=Pe),Pe!=="x")return;E.currentTarget.hasPointerCapture(E.pointerId)||E.currentTarget.setPointerCapture(E.pointerId);const De=Math.max(120,_t*.95);let $e=Math.max(-De,Math.min(De,X));const dt=as(A.current,$e<0?1:-1);$e!==0&&!y.current.has(dt)&&(M.current=$e<0?{...M.current,next:0}:{...M.current,previous:0},$e=0,mn(dt));let ze=M.current;const et=$e<0?ze.next:ze.previous;if($e!==0&&et<=0&&(ze=Cs()),$e!==0){const Ct=Math.min(1,Math.abs($e)/Math.max(1,_t)),Gt=$e<0?ze.next:ze.previous;_.queue(x.current,Ll(ze.current,Gt,Ct))}Mn($e),w.queue(k.current,$e)},[Mn,w,_,_t,ps,ls,Cs,mn]),vr=r.useCallback(E=>{if(E===0){k.current?.classList.remove("is-animating"),w.flush(k.current,0),Ms(),_.clear(x.current),Ls(!1);return}const X=as(A.current,E),ee=y.current.get(X);if(!ee){k.current?.classList.remove("is-animating"),w.flush(k.current,0),Ms(),_.clear(x.current),Ls(!1),en(X);return}xa.flushSync(()=>{ss(ee),jt(""),ht(!1),A.current=X,L(X),Ls(!1)}),k.current?.classList.remove("is-animating"),w.flush(k.current,0),Ms(),_.clear(x.current),Pn(X)},[Ms,ss,w,_,Pn,en]),Ea=r.useCallback(E=>{if(E?.currentTarget.hasPointerCapture(E.pointerId)&&E.currentTarget.releasePointerCapture(E.pointerId),ps===null)return;const X=le.current==="x";X&&(ot.current=Date.now()+220);const ee=xs(k.current)??0,Pe=w.getOffset(),De=Math.max(42,Math.min(96,ee*.18));let $e=0,dt=0;if(E?.type!=="pointercancel"&&ee>0&&X&&Math.abs(Pe)>=De&&($e=Pe<0?1:-1,dt=$e===1?-ee:ee),$e!==0){const Gt=as(A.current,$e);y.current.has(Gt)||(mn(Gt),$e=0,dt=0)}Qt(null),qt(null),le.current=null,Ve.current.clear();const ze=X&&(Math.abs(Pe)>0||$e!==0);if(Ls(ze),!ze){w.flush(k.current,0),Ms(),_.clear(x.current);return}if(!H.start($e,vr)){w.flush(k.current,0),Ms(),_.clear(x.current),Ls(!1);return}const et=M.current,Ct=$e<0?et.previous:$e>0?et.next:et.current;_.flush(x.current,Ll(et.current,Ct,1),!0),Mn(dt,!0),k.current?.classList.add("is-animating"),w.flush(k.current,dt)},[Mn,Ms,w,H,_,vr,ps,mn]),Nr=r.useCallback(E=>{E.target!==E.currentTarget||E.propertyName!=="transform"||H.complete()},[H]);r.useEffect(()=>()=>{R.cancel(),D.cancel(),w.cancel(),_.clear(x.current),W.cancel(),H.cancel(),ie.dispose()},[R,w,H,_,ie,D,W]);const It=r.useCallback((E,X)=>E.map(ee=>{const Pe=ee.session.sessionId,De=ee.actions.filter(ft=>$l(ft)),$e=De.length>1,dt=Gg(De),ze=De[0]??ee.actions[0]??null,et=ee.instructorSummary?ax(ee.instructorSummary):null,Ct=typeof ee.session.spotsRemaining=="number"?`${ee.session.spotsRemaining} spots left`:"Spots available",Gt=ee.session.status==="cancelled",cs=ee.session.status==="closed",{isPast:sa}=Bu(ee.session.endTime,qe),sn=!!ee.session.workshop,Tt=Yg(ee.session.instructors,ee.session.instructorName||ee.instructorSummary?.instructorName),Ot=Qg(ee.session),xi=Lo(Ot,ne,3),Aa=Ql(ee.session.programmeFocus?.colour),gn=Aa?Lo(Aa,ne,3):null,ji=gn?{"--member-session-theme-bg":gn,"--member-session-theme-text":Kl(gn)}:void 0,Da=Zg(ee.session),xn=ee.eventRegistrations[0]??null,La=Gt?"Cancelled":cs?"Booking Closed":xn?"Registered":ee.hasJoined?"Joined":null,Ia=!Gt&&!cs&&!ee.bookingClosed,yi={"--member-session-class-color":xi},nn=(ft="members")=>{Vt(),t.push(yu(Pe,ft))};return e.jsxs("article",{className:`member-session-card${c?" is-instructor-manageable":""}${ee.compactUnavailable&&!Gt?" is-compact-unavailable":""}${ee.hasJoined?" is-joined":""}${Gt?" is-cancelled":""}${cs?" is-closed":""}${sa?" is-past":""}`,style:yi,role:c?"button":void 0,tabIndex:c?0:void 0,"aria-label":c?`Open class management for ${ee.session.title}`:void 0,onClick:c?()=>{Date.now()>=ot.current&&nn("members")}:void 0,onKeyDown:c?ft=>
2{ft.target!==ft.currentTarget||ft.key!=="Enter"&&ft.key!==" "||(ft.preventDefault(),nn("members"))}:void 0,children:[e.jsxs("div",{className:"member-session-top",children:[e.jsxs("div",{children:[e.jsx("p",{className:"member-session-time",children:px(ee.session,n)}),e.jsx("h3",{className:"member-session-title",children:ee.session.workshop?.title||ee.session.title}),ee.session.programmeFocus?.title?e.jsxs("div",{className:"member-session-theme",children:[e.jsx("span",{className:"member-session-theme-badge",style:ji,children:ee.session.programmeFocus.title}),ee.session.programmeFocus.detail?e.jsx("small",{className:"member-session-theme-detail",children:ee.session.programmeFocus.detail}):null]}):null,ee.session.workshop?e.jsxs("p",{className:"member-session-workshop-day",children:[ee.session.workshop.eventType==="seminar"?"Seminar":"Workshop"," · Day ",ee.session.workshop.sessionNumber," of ",ee.session.workshop.sessionCount]}):null]}),c&&!sn&&(Tt||u)?u?e.jsxs("button",{type:"button",className:"member-session-instructor is-card-corner is-assignment-trigger","aria-label":`Manage instructors for ${ee.session.title}`,onClick:ft=>{ft.stopPropagation(),t.push(ub(Pe))},children:[e.jsx("span",{className:`member-session-lead-avatar${Tt?"":" is-unassigned"}`,"aria-hidden":"true",children:Tt?.avatarUrl?e.jsx("img",{src:Tt.avatarUrl,alt:""}):Tt?Tt.displayName.charAt(0).toUpperCase():e.jsx(V,{icon:qs})}),e.jsx("span",{className:"member-session-instructor-copy",children:e.jsx("strong",{children:Tt?Tt.displayName.trim().split(/\s+/)[0]:"Unassigned"})})]}):e.jsxs("div",{className:"member-session-instructor is-card-corner","aria-label":`Instructor ${Tt?.displayName||""}`,children:[e.jsx("span",{className:"member-session-lead-avatar","aria-hidden":"true",children:Tt?.avatarUrl?e.jsx("img",{src:Tt.avatarUrl,alt:""}):Tt?.displayName.charAt(0).toUpperCase()}),e.jsx("span",{className:"member-session-instructor-copy",children:e.jsx("strong",{children:Tt?.displayName.trim().split(/\s+/)[0]})})]}):null]}),Gt?e.jsxs("div",{className:"member-session-cancellation-reason",children:[e.jsx("strong",{children:"Cancellation reason"}),e.jsx("span",{children:ee.session.cancellationReason||"No reason was provided."})]}):ee.compactUnavailable?null:e.jsxs(e.Fragment,{children:[c&&ee.instructorSummary?e.jsx("div",{className:`member-instructor-class-stats${sn?" is-event":""}`,role:"group","aria-label":sn?"Open event attendees by status":"Open class attendees by status",children:sn?e.jsxs(e.Fragment,{children:[e.jsxs("button",{type:"button","aria-label":"Open attendees",onClick:ft=>{ft.stopPropagation(),nn("members")},children:[e.jsx(V,{icon:As,"aria-hidden":"true"}),e.jsxs("span",{children:[e.jsx("strong",{children:et?.attendeeCapacityValue}),e.jsx("small",{children:"Attendees"})]})]}),e.jsxs("button",{type:"button","aria-label":"Open cancelled attendees",onClick:ft=>{ft.stopPropagation(),nn("cancelled")},children:[e.jsx(V,{icon:pa,"aria-hidden":"true"}),e.jsxs("span",{children:[e.jsx("strong",{children:et?.cancelledValue}),e.jsx("small",{children:"Cancelled"})]})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("button",{type:"button","aria-label":"Open members",onClick:ft=>{ft.stopPropagation(),nn("members")},children:[e.jsx(V,{icon:As,"aria-hidden":"true"}),e.jsxs("span",{children:[e.jsx("strong",{children:et?.memberCapacityValue}),e.jsx("small",{children:"Members"})]})]}),e.jsxs("button",{type:"button","aria-label":"Open trials",onClick:ft=>{ft.stopPropagation(),nn("trials")},children:[e.jsx(V,{icon:bm,"aria-hidden":"true"}),e.jsxs("span",{children:[e.jsx("strong",{children:et?.trialValue}),e.jsx("small",{children:"Trials"})]})]}),e.jsxs("button",{type:"button","aria-label":"Open cancelled bookings",onClick:ft=>{ft.stopPropagation(),nn("cancelled")},children:[e.jsx(V,{icon:pa,"aria-hidden":"true"}),e.jsxs("span",{children:[e.jsx("strong",{children:et?.cancelledValue}),e.jsx("small",{children:"Cancelled"})]})]})]})}):null,c?null:e.jsxs("div",{className:"member-session-member-meta",children:[e.jsx("div",{className:"member-session-availability",children:e.jsxs("span",{children:[e.jsx(V,{icon:As}),Ct]})}),Tt?e.jsxs("div",{className:"member-session-instructor","aria-label":`Instructor ${Tt.dis
2playName}`,children:[e.jsx("span",{className:"member-session-lead-avatar","aria-hidden":"true",children:Tt.avatarUrl?e.jsx("img",{src:Tt.avatarUrl,alt:""}):Tt.displayName.charAt(0).toUpperCase()}),e.jsx("span",{className:"member-session-instructor-copy",children:e.jsx("strong",{children:Tt.displayName.trim().split(/\s+/)[0]})})]}):null]})]}),e.jsxs("div",{className:"member-session-footer",children:[e.jsxs("div",{className:"member-session-class-details",children:[e.jsx("span",{className:"member-session-age",children:Da}),La?e.jsx("span",{className:"member-session-state-label",children:La}):null]}),e.jsx("div",{className:"member-session-actions-single",children:cs||ee.bookingClosed?e.jsx("span",{className:"member-session-status-pill",role:"status",children:cs?"Booking Closed":"Booking closed"}):!c&&Ia&&ee.session.workshop?e.jsxs("button",{type:"button",className:`member-session-action-btn ${xn?"is-cancel":"is-book"}`,onClick:ft=>{if(ft.stopPropagation(),xn?.canCancelOnline){Nt(xn);return}t.push(`/events/details/${encodeURIComponent(ee.session.workshop?.slug||"")}`)},children:[e.jsx("span",{children:xn?"CANCEL":"REGISTER"}),e.jsx(V,{icon:xn?zn:qr})]}):Ia&&!ee.session.workshop&&$e?e.jsxs("button",{type:"button",className:`member-session-action-btn${ee.hasJoined?" is-cancel":" is-book"} is-sheet-trigger`,onPointerDown:ft=>{ft.stopPropagation()},onTouchStart:ft=>{ft.stopPropagation()},onClick:ft=>{ft.stopPropagation(),ta(Pe,ee.session.title,De)},children:[e.jsx("span",{children:dt}),e.jsx(V,{icon:jo})]}):Ia&&!ee.session.workshop&&ze?(()=>{const ft=ze.isBooked?`cancel:${ze.bookingUuid??""}`:`book:${Pe}:${ze.targetId}`,kr=Kt===ft||(ze.isBooked?!ze.canCancel||!ze.bookingUuid:!ze.canBook),vi=ze.isBooked?"CANCEL":ee.session.isFull?"FULL":"BOOK";return e.jsxs("button",{type:"button",className:`member-session-action-btn${ze.isBooked?" is-cancel":" is-book"}${kr?" is-disabled":""}`,disabled:kr,title:ze.disabledReason??void 0,onPointerDown:Os=>{Os.stopPropagation()},onTouchStart:Os=>{Os.stopPropagation()},onClick:Os=>{if(Os.stopPropagation(),ze.isBooked){ze.bookingUuid&&ze.canCancel&&$s(Pe,ze.bookingUuid,ze.targetType,ze.firstName);return}ze.canBook&&Is(Pe,ze.targetId,ze.targetType,ze.firstName)},children:[e.jsx("span",{children:vi}),ee.session.isFull&&!ze.isBooked?null:e.jsx(V,{icon:ze.isBooked?zn:qr})]})})():null})]})]},`${X}:${Pe}`)}),[Kt,ne,qe,u,c,Is,$s,t,ta,Vt,n]);return e.jsxs(Cn,{className:"member-timetable-page",children:[e.jsx(So,{}),e.jsxs(wn,{ref:v,fullscreen:!0,forceOverscroll:!1,scrollEvents:!0,onIonScroll:E=>{Z.current=E.detail.scrollTop},className:"member-timetable-content",children:[xt?.memberAppPromptCandidate?xt.memberAppPromptCandidate.repeatOnLoad?null:e.jsx(Co,{memberUuid:xt.member?.uuid??"",promptCandidate:xt.memberAppPromptCandidate}):xt?e.jsx(Bg,{memberUuid:xt?.member?.uuid??"",promptCandidate:xt?.communityGroups.promptCandidate??null}):null,e.jsx(bo,{slot:"fixed",onIonRefresh:E=>{hi().catch(()=>{}).finally(()=>{E.detail.complete()})},children:e.jsx(fo,{})}),e.jsxs("main",{ref:N,className:`member-timetable-main${Xe||st?" has-forms-banner":""}`,onPointerDown:yr,onPointerMove:gi,onPointerUp:Ea,onPointerCancel:Ea,children:[e.jsxs("section",{className:"member-timetable-sticky-panel",children:[e.jsxs("button",{type:"button",className:"member-timetable-date-row",onClick:()=>Y(!0),"aria-label":"Select date",children:[e.jsx("span",{children:hx(O)}),e.jsx(V,{icon:Ut})]}),e.jsxs("div",{ref:p,style:{"--member-calendar-selected-index":br.indexOf(O)},className:`member-timetable-week-strip-viewport has-moving-selection${Wt!==null?" is-dragging":""}`,onPointerDown:E=>{E.pointerType==="mouse"&&E.button!==0||gr(E.clientX,E.clientY)},onPointerMove:xr,onPointerUp:E=>{E.currentTarget.hasPointerCapture(E.pointerId)&&E.currentTarget.releasePointerCapture(E.pointerId),Ua()},onPointerCancel:E=>{E.currentTarget.hasPointerCapture(E.pointerId)&&E.currentTarget.releasePointerCapture(E.pointerId),Ua(!0)},children:[[-1,0,1].map(E=>e.jsx("span",{"aria-hidden":"true",className:"member-timetable-selection",style:{"--member-calendar-selection-copy":E}},E)),e.jsx("div",{ref:g,className:`member-timetable-week-strip member-timetable-gesture-track${Zs?" is-animating":""}`,onTransitionEnd:jr,children:[pi,br,bn].map((E,X)=>e.jsx("div",{className:"member-timetable-week-page",children:E.map((ee,Pe)=>{const De=Jn(ee),$e=ee===O;return e.jsxs("button",{type:"button",className:`member-timetable-day-pill${$e?" is-active":""}`,"aria-pressed":$e,onClick:()=>{Date.now()<hs||Zs||Xs||Math.abs(D.getOffset())>8||L(ee)},children:[e.jsx("span",{className:"member-timetable-day-label",children:lx[Pe]}),e.jsx("span",{className:"member-timetable-day-number",children:De?.day??"--"})]},ee)})},`week-page-${X}`))})]}),ke.length>0?e.jsxs("div",{className:"member-timetable-filter-strip","aria-label":"Filter classes by type",children:[e.jsx("button",{type:"button",className:`member-timetable-filter-pill${fe===""?" is-active":""}`,onClick:()=>Ae(""),children:"All classes"}
2),ke.map(E=>{const X=Jg(G,E.id);return e.jsx("button",{type:"button",className:`member-timetable-filter-pill${fe===E.id?" is-active":""}${X?"":" is-empty"}`,onClick:()=>Ae(E.id),"aria-label":`${E.name}${X?"":", no classes today"}`,children:E.name},E.id)})]}):null]}),e.jsx("div",{ref:x,className:`member-timetable-cards-viewport${ps!==null?" is-dragging":""}`,children:e.jsxs("div",{ref:k,className:`member-timetable-cards-track member-timetable-gesture-track${Xs?" is-animating":""}`,onTransitionEnd:Nr,children:[e.jsx("section",{ref:j,className:"member-timetable-cards-page is-side","aria-hidden":"true",children:e.jsx("section",{className:"member-timetable-cards",children:Ce?tn.length===0?Ce.closures.length>0?e.jsxs("div",{className:"member-timetable-closure",children:[e.jsx("strong",{children:"Gym closed"}),e.jsx("span",{children:Ce.closures[0].reason||"The gym is closed for this day."})]}):e.jsx("div",{className:"member-timetable-empty",children:"No classes available for this day."}):It(tn,Ta):null})}),e.jsx("section",{ref:I,className:"member-timetable-cards-page is-current",children:e.jsxs("section",{className:"member-timetable-cards",children:[Pt||es?e.jsxs("div",{className:"member-timetable-loader",children:[e.jsx(Te,{name:"crescent"}),e.jsx("span",{children:"Loading classes..."})]}):null,!Pt&&!es&&vs?e.jsx("div",{className:"member-timetable-empty",children:vs}):null,!Pt&&!es&&!vs&&Rn.length===0?lt.length>0?e.jsxs("div",{className:"member-timetable-closure",children:[e.jsx("strong",{children:"Gym closed"}),e.jsx("span",{children:lt[0].reason||"The gym is closed for this day."})]}):e.jsx("div",{className:"member-timetable-empty",children:"No classes available for this day."}):null,!Pt&&!es&&!vs?It(Rn,O):null]})}),e.jsx("section",{ref:S,className:"member-timetable-cards-page is-side","aria-hidden":"true",children:e.jsx("section",{className:"member-timetable-cards",children:zt?Ma.length===0?zt.closures.length>0?e.jsxs("div",{className:"member-timetable-closure",children:[e.jsx("strong",{children:"Gym closed"}),e.jsx("span",{children:zt.closures[0].reason||"The gym is closed for this day."})]}):e.jsx("div",{className:"member-timetable-empty",children:"No classes available for this day."}):It(Ma,_a):null})})]})})]}),e.jsx(at,{isOpen:B,className:"member-date-modal",keepContentsMounted:!0,onDidDismiss:()=>Y(!1),children:e.jsx("div",{className:"member-date-modal-content",children:e.jsx(Zr,{presentation:"date",locale:"en-GB",firstDayOfWeek:1,value:O,onIonChange:E=>{const X=Wu(E.detail.value);X&&(L(X),Y(!1))}})})}),e.jsx(at,{isOpen:oe!==null,className:"member-dob-modal",backdropDismiss:!Lt,onDidDismiss:()=>{Lt||(Ue(null),rt(""))},children:e.jsxs("div",{className:"member-dob-modal-content",children:[e.jsx("h2",{children:"Date of birth required"}),e.jsxs("p",{children:["Add ",oe?.targetType==="self"?"your":`${oe?.targetName??"this member"}'s`," date of birth before booking this class."]}),e.jsx("label",{htmlFor:"member-booking-dob",children:"Date of birth"}),e.jsx("input",{id:"member-booking-dob",type:"date",value:_e,max:Va(n),disabled:Lt,onChange:E=>{He(E.target.value),rt("")}}),kt?e.jsx("p",{className:"member-dob-modal-error",role:"alert",children:kt}):null,e.jsxs("div",{className:"member-dob-modal-actions",children:[e.jsx("button",{type:"button",disabled:Lt,onClick:()=>Ue(null),children:"Cancel"}),e.jsx("button",{type:"button",className:"is-primary",disabled:Lt||!_e,onClick:()=>{bi()},children:Lt?"Saving...":"Save and book"})]})]})}),e.jsx(ci,{isOpen:Ht.isOpen,title:Ht.sessionTitle||"Choose member action",actions:fr,onClose:ws}),e.jsx(Xl,{isOpen:Oe.open,message:Oe.message,spinner:"crescent",showBackdrop:!0,cssClass:"member-booking-loading",onDidDismiss:Pa}),e.jsx(Vn,{isOpen:!!Ze,header:"Cancel event registration?",message:Ze?Rc({attendeeName:Ze.attendeeName,amountMinor:Ze.amountMinor,refundAvailable:Ze.cancellationRefundAvailable}):"",cssClass:"member-status-alert member-status-alert-warning",buttons:[{text:"No",role:"cancel"},{text:"Yes, cancel",role:"destructive",handler:()=>{const E=Ze;Nt(null),E&&fi(E)}}],onDidDismiss:()=>Nt(null)}),e.jsx(Vn,{isOpen:je.open,header:je.title||void 0,message:je.message,cssClass:`member-status-alert member-booking-result-alert member-status-alert-${je.color}${je.title?"":" is-titleless"}`,buttons:[...je.actionUrl?[{text:je.actionLabel||"Upgrade",handler:()=>{window.location.assign(je.actionUrl||"/app/memberships")}}]:[],{text:"Close",role:"cancel"}],onDidDismiss:()=>we(E=>({...E,open:!1}))})]}),Xe&&!st&&!Ht.isOpen?e.jsx(Fg,{state:Xe,actionPath:bs}):null,Ht.isOpen?null:e.jsx(Po,{activeTab:"classes"})]})}function Nx(){const t=tt(),{user:s}=Ge(),n=s?.accessPolicy?.memberExperienceMode==="booking_beta",a=Ws(s),[i,o]=r.useState(!0),l=s?.featureFlags?.strengthTrackingEnabled===!0&&i,c=s?.featureFlags?.workoutPlannerEnabled===!0;r.useEffect(()=>{if(!s?.featureFlags?.strengthTrackingEnabled)return;const d=new AbortController;
2return T.training.getPreferences(d.signal).then(h=>o(h.preferences.show_strength_tracker)).catch(()=>{}),()=>d.abort()},[s?.featureFlags?.strengthTrackingEnabled]);const u=[...n?[]:[{label:"Training Progress",description:"See grading progress and your next targets.",path:"/progress",icon:Jr},{label:"Attendance",description:"Review recent attendance patterns and class counts.",path:"/attendance",icon:uc}],...!n&&a?[{label:"Curriculum",description:"Browse your curriculum tree, notes, and checkpoints.",path:"/curriculum",icon:Ar}]:[],...l?[{label:"Strength",description:"Log personal bests and max rep results.",path:"/strength",icon:fm}]:[],...c?[{label:"Class workouts",description:"See published kettlebell class plans.",path:"/workouts",icon:Ut}]:[]];return e.jsxs(Ye,{standardUI:!0,title:"Training",subtitle:n?"Log results and view class workouts.":"Progress, attendance, and curriculum in one place.",activeTab:"none",children:[e.jsxs("section",{className:"member-section",children:[e.jsx("h2",{children:"Training tools"}),e.jsx("div",{className:"member-panel-list member-list--divided",children:u.map(d=>e.jsxs("button",{type:"button",className:"member-panel-row",onClick:()=>t.push(d.path),children:[e.jsxs("div",{className:"member-row-main",children:[e.jsx("strong",{children:d.label}),e.jsx(V,{icon:d.icon})]}),e.jsx("p",{children:d.description})]},d.path))})]}),!n&&!a?e.jsxs("section",{className:"member-section",children:[e.jsx("h2",{children:"Curriculum"}),e.jsx("p",{children:"Curriculum viewing is not enabled for this account yet."})]}):null]})}const Vi=r.forwardRef(function({value:s,onIonInput:n,onIonBlur:a,...i},o){const l=Zd(s??void 0);return e.jsx(kd,{...i,ref:o,type:"number",value:l.value,onIonInput:c=>{l.change(c.detail.value??""),n?.(c)},onIonBlur:c=>
2{a?.(c),l.blur()}})}),kx=()=>new Date().toISOString().slice(0,10);function wx(){const t=tt(),[s]=Yl(),n=s.get("movement")||"",a=s.get("block")||"",i=r.useRef(!1),{user:o}=Ge(),[l,c]=r.useState([]),[u,d]=r.useState([]),[h,m]=r.useState([]),[f,b]=r.useState(!0),[p,g]=r.useState(!1),[v,N]=r.useState(!1),[x,k]=r.useState(!1),[j,I]=r.useState(""),[S,M]=r.useState([]),[y,P]=r.useState(null),[U,F]=r.useState(""),[A,D]=r.useState({movement_uuid:"",performed_on:kx(),result_type:"weight_for_reps",weight:16,weight_unit:"kg",reps:1,side:"both",quality:"",note:"",lesson_plan_block_uuid:void 0}),R=r.useCallback(async O=>{if(o?.featureFlags?.strengthTrackingEnabled){b(!0);try{const[L,Z,ce,me]=await Promise.all([T.training.listMovements(O),T.training.listResults(void 0,O),T.training.listPersonalBests(O),T.training.getPreferences(O)]);if(!me.preferences.show_strength_tracker){t.replace("/training");return}if(c(L),d(Z),m(ce),o?.featureFlags?.strengthLeaderboardsEnabled&&me.preferences.leaderboard_opt_in&&me.workout_settings.leaderboards_enabled){const xe=await T.training.listBenchmarks(O);M(xe.benchmarks||[])}else M([]);const Ne=L.some(xe=>xe.uuid===n)?n:L[0]?.uuid||"",ve=!i.current&&!!(n&&a)&&L.some(xe=>xe.uuid===n);D(xe=>({...xe,movement_uuid:xe.movement_uuid||Ne,weight_unit:me.workout_settings.default_measurement_unit,lesson_plan_block_uuid:ve?a:xe.lesson_plan_block_uuid})),ve&&(i.current=!0,g(!0))}catch(L){F(re(L,"Unable to load strength tracking."))}finally{b(!1)}}},[t,a,n,o?.featureFlags?.strengthLeaderboardsEnabled,o?.featureFlags?.strengthTrackingEnabled]);r.useEffect(()=>{const O=new AbortController;return R(O.signal),()=>O.abort()},[R]);const w=r.useMemo(()=>l.find(O=>O.uuid===A.movement_uuid),[A.movement_uuid,l]),_=r.useMemo(()=>u.filter(O=>O.movement_uuid===A.movement_uuid&&O.result_type===A.result_type),[A.movement_uuid,A.result_type,u]),W=r.useMemo(()=>_.slice(0,12).reverse().map(O=>O.result_type==="weight_for_reps"?O.canonical_weight_kg:O.reps),[_]);function H(O){const L=l.find(Ne=>Ne.uuid===O),Z=L?.allowed_result_types?.length?L.allowed_result_types:["weight_for_reps"],ce=Z.includes(A.result_type)?A.result_type:Z[0],me=u.find(Ne=>Ne.movement_uuid===O&&Ne.result_type===ce);D(Ne=>({...Ne,movement_uuid:O,result_type:ce,weight:me?.weight??Ne.weight,weight_unit:me?.weight_unit??Ne.weight_unit,reps:me?.reps??Ne.reps,side:me?.side??(L?.laterality==="unilateral"||L?.laterality==="either"?"left":"both")}))}function ne(O){const L=u.find(Z=>Z.movement_uuid===A.movement_uuid&&Z.result_type===O);D(Z=>({...Z,result_type:O,weight:L?.weight??Z.weight,weight_unit:L?.weight_unit??Z.weight_unit,reps:L?.reps??Z.reps,side:L?.side??Z.side}))}async function K(){try{await T.training.createResult({...A,quality:A.quality||null,note:A.note.trim()||null}),D(O=>({...O,lesson_plan_block_uuid:void 0})),g(!1),N(!1),F("Result saved."),await R()}catch(O){F(re(O,"Unable to save result."))}}async function ye(){const O=j.trim();if(O)try{const L=await T.training.createMovement(O);c(Z=>[...Z,L]),D(Z=>({...Z,movement_uuid:L.uuid})),I(""),F("Movement added.")}catch(L){F(re(L,"Unable to add movement."))}}async function de(O){try{const L=await T.training.getLeaderboard(O.uuid);P({title:O.title,rows:L})}catch(L){F(re(L,"Unable to load leaderboard."))}}return o?.featureFlags?.strengthTrackingEnabled?e.jsxs(Ye,{standardUI:!0,title:"Strength",subtitle:"Log a result and see your progress.",activeTab:"none",backTo:"/training",onRefresh:R,children:[f?e.jsxs("div",{className:"member-panel-loading",children:[e.jsx(Te,{name:"crescent"}),e.jsx("span",{children:"Loading strength results..."})]}):null,f?null:e.jsxs(e.Fragment,{children:[e.jsxs("section",{className:"member-panel-card member-strength-summary",children:[e.jsxs("div",{className:"member-row-main",children:[e.jsxs("div",{children:[e.jsx("h2",{children:"Movement progress"}),e.jsx("p",{children:"Choose one movement to see comparable results."})]}),e.jsx(vt,{onClick:()=>{D(O=>({...O,lesson_plan_block_uuid:void 0})),g(!0)},children:"Log result"})]}),e.jsx(pt,{children:e.jsx($n,{label:"Movement",labelPlacement:"stacked",value:A.movement_uuid,onIonChange:O=>H(O.detail.value),children:l.map(O=>e.jsx(Fs,{value:O.uuid,children:O.name},O.uuid))})}),h.filter(O=>O.movement_uuid===A.movement_uuid).length?e.jsx("div",{className:"member-strength-best-grid",children:h.filter(O=>O.movement_uuid===A.movement_uuid).map(O=>e.jsxs("article",{children:[e.jsx("strong",{children:"Personal best"}),e.jsx("span",{children:O.result_type==="weight_for_reps"?`${O.weight} ${O.weight_unit} x ${O.reps}`:`${O.reps} reps at ${O.weight} ${O.weight_unit}`}),e.jsx("small",{children:gt(O.side)})]},`${O.uuid}-${O.side}`))}):e.jsx("p",{children:"No results for this movement yet."})]}),e.jsxs("section",{className:"member-panel-card",children:[e.jsx("h2",{children:"History"}),_.length?e.jsx("div",{className:"member-panel-list",children:_.map(O=>e.jsxs("div",{className:"member-panel-row",children:[e.jsxs("div",{className:"member-row-main",children:[e.jsx("strong",{children:O.movement_name}),e.jsxs("span",{children:[O.weight," ",O.weight_unit," x ",O.reps]})]}),e.jsxs("p",{children:[O.performed_on," · ",gt(O.side),O.quality?` · ${gt(O.quality)}`:""]})]},O.uuid))}):e.jsx("p",{children:"Your saved results for this movement will appear here."})]}),W.length>1?e.jsxs("section",{className:"member-panel-card",children:[e.jsx("h2",{children:"Recent progress"}),e.jsx("svg",{className:"member-strength-chart",viewBox:"0 0 320 120",role:"img","aria-label":"Recent result trend",children:e.jsx("polyline",{fill:"none",stroke:"currentColor",strokeWidth:"4",strokeLinecap:"round",strokeLinejoin:"round",points:W.map((O,L)=>{const Z=Math.min(...W),ce=Math.max(...W),me=10+L*(300/Math.max(1,W.length-1)),Ne=105-(O-Z)/Math.max(1,ce-Z)*90;return`${me},${Ne}`}).join(" ")})})]}):null,e.jsx(vt,{fill:"clear",onClick:()=>k(!x),children:x?"Hide advanced tools":"Advanced tools"}),x?e.jsxs("section",{className:"member-panel-card",children:[e.jsx("h2",{children:"Your movements"}),e.jsx("p",{children:"Add a lift only you can see."}),e.jsx(pt,{children:e.jsx(Vi,{label:"Movement name",labelPlacement:"stacked",maxlength:120,value:j,onIonInput:O=>I(O.detail.value||"")})}),e.jsx(vt,{fill:"outline",disabled:!j.trim(),onClick:()=>{ye()},children:"Add movement"})]}):null,x&&S.length?e.jsxs("section",{className:"member-panel-card",children:[e.jsx("h2",{children:"Benchmarks"}),e.jsx("div",{className:"member-panel-list",children:S.map(O=>e.jsx("div",{className:"member-panel-row",children:e.jsxs("div",{className:"member-row-main",children:[e.jsxs("div",{children:[e.jsx("strong",{children:O.title}),e.jsx("p",{children:O.movement_name})]}),e.jsx(vt,{fill:"clear",onClick:()=>{de(O)},children:"View"})]})},O.uuid))}),y?e.jsxs("div",{className:"member-panel-list",children:[e.jsx("h3",{children:y.title}),y.rows.map(O=>e.jsxs("div",{className:"member-row-main",children:[e.jsxs("strong",{children:[O.rank,". ",O.display_name]}),e.jsx("span",{children:O.score})]},`${O.rank}-${O.display_name}`))]}):null]}):null]}),e.jsx(at,{isOpen:p,onDidDismiss:()=>g(!1),className:"member-strength-modal",children:e.jsxs("div",{className:"member-ui member-modal-sheet member-strength-sheet member-strength-modal-sheet",children:[e.jsxs("div",{className:"member-modal-header member-strength-modal-header",children:[e.jsxs("div",{children:[e.jsx("h2",{children:"Log result"}),e.jsx("p",{children:"Keep it short."})]}),e.jsx(vt,{fill:"clear",onClick:()=>g(!1),children:"Close"})]}),e.jsxs("section",{className:"member-panel-card member-strength-form",children:[e.jsx(pt,{children:e.jsx($n,{label:"Movement",labelPlacement:"stacked",value:A.movement_uuid,onIonChange:O=>H(O.detail.value),children:l.map(O=>e.jsx(Fs,{value:O.uuid,children:O.name},O.uuid))})}),e.jsx(pt,{children:e.jsx($n,{label:"Result",labelPlacement:"stacked",value:A.result_type,onIonChange:O=>ne(O.detail.value),children:(w?.allowed_result_types?.length?w.allowed_result_types:["weight_for_reps"]).map(O=>e.jsx(Fs,{value:O,children:O==="weight_for_reps"?"Best weight for reps":"Max reps at weight"},O))})}),e.jsxs("div",{className:"member-strength-fields",children:[e.jsx(pt,{children:e.jsx(Vi,{label:"Weight",labelPlacement:"stacked",type:"number",value:A.weight,onIonInput:O=>D({...A,weight:Number(O.detail.value)})})}),e.jsx(pt,{children:e.jsxs($n,{label:"Unit",labelPlacement:"stacked",value:A.weight_unit,onIonChange:O=>D({...A,weight_unit:O.detail.value}),children:[e.jsx(Fs,{value:"kg",children:"kg"}),e.jsx(Fs,{value:"lb",children:"lb"})]})}),e.jsx(pt,{children:e.jsx(Vi,{label:"Reps",labelPlacement:"stacked",type:"number",value:A.reps,onIonInput:O=>D({...A,reps:Number(O.detail.value)})})})]}),e.jsx(pt,{children:e.jsx($n,{label:"Side",labelPlacement:"stacked",value:A.side,onIonChange:O=>D({...A,side:O.detail.value}),children:(w?.laterality==="unilateral"||w?.laterality==="either"?["left","right","both","alternating"]:["both","not_applicable"]).map(O=>e.jsx(Fs,{value:O,children:gt(O)},O))})}),e.jsx(vt,{fill:"clear",onClick:()=>N(!v),children:v?"Hide details":"More details"}),v?e.jsxs(e.Fragment,{children:[e.jsx(pt,{children:e.jsxs($n,{label:"Feel",labelPlacement:"stacked",value:A.quality,onIonChange:O=>D({...A,quality:O.detail.value}),children:[e.jsx(Fs,{value:"",children:"Not recorded"}),["crisp","good","hard_but_clean","grind","pain_or_issue"].map(O=>e.jsx(Fs,{value:O,children:gt(O)},O))]})}),e.jsx(pt,{children:e.jsx(wd,{label:"Short note",labelPlacement:"stacked",maxlength:500,value:A.note,onIonInput:O=>D({...A,note:O.detail.value||""})})})]}):null,e.jsx(vt,{expand:"block",disabled:!A.movement_uuid||A.reps<1||A.weight<0,onClick:()=>{K()},children:"Save result"})]})]})}),e.jsx(Dt,{isOpen:!!U,message:U,duration:2300,onDidDismiss:()=>F("")})]}):e.jsx(Ye,{standardUI:!0,title:"Strength",subtitle:"Strength tracking is not enabled.",activeTab:"none",backTo:"/training",children:e.jsx("section",{className:"member-panel-card",children:e.jsx("p",{children:"This module is not available."})})})}function Cx(){const t=tt(),[s,n]=r.useState([]),[a,i]=r.useState(!0),[o,l]=r.useState(""),c=r.useCallback(async u=>
2{i(!0);const d=new Date,h=new Date(d);h.setDate(h.getDate()+14);try{n(await T.training.listWorkouts(d.toISOString().slice(0,10),h.toISOString().slice(0,10),u))}catch(m){l(re(m,"Unable to load class workouts."))}finally{i(!1)}},[]);return r.useEffect(()=>{const u=new AbortController;return c(u.signal),()=>u.abort()},[c]),e.jsxs(Ye,{title:"Class workouts",subtitle:"Published plans for the next two weeks.",activeTab:"none",backTo:"/training",onRefresh:c,children:[a?e.jsxs("div",{className:"member-panel-loading",children:[e.jsx(Te,{}),e.jsx("span",{children:"Loading workouts..."})]}):null,!a&&!s.length?e.jsx("section",{className:"member-panel-card",children:e.jsx("p",{children:"No published workouts are available."})}):s.map(u=>e.jsxs("section",{className:"member-panel-card",children:[e.jsx("h2",{children:u.title}),e.jsx("p",{children:u.planned_date}),e.jsx("div",{className:"member-panel-list",children:u.sections.map(d=>e.jsxs("article",{className:"member-workout-section",children:[e.jsxs("div",{className:"member-row-main",children:[e.jsx("strong",{children:d.title}),d.planned_minutes?e.jsxs("span",{children:[d.planned_minutes," min"]}):null]}),d.member_instructions?e.jsx("p",{children:d.member_instructions}):null,d.structure?.exercises&&Array.isArray(d.structure.exercises)?e.jsx("ul",{children:d.structure.exercises.map((h,m)=>e.jsxs("li",{children:[String(h.movement||h.name||"Exercise"),h.reps?` x ${h.reps}`:"",h.load?` · ${h.load}`:""]},m))}):null,d.logging_prompt&&d.linked_movement_uuid?e.jsx(vt,{fill:"outline",size:"small",onClick:()=>t.push(`/strength?movement=${d.linked_movement_uuid}&block=${d.uuid}`),children:"Log result"}):null]},d.uuid))})]},u.uuid)),e.jsx(Dt,{isOpen:!!o,message:o,duration:2300,onDidDismiss:()=>l("")})]})}var Na;(function(t){t.Unimplemented="UNIMPLEMENTED",t.Unavailable="UNAVAILABLE"})(Na||(Na={}));class zi extends Error{constructor(s,n,a){super(s),this.message=s,this.code=n,this.data=a}}const Sx=t=>{var s,n;return t?.androidBridge?"android":!((n=(s=t?.webkit)===null||s===void 0?void 0:s.messageHandlers)===null||n===void 0)&&n.bridge?"ios":"web"},Px=t=>{const s=t.CapacitorCustomPlatform||null,n=t.Capacitor||{},a=n.Plugins=n.Plugins||{},i=()=>s!==null?s.name:Sx(t),o=()=>i()!=="web",l=m=>{const f=d.get(m);return!!(f?.platforms.has(i())||c(m))},c=m=>{var f;return(f=n.PluginHeaders)===null||f===void 0?void 0:f.find(b=>b.name===m)},u=m=>t.console.error(m),d=new Map,h=(m,f={})=>{const b=d.get(m);if(b)return console.warn(`Capacitor plugin "${m}" already registered. Cannot register plugins twice.`),b.proxy;const p=i(),g=c(m);let v;const N=async()=>(!v&&p in f?v=typeof f[p]=="function"?v=await f[p]():v=f[p]:s!==null&&!v&&"web"in f&&(v=typeof f.web=="function"?v=await f.web():v=f.web),v),x=(y,P)=>{var U,F;if(g){const A=g?.methods.find(D=>P===D.name);if(A)return A.rtype==="promise"?D=>n.nativePromise(m,P.toString(),D):(D,R)=>n.nativeCallback(m,P.toString(),D,R);if(y)return(U=y[P])===null||U===void 0?void 0:U.bind(y)}else{if(y)return(F=y[P])===null||F===void 0?void 0:F.bind(y);throw new zi(`"${m}" plugin is not implemented on ${p}`,Na.Unimplemented)}},k=y=>{let P;const U=(...F)=>{const A=N().then(D=>{const R=x(D,y);if(R){const w=R(...F);return P=w?.remove,w}else throw new zi(`"${m}.${y}()" is not implemented on ${p}`,Na.Unimplemented)});return y==="addListener"&&(A.remove=async()=>P()),A};return U.toString=()=>`${y.toString()}() { [capacitor code] }`,Object.defineProperty(U,"name",{value:y,writable:!1,configurable:!1}),U},j=k("addListener"),I=k("removeListener"),S=(y,P)=>{const U=j({eventName:y},P),F=async()=>{const D=await U;I({eventName:y,callbackId:D},P)},A=new Promise(D=>U.then(()=>D({remove:F})));return A.remove=async()=>{console.warn("Using addListener() without 'await' is deprecated."),await F()},A},M=new Proxy({},{get(y,P){switch(P){case"$$typeof":return;case"toJSON":return()=>({});case"addListener":return g?S:j;case"removeListener":return I;default:return k(P)}}});return a[m]=M,d.set(m,{name:m,proxy:M,platforms:new Set([...Object.keys(f),...g?[p]:[]])}),M};return n.convertFileSrc||(n.convertFileSrc=m=>m),n.getPlatform=i,n.handleError=u,n.isNativePlatform=o,n.isPluginAvailable=l,n.registerPlugin=h,n.Exception=zi,n.DEBUG=!!n.DEBUG,n.isLoggingEnabled=!!n.isLoggingEnabled,n},Rx=t=>t.Capacitor=Px(t),Yr=Rx(typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{}),di=Yr.registerPlugin;class Eo{constructor(){this.listeners={},this.retainedEventArguments={},this.windowListeners={}}addListener(s,n){let a=!1;this.listeners[s]||(this.listeners[s]=[],a=!0),this.listeners[s].push(n);const o=this.windowListeners[s];o&&!o.registered&&this.addWindowListener(o),a&&this.sendRetainedArgumentsForEvent(s);const l=async()=>this.removeListener(s,n);return Promise.resolve({remove:l})}async removeAllListeners(){this.listeners={};for(const s in this.windowListeners)this.removeWindowListener(this.windowListeners[s]);this.windowListeners={}}notifyListeners(s,n,a){const i=this.listeners[s];if(!i){if(a){let o=this.retainedEventArguments[s];o||(o=[]),o.push(n),this.retainedEventArguments[s]=o}return}i.forEach(o=>o(n))}hasListeners(s){var n;return!!(!((n=this.listeners[s])===null||n===void 0)&&n.length)}registerWindowListener(s,n){this.windowListeners[n]={registered:!1,windowEventName:s,pluginEventName:n,handler:a=>{this.notifyListeners(n,a)}}}unimplemented(s="not implemented"){return new Yr.Exception(s,Na.Unimplemented)}unavailable(s="not available"){return new Yr.Exception(s,Na.Unavailable)}async removeListener(s,n){const a=this.listeners[s];if(!a)return;const i=a.indexOf(n);this.listeners[s].splice(i,1),this.listeners[s].length||this.removeWindowListener(this.windowListeners[s])}addWindowListener(s){window.addEventListener(s.windowEventName,s.handler),s.registered=!0}removeWindowListener(s){s&&(window.removeEventListener(s.windowEventName,s.handler),s.registered=!1)}sendRetainedArgumentsForEvent(s){const n=this.retainedEventArguments[s];
2n&&(delete this.retainedEventArguments[s],n.forEach(a=>{this.notifyListeners(s,a)}))}}const Ol=t=>encodeURIComponent(t).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape),Bl=t=>t.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent);class Tx extends Eo{async getCookies(){const s=document.cookie,n={};return s.split(";").forEach(a=>{if(a.length<=0)return;let[i,o]=a.replace(/=/,"CAP_COOKIE").split("CAP_COOKIE");i=Bl(i).trim(),o=Bl(o).trim(),n[i]=o}),n}async setCookie(s){try{const n=Ol(s.key),a=Ol(s.value),i=s.expires?`; expires=${s.expires.replace("expires=","")}`:"",o=(s.path||"/").replace("path=",""),l=s.url!=null&&s.url.length>0?`domain=${s.url}`:"";document.cookie=`${n}=${a||""}${i}; path=${o}; ${l};`}catch(n){return Promise.reject(n)}}async deleteCookie(s){try{document.cookie=`${s.key}=; Max-Age=0`}catch(n){return Promise.reject(n)}}async clearCookies(){try{const s=document.cookie.split(";")||[];for(const n of s)document.cookie=n.replace(/^ +/,"").replace(/=.*/,`=;expires=${new Date().toUTCString()};path=/`)}catch(s){return Promise.reject(s)}}async clearAllCookies(){try{await this.clearCookies()}catch(s){return Promise.reject(s)}}}di("CapacitorCookies",{web:()=>new Tx});const _x=async t=>new Promise((s,n)=>{const a=new FileReader;a.onload=()=>{const i=a.result;s(i.indexOf(",")>=0?i.split(",")[1]:i)},a.onerror=i=>n(i),a.readAsDataURL(t)}),Mx=(t={})=>{const s=Object.keys(t);return Object.keys(t).map(i=>i.toLocaleLowerCase()).reduce((i,o,l)=>(i[o]=t[s[l]],i),{})},Ux=(t,s=!0)=>t?Object.entries(t).reduce((a,i)=>{const[o,l]=i;let c,u;return Array.isArray(l)?(u="",l.forEach(d=>{c=s?encodeURIComponent(d):d,u+=`${o}=${c}&`}),u.slice(0,-1)):(c=s?encodeURIComponent(l):l,u=`${o}=${c}`),`${a}&${u}`},"").substr(1):null,Ex=(t,s={})=>{const n=Object.assign({method:t.method||"GET",headers:t.headers},s),i=Mx(t.headers)["content-type"]||"";if(typeof t.data=="string")n.body=t.data;else if(i.includes("application/x-www-form-urlencoded")){const o=new URLSearchParams;for(const[l,c]of Object.entries(t.data||{}))o.set(l,c);n.body=o.toString()}else if(i.includes("multipart/form-data")||t.data instanceof FormData){const o=new FormData;if(t.data instanceof FormData)t.data.forEach((c,u)=>{o.append(u,c)});else for(const c of Object.keys(t.data))o.append(c,t.data[c]);n.body=o;const l=new Headers(n.headers);l.delete("content-type"),n.headers=l}else(i.includes("application/json")||typeof t.data=="object")&&(n.body=JSON.stringify(t.data));return n};class Ax extends Eo{async request(s){const n=Ex(s,s.webFetchExtra),a=Ux(s.params,s.shouldEncodeUrlParams),i=a?`${s.url}?${a}`:s.url,o=await fetch(i,n),l=o.headers.get("content-type")||"";let{responseType:c="text"}=o.ok?s:{};l.includes("application/json")&&(c="json");let u,d;switch(c){case"arraybuffer":case"blob":d=await o.blob(),u=await _x(d);break;case"json":u=await o.json();break;default:u=await o.text()}const h={};return o.headers.forEach((m,f)=>{h[f]=m}),{data:u,headers:h,status:o.status,url:o.url}}async get(s){return this.request(Object.assign(Object.assign({},s),{method:"GET"}))}async post(s){return this.request(Object.assign(Object.assign({},s),{method:"POST"}))}async put(s){return this.request(Object.assign(Object.assign({},s),{method:"PUT"}))}async patch(s){return this.request(Object.assign(Object.assign({},s),{method:"PATCH"}))}async delete(s){return this.request(Object.assign(Object.assign({},s),{method:"DELETE"}))}}di("CapacitorHttp",{web:()=>new Ax});var Fl;(function(t){t.Dark="DARK",t.Light="LIGHT",t.Default="DEFAULT"})(Fl||(Fl={}));var Wl;(function(t){t.StatusBar="StatusBar",t.NavigationBar="NavigationBar"})(Wl||(Wl={}));class Dx extends Eo{async setStyle(){this.unavailable("not available for web")}async setAnimation(){this.unavailable("not available for web")}async show(){this.unavailable("not available for web")}async hide(){this.unavailable("not available for web")}}di("SystemBars",{web:()=>new Dx});const Lx=di("SplashScreen",{web:()=>ir(()=>import("./web-C8Nc9ZnS.js"),__vite__mapDeps([5,1,2,3,4,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47])).then(t=>new t.SplashScreenWeb)});async function Ix(){if(Yr.isNativePlatform())try{await Lx.hide({fadeOutDuration:180})}catch{}}const ql=28;function $x(t,s,n){return n!==1||!Number.isFinite(t)||!Number.isFinite(s)||s<=0?!1:t<=ql||t>=s-ql}function Ox(t,s=()=>t.defaultView?.innerWidth??0){const n=a=>{const i=a.touches.item(0);
2a.cancelable&&i&&$x(i.clientX,s(),a.touches.length)&&a.preventDefault()};return t.addEventListener("touchstart",n,{capture:!0,passive:!1}),()=>{t.removeEventListener("touchstart",n,!0)}}function Hl(t){return Array.from(t.querySelectorAll("ion-router-outlet .ion-page")).some(s=>{for(let n=s;n;n=n.parentElement){if(n.hidden||n.getAttribute("aria-hidden")==="true"||n.classList.contains("ion-page-hidden")||n.classList.contains("ion-page-invisible"))return!1;const a=t.defaultView?.getComputedStyle(n);if(a?.display==="none"||a?.visibility==="hidden"||a?.visibility==="collapse")return!1}return!0})}function Bx(t,s,n){let a,i=!1;const o=()=>{clearTimeout(a),!(i||t.visibilityState!=="visible")&&(a=setTimeout(()=>{Hl(t)||(a=setTimeout(()=>{!i&&t.visibilityState==="visible"&&!Hl(t)&&s()},1e3))},n))};return t.addEventListener("visibilitychange",o),o(),()=>{i=!0,clearTimeout(a),t.removeEventListener("visibilitychange",o)}}function Fx(){if(typeof window>"u")return!1;const t=window.navigator;return window.matchMedia?.("(display-mode: standalone)").matches===!0||t.standalone===!0}function Wx(t){const s=t&&typeof t=="object"?t:{},n=s.data&&typeof s.data=="object"?s.data:s,a=typeof n.canonical_origin=="string"?n.canonical_origin.trim().replace(/\/+$/,""):"",i=n.redirect_mode;return!a||!["none","browser_redirect_pwa_grace","migration_required"].includes(String(i))?null:{requestedHost:String(n.requested_host??""),primaryHost:String(n.primary_host??""),canonicalOrigin:a,redirectMode:i,pwaGraceUntil:typeof n.pwa_grace_until=="string"?n.pwa_grace_until:null}}function Vl(t){return`${t.canonicalOrigin}${window.location.pathname}${window.location.search}${window.location.hash}`}function qx(){const[t,s]=r.useState(null);if(r.useEffect(()=>{let a=!0;return fetch("/api/v1/tenant/context",{credentials:"same-origin",cache:"no-store"}).then(i=>i.ok?i.json():null).then(i=>{if(!a)return;const o=Wx(i);if(Mb(o?.canonicalOrigin),!(!o||o.redirectMode==="none")){if(!Fx()){window.location.replace(Vl(o));return}s(o)}}).catch(()=>{}),()=>{a=!1}},[]),!t)return null;const n=t.redirectMode==="migration_required";return e.jsxs("aside",{className:`member-domain-migration${n?" is-required":""}`,role:"status","aria-live":"polite",children:[e.jsxs("div",{children:[e.jsx("strong",{children:n?"This installed app has moved":"Install the app again"}),e.jsxs("p",{children:["Open ",t.primaryHost," in your browser, log in, then install the member app again. Your login and notifications cannot move automatically."]})]}),e.jsx("button",{type:"button",onClick:()=>Ks(Vl(t)),children:"Open new address"})]})}const Hx=new Set(["/login","/forgot-password","/recover-account","/reset-password","/join","/mobile-login"]);function Sa(t){const s=go(t);return Hd(t)||Hx.has(s)||s.startsWith("/onboarding/")||s==="/book-a-trial"||s.startsWith("/trial-intake/")||s.startsWith("/event/")||s.startsWith("/workshops/")||s.startsWith("/fundraisers/")||s.startsWith("/links/")||s.startsWith("/go/")||s.startsWith("/workshop-forms/")||s.startsWith("/event-change/")||s==="/workouts/display"||s.startsWith("/workouts/display/")}function mi(t){const s=go(t);return!!Or({path:"/lesson-plans/:lessonPlanUuid/document",end:!0},s)}function Vx(){const{appearance:t,themeMode:s}=ln(),n=t.loginLogoLightUrl||t.headerLogoLightUrl,a=t.loginLogoDarkUrl||t.headerLogoDarkUrl,i=t.splashImageUrl||(s==="dark"?a||n||Ki:n||a||Ki),o=t.splashImage||(s==="dark"?t.loginLogoDarkImage||t.loginLogoLightImage:t.loginLogoLightImage||t.loginLogoDarkImage);return e.jsx(Cn,{className:"member-auth-bootstrap-page",style:{"--member-splash-background":t.splashBackgroundColorHex,"--member-splash-accent":t.themeColorHex},children:e.jsx(wn,{className:"member-auth-bootstrap-content",fullscreen:!0,forceOverscroll:!1,children:e.jsxs("div",{className:"member-auth-bootstrap-shell",children:[e.jsx("div",{className:"member-auth-bootstrap-logo-wrap",children:e.jsx(ys,{image:o,fallbackUrl:i,sizes:"240px",className:"member-auth-bootstrap-logo",alt:"Tenant logo",eager:!0})}),e.jsx(Te,{className:"member-auth-bootstrap-spinner",name:"crescent"})]})})})}function zx({delayed:t=!1}){return e.jsx(Cn,{className:"member-session-restore-page",children:e.jsx(wn,{className:"member-session-restore-content",fullscreen:!0,forceOverscroll:!1,children:e.jsxs("div",{className:"member-session-restore-shell",role:"status","aria-live":"polite",children:[e.jsx(Te,{className:"member-session-restore-spinner",name:"crescent"}),e.jsxs("div",{className:"member-session-restore-copy",children:[e.jsx("strong",{children:t?"The app is taking too long":"Restoring your session"}
2),e.jsx("p",{children:t?"Reload the app or open this page in your phone browser.":"Opening your member app."}),t?e.jsxs("div",{className:"member-session-restore-actions",children:[e.jsx("button",{type:"button",onClick:()=>{nc("error_recovery"),window.location.reload()},children:"Reload app"}),e.jsx("a",{href:window.location.href,target:"_blank",rel:"noopener noreferrer",children:"Open in browser"})]}):null]})]})})})}function hr(){const{resumeState:t}=Ge(),[s,n]=r.useState(!1);return r.useEffect(()=>{const a=window.setTimeout(()=>n(!0),12e3);return()=>window.clearTimeout(a)},[]),t==="cold-boot"?e.jsx(Vx,{}):e.jsx(zx,{delayed:s})}function Gx(){const t=mt(),{appearance:s,loading:n}=ln();return r.useEffect(()=>{const a=t.pathname||"/",i=Sa(a);Bd(i&&n?null:s,i?"public":"member")},[s,n,t.pathname]),null}function Kx(){const t=mt();return Sa(t.pathname)?e.jsxs(e.Fragment,{children:[e.jsx(sd,{}),e.jsx(nd,{})]}):null}function Yx(){const t=mt(),{isAuthenticated:s,isReady:n}=Ge(),[a,i]=r.useState(!1),[o,l]=r.useState(!1);r.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const f=window.matchMedia("(min-width: 1024px) and (pointer: fine)"),b=window.matchMedia("(display-mode: standalone)"),p=window.navigator,g=()=>{i(f.matches),l(b.matches||p.standalone===!0)};return g(),typeof f.addEventListener=="function"&&typeof b.addEventListener=="function"?(f.addEventListener("change",g),b.addEventListener("change",g),()=>{f.removeEventListener("change",g),b.removeEventListener("change",g)}):(f.addListener(g),b.addListener(g),()=>{f.removeListener(g),b.removeListener(g)})},[]);const c=t.pathname||"/",u=n&&s&&!Sa(c)&&!mi(c)&&a&&!o,d=r.useMemo(()=>u?Am(`${t.pathname}${t.search}${t.hash}`):"",[u,t.hash,t.pathname,t.search]),h=r.useMemo(()=>{if(!d)return"";try{return new URL(d).host}catch{return""}},[d]),m=r.useMemo(()=>d?ya(d,176):"",[d]);return{enabled:u,shareHost:h,shareUrl:d,qrCodePreviewSrc:m}}function Qx({children:t}){const{appearance:s,tenantName:n,themeMode:a}=ln(),{enabled:i,shareHost:o,shareUrl:l,qrCodePreviewSrc:c}=Yx(),u=a==="dark"?s.mobileIconUrl||s.headerLogoDarkUrl||s.headerLogoLightUrl||"":s.mobileIconUrl||s.headerLogoLightUrl||s.headerLogoDarkUrl||"",d=a==="dark"?s.mobileIconImage||s.headerLogoDarkImage||s.headerLogoLightImage:s.mobileIconImage||s.headerLogoLightImage||s.headerLogoDarkImage,h=n?.trim()||"Member app";return r.useEffect(()=>{if(typeof document>"u")return;const m=document.body,f=document.documentElement;return m.classList.toggle("member-desktop-shell-active",i),f.setAttribute("data-member-shell",i?"desktop-private":"default"),()=>{m.classList.remove("member-desktop-shell-active"),f.setAttribute("data-member-shell","default")}},[i]),i?e.jsxs("div",{className:"member-desktop-shell-stage",children:[e.jsx("div",{className:"member-desktop-shell-atmosphere","aria-hidden":"true"}),e.jsxs("div",{className:"member-desktop-shell-layout",children:[e.jsx("div",{className:"member-desktop-phone-frame",children:e.jsxs("div",{className:"member-desktop-phone-chassis",children:[e.jsx("span",{className:"member-desktop-phone-speaker","aria-hidden":"true"}),e.jsx("div",{className:"member-desktop-phone-screen",children:e.jsx("div",{className:"member-desktop-phone-screen-host",children:t})})]})}),e.jsxs("aside",{className:"member-desktop-shell-callout","aria-label":"Open this member app page on your phone",children:[e.jsxs("div",{className:"member-desktop-shell-callout-head",children:[u?e.jsx(ys,{className:"member-desktop-shell-callout-icon",image:d,fallbackUrl:u,sizes:"64px",alt:"","aria-hidden":"true"}):null,e.jsxs("div",{className:"member-desktop-shell-callout-copy",children:[e.jsx("span",{className:"member-desktop-shell-callout-eyebrow",children:"Member mobile app"}),e.jsx("strong",{children:h})]})]}),e.jsx("p",{className:"member-desktop-shell-callout-message",children:"This is the member mobile app. For the best performance, scan to open this exact page on your phone."}),e.jsx("div",{className:"member-desktop-shell-callout-qr-card",children:c?e.jsx("img",{className:"member-desktop-shell-callout-qr",src:c,alt:"QR code to open this member app page on your phone"}):e.jsx("div",{className:"member-desktop-shell-callout-qr-fallback",children:"QR unavailable right now."})}),e.jsxs("div",{className:"member-desktop-shell-callout-footer",children:[e.jsx("span",{children:o||"Open on your phone"}),l?e.jsx("a",{href:l,target:"_blank",rel:"noreferrer",children:"Open current link"}):null]})]})]})]}):e.jsx(e.Fragment,{children:t})}function Zx({user:t,resumePath:s}){const[n,a]=r.useState(null),i=r.useRef(null);return r.useEffect(()=>{let o=!0;return!i.current||i.current.userId!==t.id?i.current={userId:t.id,path:T.auth.consumePostLoginRedirect()||s}:!i.current.path&&s&&(i.current.path=s),a(null),rf(t,i.current.path).then(l=>{o&&a(l)}),()=>{o=!1}},[s,t]),n?e.jsx(ms,{to:n,replace:!0}):e.jsx(hr,{})}function Jx(){const{isReady:t,isAuthenticated:s,resumePath:n,user:a}=Ge(),i=mt();return Wd(i.pathname)?t?Pu(i.search,window.location.origin)?e.jsx(vl,{}):s&&a?e.jsx(Zx,{user:a,resumePath:n}):e.jsx(vl,{}):e.jsx(hr,{}):null}function Xx(){const{isAuthenticated:t,isReady:s,resumePath:n,user:a}=Ge(),i=mt();return qd(i.pathname)?s?!t||!a?e.jsx(ms,{to:"/timetable",replace:!0}):e.jsx(ms,{to:Mo(a,T.auth.getPostLoginRedirect()||n),replace:!0}):e.jsx(hr,{}):null}function Ee({children:t}){const{isReady:s,isAuthenticated:n,user:a,logout:i}=Ge(),o=mt();if(r.useEffect(()=>{!s||!n||a?.accessPolicy?.canLogin===!1&&i()},[n,s,i,a?.accessPolicy?.canLogin]),!s)return e.jsx(hr,{});if(!n)return T.auth.rememberPostLoginRedirect(`${o.pathname}${o.search}${o.hash}`),e.jsx(ms,{to:"/login",replace:!0});if(a?.accessPolicy?.canLogin===!1)return e.jsx(ms,{to:"/login",replace:!0});if(a?.accessPolicy?.memberExperienceMode==="booking_beta"){const l=`${o.pathname}${o.search}${o.hash}`,c=Mo(a,l);if(c!==l)return e.jsx(ms,{to:c,replace:!0})}return e.jsx(e.Fragment,{children:t})}function Zt(t){return Oc(t)&&Qe(t)?"/staff-tools":"/account"}function zl(){const{user:t}=Ge();return e.jsx(ms,{to:an(t),replace:!0})}function nt({children:t,isAllowed:s,redirectTo:n}){const{user:a}=Ge();return a?s(a)?e.jsx(e.Fragment,{children:t}):e.jsx(ms,{to:typeof n=="function"?n(a):n,replace:!0}):e.jsx(ms,{to:"/login",replace:!0})}function Gl({children:t}){const{isAuthenticated:s,isReady:n,refreshSession:a,user:i}=Ge(),[o,l]=r.useState(!0);return r.useEffect(()=>{let c=!0;return a().catch(()=>{}).finally(()=>{c&&l(!1)}),()=>{c=!1}},[a]),!n||o?e.jsx(hr,{}):s?e.jsx(ms,{to:"/timetable",replace:!0}):e.jsx(ms,{to:"/login",replace:!0})}function ej(){const t=mt(),{isAuthenticated:s}=Ge();return!s||mi(t.pathname)?null:e.jsx(Mh,{contentId:Vc})}function tj(){const t=mt(),s=tt(),{isAuthenticated:n,isReady:a,rememberResumePath:i,user:o}=Ge(),l=r.useRef(null);return r.useEffect(()=>{const c=()=>
2{if(document.hidden){l.current=Date.now();return}const u=l.current;l.current=null,!(!u||Date.now()-u<18e4||!a||!n||!o)&&s.navigateRoot("/timetable")};return document.addEventListener("visibilitychange",c),()=>document.removeEventListener("visibilitychange",c)},[s,n,a,o]),r.useEffect(()=>{if(!a||!n||!o||Sa(t.pathname))return;const c=`${t.pathname}${t.search}${t.hash}`;!c.startsWith("/")||c==="/"||i(c)},[n,a,t.hash,t.pathname,t.search,i,o]),null}function sj(){const t=mt(),{isAuthenticated:s,isReady:n,user:a}=Ge(),i=n&&s&&!Sa(t.pathname)&&!mi(t.pathname),o=`${a?.tenantUuid||""}:${a?.id||""}`;return e.jsx(Yh,{enabled:i,identityKey:o},o)}function nj(){const t=mt(),{isAuthenticated:s,isReady:n}=Ge(),a=n&&s&&!Sa(t.pathname)&&!mi(t.pathname);return r.useEffect(()=>{if(!(!a||typeof document>"u"))return Ox(document)},[a]),null}function aj(){const t=mt(),{isAuthenticated:s,isReady:n}=Ge();return r.useEffect(()=>{if(n)return Fd("route_render"),Bx(document,()=>Vd("route_blank","route_render"),s?1500:2500)},[s,n,t.pathname,t.search]),null}function rj(){r.useEffect(()=>{Kd()},[]);const t=r.useMemo(()=>$d(),[]);return r.useEffect(()=>{const s=Od();return Ix(),()=>{s()}},[]),e.jsx(Cd,{className:"member-app-root",children:e.jsxs(ed,{children:[e.jsx(qx,{}),e.jsx(td,{}),e.jsx(Wh,{}),e.jsxs(Gd,{children:[e.jsx(Uh,{}),e.jsxs(yh,{basename:t||void 0,children:[e.jsx(Gx,{}),e.jsx(tj,{}),e.jsx(nj,{}),e.jsx(aj,{}),e.jsx(Qh,{}),e.jsx(sj,{}),e.jsx(Rh,{children:e.jsx(Ch,{children:e.jsxs(Qx,{children:[e.jsx(ej,{}),e.jsxs(Sd,{id:Vc,swipeGesture:!1,children:[e.jsx(he,{path:"/login",element:e.jsx(Jx,{})}),e.jsx(he,{path:"/forgot-password",element:e.jsx(Up,{})}),e.jsx(he,{path:"/recover-account",element:e.jsx(pg,{})}),e.jsx(he,{path:"/reset-password",element:e.jsx(jg,{})}),e.jsx(he,{path:"/mobile-login",element:e.jsx(of,{})}),e.jsx(he,{path:"/workouts/display/:date?",element:e.jsx(Vm,{})}),e.jsx(he,{path:"/event/:slug",element:e.jsx(zo,{})}),e.jsx(he,{path:"/workshops/:slug",element:e.jsx(zo,{})}),e.jsx(he,{path:"/fundraisers/:slug",element:e.jsx(Bm,{})}),e.jsx(he,{path:"/links/:slug",element:e.jsx(gm,{})}),e.jsx(he,{path:"/go/:slug",element:e.jsx(zm,{})}),e.jsx(he,{path:"/workshop-forms/:token",element:e.jsx(Qm,{})}),e.jsx(he,{path:"/event-change/:token",element:e.jsx(Gm,{})}),e.jsx(he,{path:"/book-a-trial",element:e.jsx(Lm,{})}),e.jsx(he,{path:"/trial-intake/:slug",element:e.jsx(Ym,{})}),e.jsx(he,{path:"/onboarding/trial/status",element:e.jsx(Km,{})}),e.jsx(he,{path:"/onboarding/trial/offer/:offerUuid",element:e.jsx(Go,{})}),e.jsx(he,{path:"/onboarding/trial",element:e.jsx(Go,{})}),e.jsx(he,{path:"/onboarding/conversion",element:e.jsx(Im,{})}),e.jsx(he,{path:"/onboarding/conversion/status",element:e.jsx($m,{})}),e.jsx(he,{path:"/onboarding/membership/status",element:e.jsx(Sm,{})}),e.jsx(he,{path:"/onboarding/membership",element:e.jsx(Tm,{})}),e.jsx(he,{path:"/join",element:e.jsx(Hm,{})}),e.jsx(he,{path:"/onboarding/membership/plan/:planUuid",element:e.jsx(Pm,{})}),e.jsx(he,{path:"/timetable",element:e.jsx(Ee,{children:e.jsx(vx,{})})}),e.jsx(he,{path:"/events/workshops",element:e.jsx(Ee,{children:e.jsx(Ii,{kind:"events"})})}),e.jsx(he,{path:"/shop/basket",element:t?e.jsx(Ee,{children:e.jsx(In,{basePath:$a})}):e.jsx(ki,{})}),e.jsx(he,{path:"/shop/product/:uuid",element:t?e.jsx(Ee,{children:e.jsx(In,{basePath:$a})}):e.jsx(ki,{})}),e.jsx(he,{path:"/shop/order/:uuid",element:t?e.jsx(Ee,{children:e.jsx(In,{basePath:$a})}):e.jsx(Rd,{})}),e.jsx(he,{path:"/shop",element:t?e.jsx(Ee,{children:e.jsx(In,{basePath:$a})}):e.jsx(ki,{})}),e.jsx(he,{path:`${sr}/*`,element:e.jsx(Ee,{children:e.jsx(In,{})})}),e.jsx(he,{path:"/shop/*",element:e.jsx(Ee,{children:e.jsx(In,{basePath:$a})})}),e.jsx(he,{path:"/staff-tools/shop/*",element:e.jsx(Ee,{children:e.jsx(In,{staff:!0})})}),e.jsx(he,{path:"/events",element:e.jsx(Ee,{children:e.jsx(Ii,{kind:"events"})})}),e.jsx(he,{path:"/events/fundraisers",element:e.jsx(Ee,{children:e.jsx(Ii,{kind:"fundraisers"})})}),e.jsx(he,{path:"/events/details/:slug",element:e.jsx(Ee,{children:e.jsx(Lf,{})})}),e.jsx(he,{path:"/events/fundraisers/:slug",element:e.jsx(Ee,{children:e.jsx(If,{})})}),e.jsx(he,{path:"/dashboard",element:e.jsx(Ee,{children:e.jsx(ms,{to:"/timetable",replace:!0})})}),e.jsx(he,{path:"/community-groups",element:e.jsx(Ee,{children:e.jsx(Mp,{})})}),e.jsx(he,{path:"/account",element:e.jsx(Ee,{children:e.jsx(ap,{})})}),e.jsx(he,{path:"/training",element:e.jsx(Ee,{children:e.jsx(nt,{isAllowed:Xt,redirectTo:Zt,children:e.jsx(Nx,{})})})}),e.jsx(he,{path:"/strength",element:e.jsx(Ee,{children:e.jsx(nt,{isAllowed:s=>Xt(s)&&s.featureFlags?.strengthTrackingEnabled===!0,redirectTo:Zt,children:e.jsx(wx,{})})})}),e.jsx(he,{path:"/workouts",element:e.jsx(Ee,{children:e.jsx(nt,{isAllowed:s=>Xt(s)&&s.featureFlags?.workoutPlannerEnabled===!0,redirectTo:Zt,children:e.jsx(Cx,{})})})}),e.jsx(he,{path:"/staff-tools",element:e.jsx(Ee,{children:e.jsx(nt,{isAllowed:Qe,redirectTo:"/account",children:e.jsx(Ag,{})})})}),e.jsx(he,{path:"/staff-tools/prompts",element:e.jsx(Ee,{children:e.jsx(nt,{isAllowed:Qe,redirectTo:"/account",children:e.jsx(Dg,{})})})}),e.jsx(he,{path:"/staff-tools/lesson-plans/:familyUuid?",element:e.jsx(Ee,{children:e.jsx(nt,{isAllowed:Gs,redirectTo:"/staff-tools",children:e.jsx(wg,{})})})}),e.jsx(he,{path:"/lesson-plans/:lessonPlanUuid/document",element:e.jsx(Ee,{children:e.jsx(nt,{isAllowed:Gs,redirectTo:"/staff-tools",children:e.jsx(Rg,{})})})}),e.jsx(he,{path:"/staff-tools/availability",element:e.jsx(Ee,{children:e.jsx(nt,{isAllowed:Qe,redirectTo:"/account",children:e.jsx(Tb,{})})})}),e.jsx(he,{path:"/staff-tools/rota",element:e.jsx(Ee,{children:e.jsx(nt,{isAllowed:Qe,redirectTo:"/account",children:e.jsx(qb,{})})})}),e.jsx(he,{path:"/staff-tools/log-cash",element:e.jsx(Ee,{children:e.jsx(nt,{isAllowed:Qe,redirectTo:"/account",children:e.jsx(Mg,{})})})}),e.jsx(he,{path:"/staff-tools/sales-links",element:e.jsx(Ee,{children:e.jsx(nt,{isAllowed:Qe,redirectTo:"/account",children:e.jsx(Dl,{})})})}),e.jsx(he,{path:"/staff-tools/share-tools",element:e.jsx(Ee,{children:e.jsx(nt,{isAllowed:Qe,redirectTo:"/account",children:e.jsx(Dl,{})})})}),e.jsx(he,{path:"/people",element:e.jsx(Ee,{children:e.jsx(nt,{isAllowed:oi,redirectTo:"/staff-tools",children:e.jsx(Xf,{})})})}),e.jsx(he,{path:"/people/members",element:e.jsx(Ee,{children:e.jsx(nt,{isAllowed:Kn,redirectTo:"/people",children:e.jsx(sg,{})})})}),e.jsx(he,{path:"/people/members/:uuid",element:e.jsx(Ee,{children:e.jsx(nt,{isAllowed:s=>Kn(s)||Qe(s),redirectTo:"/timetable",children:e.jsx(tg,{})})})}),e.jsx(he,{path:"/people/prospects",element:e.jsx(Ee,{children:e.jsx(nt,{isAllowed:Yn,redirectTo:"/people",children:e.jsx(ag,{})})})}),e.jsx(he,{path:"/people/prospects/:uuid",element:e.jsx(Ee,{children:e.jsx(nt,{isAllowed:Yn,redirectTo:"/people",children:e.jsx(ng,{})})})}),e.jsx(he,{path:"/leads",element:e.jsx(Ee,{children:e.jsx(nt,{isAllowed:Qn,redirectTo:"/staff-tools",children:e.jsx(rg,{})})})}),e.jsx(he,{path:"/leads/:uuid",element:e.jsx(Ee,{children:e.jsx(nt,{isAllowed:Qn,redirectTo:"/staff-tools",children:e.jsx(ig,{})})})}),e.jsx(he,{path:"/people/households",element:e.jsx(Ee,{children:e.jsx(nt,{isAllowed:Zn,redirectTo:"/people",children:e.jsx(Jf,{})})})}),e.jsx(he,{path:"/people/households/:uuid",element:e.jsx(Ee,{children:e.jsx(nt,{isAllowed:Zn,redirectTo:"/people",children:e.jsx(Zf,{})})})}
2),e.jsx(he,{path:"/instructor/classes",element:e.jsx(Ee,{children:e.jsx(nt,{isAllowed:Qe,redirectTo:"/account",children:e.jsx(fb,{})})})}),e.jsx(he,{path:"/timetable/:sessionId",element:e.jsx(Ee,{children:e.jsx(nt,{isAllowed:Qe,redirectTo:"/timetable",children:e.jsx(Rp,{})})})}),e.jsx(he,{path:"/member-hub",element:e.jsx(Ee,{children:e.jsx(nt,{isAllowed:cr,redirectTo:an,children:e.jsx(Bi,{hub:"member"})})})}),e.jsx(he,{path:"/parent-hub",element:e.jsx(Ee,{children:e.jsx(nt,{isAllowed:ur,redirectTo:an,children:e.jsx(Bi,{hub:"parent"})})})}),e.jsx(he,{path:"/instructor-hub",element:e.jsx(Ee,{children:e.jsx(nt,{isAllowed:dr,redirectTo:an,children:e.jsx(Bi,{hub:"instructor"})})})}),e.jsx(he,{path:"/resources",element:e.jsx(Ee,{children:e.jsx(zl,{})})}),e.jsx(he,{path:"/memberships",element:e.jsx(Ee,{children:e.jsx(nt,{isAllowed:va,redirectTo:Zt,children:e.jsx(Gf,{})})})}),e.jsx(he,{path:"/password-setup",element:e.jsx(Ee,{children:e.jsx(Qf,{})})}),e.jsx(he,{path:"/payment-methods",element:e.jsx(Ee,{children:e.jsx(nt,{isAllowed:li,redirectTo:Zt,children:e.jsx(Yf,{})})})}),e.jsx(he,{path:"/billing-history",element:e.jsx(Ee,{children:e.jsx(nt,{isAllowed:wo,redirectTo:Zt,children:e.jsx(hp,{})})})}),e.jsx(he,{path:"/household",element:e.jsx(Ee,{children:e.jsx(nt,{isAllowed:Bc,redirectTo:Zt,children:e.jsx(Dp,{})})})}),e.jsx(he,{path:"/profile",element:e.jsx(Ee,{children:e.jsx(hg,{})})}),e.jsx(he,{path:"/forms",element:e.jsx(Ee,{children:e.jsx(nt,{isAllowed:ko,redirectTo:Zt,children:e.jsx(Ep,{})})})}),e.jsx(he,{path:"/progress",element:e.jsx(Ee,{children:e.jsx(nt,{isAllowed:Xt,redirectTo:Zt,children:e.jsx(gg,{})})})}),e.jsx(he,{path:"/attendance",element:e.jsx(Ee,{children:e.jsx(nt,{isAllowed:Xt,redirectTo:Zt,children:e.jsx(dp,{})})})}),e.jsx(he,{path:"/member/links",element:e.jsx(Ee,{children:e.jsx(zl,{})})}),e.jsx(he,{path:"/curriculum/point/:itemUuid/notes",element:e.jsx(Ee,{children:e.jsx(nt,{isAllowed:Ws,redirectTo:Zt,children:e.jsx(ca,{entryType:"note"})})})}),e.jsx(he,{path:"/curriculum/point/:itemUuid/notes/new",element:e.jsx(Ee,{children:e.jsx(nt,{isAllowed:Ws,redirectTo:Zt,children:e.jsx(ca,{entryType:"note",composerMode:"new"})})})}),e.jsx(he,{path:"/curriculum/point/:itemUuid/notes/:entryUuid/edit",element:e.jsx(Ee,{children:e.jsx(nt,{isAllowed:Ws,redirectTo:Zt,children:e.jsx(ca,{entryType:"note",composerMode:"edit"})})})}),e.jsx(he,{path:"/curriculum/point/:itemUuid/checkpoints",element:e.jsx(Ee,{children:e.jsx(nt,{isAllowed:Ws,redirectTo:Zt,children:e.jsx(ca,{entryType:"checkpoint"})})})}),e.jsx(he,{path:"/curriculum/point/:itemUuid/checkpoints/new",element:e.jsx(Ee,{children:e.jsx(nt,{isAllowed:Ws,redirectTo:Zt,children:e.jsx(ca,{entryType:"checkpoint",composerMode:"new"})})})}),e.jsx(he,{path:"/curriculum/point/:itemUuid/checkpoints/:entryUuid/edit",element:e.jsx(Ee,{children:e.jsx(nt,{isAllowed:Ws,redirectTo:Zt,children:e.jsx(ca,{entryType:"checkpoint",composerMode:"edit"})})})}),e.jsx(he,{path:"/curriculum",element:e.jsx(Ee,{children:e.jsx(nt,{isAllowed:Ws,redirectTo:Zt,children:e.jsx(df,{})})})}),e.jsx(he,{path:"/chat",element:e.jsx(Ee,{children:e.jsx(Gl,{children:e.jsx(yp,{})})})}),e.jsx(he,{path:"/chat/:channelUuid",element:e.jsx(Ee,{children:e.jsx(Gl,{children:e.jsx(Np,{})})})}),e.jsx(he,{path:"/settings",element:e.jsx(Ee,{children:e.jsx(Ng,{})})}),e.jsx(he,{path:"/ai-connections",element:e.jsx(Ee,{children:e.jsx(lp,{})})}),e.jsx(he,{path:"/install-app",element:e.jsx(Ee,{children:e.jsx(Hb,{})})}),e.jsx(he,{path:"/notifications",element:e.jsx(Ee,{children:e.jsx(uf,{})})}),e.jsx(he,{path:"/",element:e.jsx(Xx,{})}),e.jsx(he,{path:"*",element:e.jsx(lf,{})})]})]})})}),e.jsx(Kx,{})]})]})]})})}Pd();function ij(t,s){zd(),ad(),rd.createRoot(t).render(e.jsx(St.StrictMode,{children:e.jsxs(id,{children:[e.jsx(od,{onReady:s}),e.jsx(rj,{})]})}))}const $j=Object.freeze(Object.defineProperty({__proto__:null,mountMemberApp:ij},Symbol.toStringTag,{value:"Module"}));export{Eo as W,$j as m};
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.