1import{r as o,j as e,u as kt,f as ta,N as _a,h as Oy,L as je,O as $c,i as Ds,k as ws,l as _t,m as Uy,n as zy,o as By,p as Ky,q as Qy}from"./vendor-react-CnOzdx1P.js";import{a6 as Ta,a7 as Oh,a8 as an,a9 as Ut,aa as Wy,g as Vy,ab as qc,ac as Gy,ad as Yy,ae as Hy}from"./vendor-CfPWPcRU.js";import{u as J,Q as Jy,M as Zy,a as Xy,b as re,c as W,k as sa,d as eb,e as tb}from"./vendor-tanstack-qTcl0sJc.js";import{P as sb,C as Uh,a as ab,R as nb,T as rb,S as ib,b as lb,c as zh,d as ob,e as cb,f as Bh,g as Kh,h as db,i as Qh,I as Wh,j as Vh,k as Gh,l as Yh,L as Hh,m as Jh,n as mb,o as ub,p as Zh,q as Xh,F as ep,r as Ic,s as tp,t as Oc,O as $l,u as ql,V as sp,v as Il,D as Ol,w as Uc,x as ap,y as np,z as hb,A as rp,B as pb,E as ip,G as lp,H as xb,J as op,K as gb,M as cp,N as dp,Q as fb,U as yb,W as mp,X as bb,Y as jb,Z as vb,_ as up,$ as wb,a0 as hp,a1 as pp,a2 as Nb,a3 as xp,a4 as gp,a5 as fp,a6 as kb}from"./vendor-radix-wLjbJmfR.js";import{T as Bt,L as Ul,B as ga,U as zc,H as Bc,M as fl,a as Lt,I as _b,b as Kn,C as Qt,R as ii,S as Kc,c as Qn,d as Yt,e as Wn,f as br,F as cs,g as xa,h as $t,i as Sa,j as Vn,k as Sb,G as yp,l as li,m as en,n as cn,o as zl,p as Cb,q as ya,r as Xt,A as es,s as Qc,E as Rs,t as ps,u as ts,v as Bl,w as Pb,X as ms,x as pc,y as xc,z as Wc,D as Vc,J as oi,K as gc,P as Cr,N as St,O as jr,Q as Gc,V as Pr,W as Kl,Y as bp,Z as Ua,_ as Ar,$ as zs,a0 as Hn,a1 as ea,a2 as tm,a3 as sm,a4 as Yc,a5 as Gn,a6 as Kt,a7 as jp,a8 as He,a9 as Ft,aa as Dt,ab as yl,ac as fc,ad as am,ae as nm,af as Hc,ag as Gs,ah as Ab,ai as Pn,aj as ca,ak as Hs,al as Eb,am as Tb,an as vp,ao as Jc,ap as Fa,aq as qn,ar as Zc,as as ml,at as Fb,au as Rb,av as Rt,aw as gi,ax as Ca,ay as Mb,az as An,aA as Xc,aB as wp,aC as fi,aD as Db,aE as fa,aF as ed,aG as za,aH as Er,aI as Np,aJ as vs,aK as ni,aL as Lb,aM as kn,aN as vn,aO as Ql,aP as Wl,aQ as Vl,aR as $b,aS as wo,aT as kp,aU as Tr,aV as _p,aW as rm,aX as qb,aY as Sp,aZ as Ib,a_ as Cp,a$ as im,b0 as Pp,b1 as Ap,b2 as Ep,b3 as Ob,b4 as Tp,b5 as Fp,b6 as Rp,b7 as Mp,b8 as td,b9 as Dp,ba as Lp,bb as $p,bc as qp,bd as Ip,be as Op,bf as Ub,bg as sd,bh as Up,bi as zb,bj as vr,bk as as,bl as Bb,bm as wr,bn as ci,bo as Kb,bp as Qb,bq as zp,br as Wb,bs as yc,bt as Gl,bu as Bp,bv as Ys,bw as Vb,bx as Gb,by as Yb,bz as bl,bA as No,bB as Hb,bC as Jb,bD as ad,bE as Zb,bF as Xb,bG as ej,bH as tj,bI as Kp,bJ as sj,bK as aj,bL as nj,bM as Qp,bN as rj}from"./vendor-icons-fw7XwxUA.js";import{R as nn,L as Wp,C as Yl,X as _n,Y as rn,T as ln,a as Vp,b as Gp,c as di,B as mi,d as Nr,P as ij,e as lj,f as oj,S as cj,g as dj}from"./vendor-charts-D2cimLDp.js";import{f as Yp,a as Be,b as Hp,i as nd,c as mj,d as uj,e as hj,s as lm,g as pj,h as xj,j as om,D as gj,p as fj,k as pt,l as yj,m as bj,n as Jp,o as jj,q as vj}from"./vendor-dates-DTE_rExu.js";import{l as rd,E as dn,u as mn,a as un,P as hn}from"./vendor-stripe-0qC3J1OV.js";import{u as Fr,C as qa,a as Rr,F as wj,b as Zp}from"./vendor-forms-BSa7trOX.js";import{N as Nj,m as kj,u as Xp,i as ex,a as tx,b as sx,c as ax,d as nx,E as rx}from"./vendor-tiptap-BG8yKkT3.js";import{u as id,C as ld,a as od,b as kr,D as jl,c as vl,S as wl,v as Nl,d as cd,s as dd,K as md,P as ud}from"./vendor-dnd-DyzRSIY0.js";import{M as _j}from"./vendor-markdown-B4weDGIr.js";import{c as ix,i as Sj,E as Cj}from"./vendor-sentry-vdG1fjaH.js";(function(){const s=document.createElement("link").relList;if(s&&s.supports&&s.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))n(r);new MutationObserver(r=>{for(const i of r)if(i.type==="childList")for(const l of i.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&n(l)}).observe(document,{childList:!0,subtree:!0});function a(r){const i={};return r.integrity&&(i.integrity=r.integrity),r.referrerPolicy&&(i.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?i.credentials="include":r.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function n(r){if(r.ep)return;r.ep=!0;const i=a(r);fetch(r.href,i)}})();function hd(t){return!t||t.length>512||!t.startsWith("/")||t.startsWith("//")||t.includes("\\")||t==="/"||t.startsWith("/login")?null:t}function pd(t){const s=hd(t);return s?`/login?${new URLSearchParams({next:s}).toString()}`:"/login"}
1const ds="https://ams-api.korevera.com",Pj=`${ds}/api/v1`;function lx(t){const s=document.cookie.match(new RegExp("(?:^|; )"+t+"=([^;]*)"));return s?decodeURIComponent(s[1]):void 0}const F=Ta.create({baseURL:Pj,withCredentials:!0,headers:{"Content-Type":"application/json","X-Requested-With":"XMLHttpRequest"},paramsSerializer:{indexes:null}});F.interceptors.request.use(t=>{const s=lx("csrf_token");return s&&(t.headers["X-CSRF-Token"]=s),t});let Ii=!1,bc=[];function cm(t,s=!1){bc.forEach(a=>a(t,s)),bc=[]}function Aj(t){bc.push(t)}F.interceptors.response.use(t=>t,async t=>{const s=t.config,a=s?.url?.includes("/auth/refresh-cookie")||s?.url?.includes("/auth/login"),n=t.response?.data?.detail,r=t.response?.status===403&&typeof n=="string"&&n.toLowerCase().includes("csrf");if((t.response?.status===401||r)&&!a&&!s._retry){if(Ii)return new Promise((l,m)=>{Aj((c,d)=>{c?l(F(s)):d||m(t)})});s._retry=!0,Ii=!0;try{return await F.post("/auth/refresh-cookie"),Ii=!1,cm(!0),F(s)}catch{Ii=!1;const l=!s?.url?.includes("/auth/me");return cm(!1,l),l?(window.location.href=pd(window.location.pathname+window.location.search),new Promise(()=>{})):Promise.reject(t)}}return Promise.reject(t)});const ko=Ta.create({baseURL:`${ds}/api/v1`,withCredentials:!1}),Nn={login:async t=>(await F.post("/auth/login",t)).data,logout:async()=>{await F.post("/auth/logout")},me:async()=>(await F.get("/auth/me")).data,providers:async()=>(await ko.get("/auth/providers")).data,googleSignInUrl:t=>`${ds}/api/v1/auth/google/start?${new URLSearchParams({next:t}).toString()}`,endSessionQuietly:async()=>{const t=()=>{const s=lx("csrf_token");return Ta.post(`${ds}/api/v1/auth/logout?this_browser=true`,null,{withCredentials:!0,headers:s?{"X-CSRF-Token":s}:{}})};try{await t()}catch{await Ta.post(`${ds}/api/v1/auth/refresh-cookie`,null,{withCredentials:!0}).then(t).catch(()=>{})}},inspectLink:async t=>(await ko.post("/auth/account-link/inspect",{token:t})).data,completeLink:async(t,s)=>(await ko.post("/auth/account-link/complete",{token:t,password:s})).data},Gt={list:async(t={})=>(await F.get("/members",{params:t})).data,get:async(t,s)=>(await F.get(`/members/${t}`,{params:s?{society_id:s}:{}})).data,create:async(t,s)=>(await F.post("/members",t,{params:s?{society_id:s}:{}})).data,update:async(t,s,a)=>(await F.patch(`/members/${t}`,s,{params:a?{society_id:a}:{}})).data,delete:async(t,s)=>{await F.delete(`/members/${t}`,{params:s?{society_id:s}:{}})},approve:async t=>(await F.post(`/members/${t}/approve`)).data,reject:async(t,s)=>(await F.post(`/members/${t}/reject`,{reason:s})).data,overrideStatus:async(t,s)=>(await F.post(`/members/${t}/override-status`,s)).data,getPaymentSummary:async t=>(await F.get(`/members/${t}/payment-summary`)).data,impersonate:async t=>(await F.post(`/members/${t}/impersonate`)).data,getDunningStatus:async t=>(await F.get(`/members/${t}/dunning-status`)).data,getEvents:async t=>(await F.get(`/members/${t}/events`)).data,listNotes:async(t,s=1,a=20)=>(await F.get(`/members/${t}/notes`,{params:{page:s,size:a}})).data,createNote:async(t,s)=>(await F.post(`/members/${t}/notes`,{content:s})).data,deleteNote:async(t,s)=>{await F.delete(`/members/${t}/notes/${s}`)},bulkAction:async t=>(await F.post("/members/bulk-action",t)).data,resetPassword:async(t,s)=>(await F.post(`/members/${t}/reset-password`,{new_password:s})).data,bulkSendAccessEmail:async(t,s)=>(await F.post("/members/bulk-send-access-email",{member_ids:t},{params:s?{society_id:s}:{}})).data,bulkSendFacultyWelcomeEmail:async(t,s)=>(await F.post("/members/bulk-send-faculty-welcome-email",{member_ids:t},{params:s?{society_id:s}:{}})).data,duplicateScan:async(t,s=!1)=>(await F.post("/members/duplicate-scan",{include_dismissed:s},{params:t?{society_id:t}:{}})).data,dismissDuplicates:async(t,s)=>(await F.post("/members/duplicate-dismissals",{member_ids:t},{params:s?{society_id:s}:{}})).data,mergeMembers:async(t,s,a)=>(await F.post("/members/merge",{keep_member_id:t,merge_member_ids:s},{params:a?{society_id:a}:{}})).data},Ej={getMemberHistory:async(t,s=1,a=20)=>(await F.get(`/audit/member/${t}`,{params:{page:s,size:a}})).data},Ba={list:async(t={})=>(await F.get("/payments",{params:t})).data,get:async t=>(await F.get(`/payments/${t}`)).data,listByMember:async(t,s=1,a=20)=>(await F.get(`/payments/member/${t}`,{params:{page:s,size:a}})).data,createManual:async t=>(await F.post("/payments/manual",t)).data,createAdminCheckout:async(t,s,a)=>(await F.post("/stripe/checkout/admin-create-session",{member_id:t,success_url:s,cancel_url:a})).data,logPaymentFailure:async t=>(await F.post("/stripe/checkout/admin-log-payment-failure",t)).data,confirmPayment:async(t,s)=>(await F.post("/stripe/checkout/admin-confirm-payment",{payment_intent_id:t,member_id:s})).data,settlementReview:async(t,s,a)=>(await F.post(`/payments/${t}/settlement-review`,s,{params:a?{society_id:a}:{}}
1)).data,sendReceipt:async(t,s)=>(await F.post(`/payments/${t}/send-receipt`,null,{params:s?{to_email:s}:{}})).data,refund:async(t,s)=>(await F.post("/payments/refund",t,{params:s?{society_id:s}:{}})).data,markOrderRefunded:async(t,s,a)=>(await F.post(`/payments/orders/${t}/mark-refunded`,s,{params:a?{society_id:a}:{}})).data,createPaymentIntent:async t=>(await F.post("/stripe/checkout/admin-create-payment-intent",{member_id:t})).data},Ns={dashboard:async t=>(await F.get("/reports/dashboard",{params:t?{society_id:t}:{}})).data,membership:async t=>(await F.get("/reports/membership",{params:t?{society_id:t}:{}})).data,revenue:async(t,s,a)=>{const n=new Date,r=s||`${n.getFullYear()}-01-01`,i=a||n.toISOString().split("T")[0];return(await F.get("/reports/revenue",{params:{start_date:r,end_date:i,...t?{society_id:t}:{}}})).data},retention:async(t,s)=>(await F.get("/reports/retention",{params:{...t&&{society_id:t},...s&&{periods:s}}})).data,membershipMatrix:async t=>(await F.get("/reports/membership-matrix",{params:t?{society_id:t}:{}})).data,expiring:async(t,s)=>(await F.get("/reports/expiring",{params:{...t&&{society_id:t},...s&&{days:s}}})).data,renewalProgress:async t=>(await F.get("/reports/renewal-progress",{params:t?{society_id:t}:{}})).data,revenuePacing:async t=>(await F.get("/reports/revenue-pacing",{params:t?{society_id:t}:{}})).data,lapsedRecovery:async(t,s)=>(await F.get("/reports/lapsed-recovery",{params:{...t&&{society_id:t},...s&&{days:s}}})).data,memberGrowthPacing:async t=>(await F.get("/reports/member-growth",{params:t?{society_id:t}:{}})).data,arAging:async t=>(await F.get("/reports/ar-aging",{params:t?{society_id:t}:{}})).data,atRisk:async t=>(await F.get("/reports/at-risk",{params:t?{society_id:t}:{}})).data,mtdRenewals:async t=>(await F.get("/reports/mtd-renewals",{params:t?{society_id:t}:void 0})).data,failedAutoRenewals:async t=>(await F.get("/reports/failed-auto-renewals",{params:t?{society_id:t}:void 0})).data,pendingActions:async t=>(await F.get("/reports/pending-actions",{params:t?{society_id:t}:void 0})).data,emailHealth:async t=>(await F.get("/reports/email-health",{params:t?{society_id:t}:void 0})).data,renewalFunnel:async t=>(await F.get("/reports/renewal-funnel",{params:t?{society_id:t}:void 0})).data,eventFillRates:async t=>(await F.get("/reports/event-fill-rates",{params:t?{society_id:t}:void 0})).data,membershipTypeTrends:async t=>(await F.get("/reports/membership-type-trends",{params:t?{society_id:t}:void 0})).data,executiveSummaryPdf:async t=>(await F.get("/reports/executive-summary-pdf",{params:t?{society_id:t}:{},responseType:"blob"})).data},dm=1e3,Ks={list:async(t={})=>(await F.get("/societies",{params:t})).data,listAll:async(t={})=>{const s=await Ks.list({...t,page:1,size:dm});if(s.items.length<s.total)throw new Error(`There are more than ${dm} societies to list.`);return s.items},get:async t=>(await F.get(`/societies/${t}`)).data,getBySlug:async t=>(await F.get(`/societies/by-slug/${t}`)).data,create:async t=>(await F.post("/societies",t)).data,update:async(t,s)=>(await F.patch(`/societies/${t}`,s)).data,getDeletionImpact:async t=>(await F.get(`/societies/${t}/deletion-impact`,{timeout:15e3})).data,delete:async t=>(await F.delete(`/societies/${t}`,{timeout:9e4})).data,uploadLogo:async(t,s)=>{const a=new FormData;return a.append("file",s),(await F.post(`/societies/${t}/logo`,a,{headers:{"Content-Type":"multipart/form-data"}})).data},deleteLogo:async t=>(await F.delete(`/societies/${t}/logo`)).data,uploadFavicon:async(t,s)=>{const a=new FormData;return a.append("file",s),(await F.post(`/societies/${t}/favicon`,a,{headers:{"Content-Type":"multipart/form-data"}})).data},deleteFavicon:async t=>(await F.delete(`/societies/${t}/favicon`)).data,getStats:async t=>(await F.get(`/societies/${t}/stats`)).data,getSetupStatus:async t=>(await F.get(`/societies/${t}/setup-status`)).data},yi={configure:async(t,s)=>(await F.post(`/societies/${t}/stripe/configure`,s)).data,getStatus:async t=>(await F.get(`/societies/${t}/stripe/status`)).data,test:async t=>(await F.post(`/societies/${t}/stripe/test`)).data,disconnect:async t=>(await F.post(`/societies/${t}/stripe/disconnect`)).data,toggleMode:async(t,s)=>(await F.post(`/societies/${t}/stripe/toggle-mode`,{mode:s})).data},Jn={configure:async(t,s)=>(await F.post(`/societies/${t}/mailchimp/configure`,s)).data,getStatus:async t=>(await F.get(`/societies/${t}/mailchimp/status`)).data,test:async t=>(await F.post(`/societies/${t}/mailchimp/test`)).data,selectList:async(t,s)=>(await F.post(`/societies/${t}/mailchimp/select-list`,{list_id:s})).data,disconnect:async t=>(await F.post(`/societies/${t}/mailchimp/disconnect`)).data,sync:async(t,s)=>(await F.post("/mailchimp/sync",{list_id:s,sync_all:!0},{params:{society_id:t}})).data,syncSuppressions:async t=>(await F.post("/mailchimp/sync-suppressions",{},{params:{society_id:t}})).data},Mr={configure:async(t,s)=>(await F.post(`/societies/${t}/mailerlite/configure`,s)).data,getStatus:async t=>(await F.get(`/societies/${t}/mailerlite/status`)).data,test:async t=>(await F.post(`/societies/${t}/mailerlite/test`)).data,selectGroup:async(t,s)=>(await F.post(`/societies/${t}/mailerlite/select-group`,{group_id:s})).data,disconnect:async t=>(await F.post(`/societies/${t}/mailerlite/disconnect`)).data,sync:async(t,s)=>(await F.post("/mailerlite/sync",{group_id:s,sync_all:!0},{params:{society_id:t}})).data},Hl={getStatus:async t=>(await F.get(`/societies/${t}/email/status`)).data,configure:async(t,s)=>(await F.post(`/societies/${t}/email/configure`,s)).data,test:async t=>(await F.post(`/societies/${t}/email/test`)).data,disconnect:async t=>(await F.post(`/societies/${t}/email/disconnect`)).data},Dr={getStatus:async t=>(await F.get(`/societies/${t}/event-app/status`)).data,configure:async(t,s)=>(await F.post(`/societies/${t}/event-app/configure`,s)).data,disconnect:async t=>(await F.post(`/societies/${t}/event-app/disconnect`)).data,getAdminSsoToken:async t=>(await F.get(`/commerce/event-app-admin-sso-token?society_id=${t}`)).data,testSync:async(t,s)=>(await F.post(`/societies/${t}/event-app/test-sync`,s?{event_id:s}:{})).data,syncRegistrationFields:async(t,s)=>(await F.post(`/societies/${t}/event-app/test-sync`,{event_id:s})).data.schema_sync},xd={getStatus:async t=>(await F.get(`/societies/${t}/video-library/status`)).data,configure:async(t,s)=>(await F.post(`/societies/${t}/video-library/configure`,s)).data,disconnect:async t=>(await F.post(`/societies/${t}/video-library/disconnect`)).data},gd={configure:async(t,s)=>(await F.post(`/societies/${t}/custom-domain`,s)).data,getStatus:async t=>(await F.get(`/societies/${t}/domain-status`)).data,remove:async t=>(await F.delete(`/societies/${t}/custom-domain`)).data},Zn={list:async(t,s,a)=>{const n=await F.get("/membership-types",{params:{...t?{society_id:t}:{},...s?{include_inactive:!0}:{},...a?{include_non_member:!0}:{}}});return Array.isArray(n.data)?n.data:n.data.items},get:async t=>(await F.get(`/membership-types/${t}`)).data,create:async(t,s)=>(await F.post("/membership-types",s,{params:{society_id:t}})).data,update:async(t,s)=>(await F.patch(`/membership-types/${t}`,s)).data,delete:async t=>{await F.delete(`/membership-types/${t}`)},reorder:async t=>{await Promise.all(t.map((s,a)=>F.patch(`/membership-types/${s}`,{display_order:a})))}},Lr={list:async t=>(await F.get("/custom-fields",{params:{society_id:t,include_inactive:!0}})).data.items,get:async t=>(await F.get(`/custom-fields/${t}`)).data,create:async(t,s)=>(await F.post("/custom-fields",s,{params:{society_id:t}})).data,update:async(t,s)=>(await F.patch(`/custom-fields/${t}`,s)).data,delete:async(t,s)=>{await F.delete(`/custom-fields/${t}`,{params:s?{force:!0}:{}})},reorder:async(t,s)=>{await Promise.all(s.map((a,n)=>F.patch(`/custom-fields/${a}`,{display_order:n})))},getFormSchema:async(t,s,a)=>(await F.get(`/custom-fields/form-schema/${s}`,{params:{society_id:t,...a?{member_id:a}:{}}
1})).data},bi={getAttention:async t=>(await F.get("/platform/attention",{params:t?{society_id:t}:void 0})).data,listActivity:async t=>(await F.get("/platform/activity",{params:t})).data,getDashboard:async()=>(await F.get("/platform/dashboard")).data,getIntegrationHealth:async t=>(await F.get(`/platform/societies/${t}/integration-health`)).data},Pa={list:async(t={})=>(await F.get("/users",{params:t})).data,invite:async t=>(await F.post("/users/invitations",t)).data,resendInvitation:async t=>(await F.post(`/users/${t}/invitation/resend`)).data,revokeInvitation:async t=>(await F.post(`/users/${t}/invitation/revoke`)).data,sendResetLink:async t=>(await F.post(`/users/${t}/reset-link`)).data,update:async(t,s)=>(await F.patch(`/users/${t}`,s)).data,delete:async t=>{await F.delete(`/users/${t}`)}},ks={getSocietySettings:async t=>(await F.get("/society/settings",{params:t?{society_id:t}:{}})).data,updateEmailsPaused:async(t,s)=>(await F.patch("/society/settings",{emails_paused:t},{params:s?{society_id:s}:{}})).data,updateSocietySettings:async(t,s)=>(await F.patch("/society/settings",t,{params:s?{society_id:s}:{}})).data,list:async(t={})=>(await F.get("/emails/templates",{params:t})).data,get:async t=>(await F.get(`/emails/templates/${t}`)).data,create:async(t,s)=>(await F.post("/emails/templates",t,{params:s?{society_id:s}:{}})).data,update:async(t,s)=>(await F.patch(`/emails/templates/${t}`,s)).data,delete:async t=>{await F.delete(`/emails/templates/${t}`)},getVariables:async t=>(await F.get(`/emails/templates/variables/${t}`)).data,sendTest:async t=>(await F.post("/emails/send-test",t)).data,listLogs:async(t={})=>(await F.get("/emails/logs",{params:t})).data,triggerRenewalReminders:async t=>(await F.post("/emails/trigger-renewal-reminders",null,{params:t?{society_id:t}:{}})).data,listSuppressions:async(t={})=>(await F.get("/emails/suppressions",{params:t})).data,createSuppression:async(t,s)=>(await F.post("/emails/suppressions",t,{params:s?{society_id:s}:{}})).data,removeSuppression:async(t,s)=>(await F.delete(`/emails/suppressions/${t}`,{params:s?{society_id:s}:{}})).data,getStats:async t=>(await F.get("/emails/stats",{params:t?{society_id:t}:{}})).data,domainHealth:async(t,s=!1)=>(await F.get(`/societies/${t}/email/domain-health${s?"?refresh=true":""}`)).data},ji={list:async(t={})=>(await F.get("/audit",{params:t})).data,getActions:async()=>(await F.get("/audit/actions")).data.actions,getResourceTypes:async t=>(await F.get("/audit/resource-types",{params:t?{society_id:t}:{}})).data.resource_types,getActors:async t=>(await F.get("/audit/users",{params:t?{society_id:t}:{}})).data.users},Bs={list:async(t={})=>(await F.get("/invoices",{params:t})).data,get:async t=>(await F.get(`/invoices/${t}`)).data,listByMember:async(t,s=1,a=20)=>(await F.get(`/invoices/member/${t}`,{params:{page:s,size:a}})).data,markPaid:async(t,s)=>(await F.post(`/invoices/${t}/mark-paid`,s)).data,void:async(t,s)=>(await F.post(`/invoices/${t}/void`,s)).data,downloadPdf:async t=>(await F.get(`/invoices/${t}/pdf`,{responseType:"blob"})).data,sendEmail:async(t,s)=>(await F.post(`/invoices/${t}/send-email`,s||{})).data,getOutstandingCount:async t=>(await F.get("/invoices/outstanding-count",{params:t?{society_id:t}:{}})).data,sendReminders:async(t,s)=>(await F.post("/invoices/send-reminders",s||{},{params:t?{society_id:t}:{}})).data,bulkPrintPreview:async(t,s)=>(await F.post("/invoices/bulk-print/preview",{member_ids:t},{params:s?{society_id:s}:{}})).data,bulkPrintDownload:async(t,s,a=[])=>(await F.post("/invoices/bulk-print/download",{member_ids:t,acknowledged_skipped_invoice_ids:a},{params:s?{society_id:s}:{},responseType:"blob",timeout:18e4})).data,previewBatch:async(t,s)=>(await F.post("/invoices/batches/preview",t,{params:s?{society_id:s}:{}})).data,createBatch:async(t,s)=>(await F.post("/invoices/batches",t,{params:s?{society_id:s}:{}})).data,listBatches:async(t=1,s=20,a)=>(await F.get("/invoices/batches",{params:{page:t,size:s,...a?{society_id:a}:{}}})).data,getBatch:async t=>(await F.get(`/invoices/batches/${t}`)).data,downloadBatch:async t=>(await F.get(`/invoices/batches/${t}/download`,{responseType:"blob"})).data,sendBatchEmails:async t=>(await F.post(`/invoices/batches/${t}/send-emails`)).data};function mm(t,s){const a=window.URL.createObjectURL(t),n=document.createElement("a");n.href=a,n.download=s,document.body.appendChild(n),n.click(),window.URL.revokeObjectURL(a),document.body.removeChild(n)}const $a={previewImport:async(t,s,a,n=!1)=>{const r=new FormData;return r.append("file",t),(await F.post("/imports/members/preview",r,{headers:{"Content-Type":"multipart/form-data"},params:{update_existing:s,society_id:a,allow_blank_email:n}})).data},executeImport:async(t,s,a)=>{const n=new FormData;return n.append("file",t),(await F.post("/imports/members",n,{headers:{"Content-Type":"multipart/form-data"},params:{update_existing:s.update_existing,send_welcome_emails:s.send_welcome_emails,default_membership_type_id:s.default_membership_type_id,default_status:s.default_status,allow_blank_email:s.allow_blank_email,society_id:a}})).data},downloadTemplate:()=>{window.open(`${ds}/api/v1/imports/members/template`,"_blank")},exportMembers:async(t,s)=>{const a=await F.get("/exports/members",{params:{format:t.format,status:t.status,membership_type_id:t.membership_type_id,include_custom_fields:t.include_custom_fields,fields:t.fields,query:t.query,filter_field:t.filter_field,filter_value:t.filter_value,filter_tag:t.filter_tag,expiring_within_days:t.expiring_within_days,sort_by:t.sort_by,sort_dir:t.sort_dir,society_id:s},responseType:"blob"}),n=t.format==="xlsx"?"xlsx":"csv";mm(a.data,`members.${n}`)},listTemplates:async t=>(await F.get("/export-templates",{params:{society_id:t}})).data,createTemplate:async(t,s)=>(await F.post("/export-templates",t,{params:{society_id:s}})).data,deleteTemplate:async(t,s)=>{await F.delete(`/export-templates/${t}`,{params:{society_id:s}})},exportPayments:async(t,s)=>{const a=await F.get("/exports/payments",{params:{format:t.format,date_from:t.date_from,date_to:t.date_to,society_id:s},responseType:"blob"}),n=t.format==="xlsx"?"xlsx":"csv";mm(a.data,`payments.${n}`)}},Sn={listSteps:async t=>(await F.get("/renewal-sequence/steps",{params:t?{society_id:t}:{}})).data,createStep:async(t,s)=>(await F.post("/renewal-sequence/steps",t,{params:s?{society_id:s}:{}})).data,updateStep:async(t,s,a)=>(await F.patch(`/renewal-sequence/steps/${t}`,s,{params:a?{society_id:a}:{}}
1)).data,deleteStep:async(t,s)=>{await F.delete(`/renewal-sequence/steps/${t}`,{params:s?{society_id:s}:{}})},reorderSteps:async(t,s)=>(await F.post("/renewal-sequence/steps/reorder",{step_ids:t},{params:s?{society_id:s}:{}})).data,applyDefaults:async t=>(await F.post("/renewal-sequence/apply-defaults",null,{params:t?{society_id:t}:{}})).data,restoreDefaults:async(t,s)=>(await F.post("/renewal-sequence/restore-defaults",{step_ids:t},{params:s?{society_id:s}:{}})).data,getLog:async(t={})=>(await F.get("/renewal-sequence/log",{params:t})).data,getMemberLog:async(t,s={})=>(await F.get(`/renewal-sequence/member/${t}/log`,{params:s})).data},Xa={getRegisterOptions:async()=>(await F.post("/auth/webauthn/register/options",{})).data,verifyRegistration:async(t,s)=>(await F.post("/auth/webauthn/register/verify",{credential:t,name:s})).data,getAuthenticateOptions:async t=>(await F.post("/auth/webauthn/authenticate/options",{email:t||null})).data,verifyAuthentication:async t=>(await F.post("/auth/webauthn/authenticate/verify",{credential:t})).data,listCredentials:async()=>(await F.get("/auth/webauthn/credentials")).data,renameCredential:async(t,s)=>(await F.patch(`/auth/webauthn/credentials/${t}`,{name:s})).data,deleteCredential:async t=>{await F.delete(`/auth/webauthn/credentials/${t}`)}},ox=o.createContext(null),Wr=t=>`ams_selected_society_id:${t}`;function Tj({children:t}){const[s,a]=o.useState(null),[n,r]=o.useState(!0),[i,l]=o.useState(null),m=s?.id??null;let c=i?.id??null;if(m&&i?.userId!==m){const w=Wr(m),v=sessionStorage.getItem(w);c=v!==null?v||null:localStorage.getItem(w),l({userId:m,id:c})}o.useEffect(()=>{i&&sessionStorage.setItem(Wr(i.userId),i.id??"")},[i]);const d=o.useCallback(w=>{m&&(sessionStorage.setItem(Wr(m),w??""),w?localStorage.setItem(Wr(m),w):localStorage.removeItem(Wr(m)),l({userId:m,id:w}))},[m]),h=(s&&s.role!=="super_admin"?s.society_id:null)??(m?c:null),p=s?.role==="super_admin"&&!h;o.useEffect(()=>{localStorage.removeItem("ams_selected_society_id")},[]),o.useEffect(()=>{let w=!0;return(async()=>{if(window.location.pathname.includes("/portal")){w&&r(!1);return}try{const k=await Nn.me();w&&a(k)}catch{w&&a(null)}finally{w&&r(!1)}})(),()=>{w=!1}},[]);const x=o.useCallback(async(w,v)=>{const k=await Nn.login({email:w,password:v});a(k.user)},[]),f=o.useCallback(async()=>{const w=await Xa.getAuthenticateOptions(),v=await Oh({optionsJSON:w}),k=await Xa.verifyAuthentication(v);a(k.user)},[]),b=o.useCallback(async()=>{await Nn.logout(),d(null),a(null)},[d]),N=o.useCallback(()=>{s?.role==="super_admin"&&d(null)},[s?.role,d]),j=o.useMemo(()=>({user:s,isLoading:n,login:x,loginWithPasskey:f,logout:b,selectedSocietyId:h,setSelectedSocietyId:d,isPlatformMode:p,exitToPlatform:N}),[s,n,x,f,b,h,d,p,N]);return e.jsx(ox.Provider,{value:j,children:t})}function V(){const t=o.useContext(ox);if(!t)throw new Error("useAuth must be used within an AuthProvider");return t}const Jl="korevera.signupResume.",Fj="signup_payment_incomplete",cx="An account with this email already exists. Its membership starts once your payment is received â no need to sign up again. Questions? Please contact the society office.",um=7200*1e3;function Rj(t){const s=t.split(".")[1];if(!s)return um;try{const a=atob(s.replace(/-/g,"+").replace(/_/g,"/")),{exp:n,iat:r}=JSON.parse(a);if(typeof n=="number"&&typeof r=="number"&&n>r)return(n-r)*1e3}catch{}return um}function Zl(){try{return window.sessionStorage}catch{return null}}function fd(t,s,{now:a=Date.now(),historyKey:n,paymentIntentId:r,expiresAt:i}={}){const l={resumeToken:s,expiresAt:i??a+Rj(s),historyKey:n,paymentIntentId:r};try{Zl()?.setItem(Jl+t,JSON.stringify(l))}catch{}}function dx(t,s=Date.now()){const a=Zl()?.getItem(Jl+t);if(!a)return null;try{const n=JSON.parse(a);if(typeof n.resumeToken=="string"&&typeof n.expiresAt=="number"&&n.expiresAt>s)return{resumeToken:n.resumeToken,expiresAt:n.expiresAt,historyKey:typeof n.historyKey=="string"?n.historyKey:void 0,paymentIntentId:typeof n.paymentIntentId=="string"?n.paymentIntentId:void 0}}catch{}return Ln(t),null}function Ln(t){Zl()?.removeItem(Jl+t)}function Mj(t,s){const a=dx(t);a&&fd(t,a.resumeToken,{historyKey:a.historyKey,expiresAt:a.expiresAt,paymentIntentId:s})}function Dj(t){return t.split("_secret_")[0]}function mx(t,{locationKey:s,stripeReturnPaymentIntent:a}){const n=dx(t);return n?(a?n.paymentIntentId===a:$j(n,s))?n:(Ln(t),null):null}function ux(t){return new URLSearchParams(t).get("payment_intent")}function $n(){const t=Zl();if(!t)return;const s=[];for(let a=0;a<t.length;a++){const n=t.key(a);n?.startsWith(Jl)&&s.push(n)}s.forEach(a=>t.removeItem(a))}const Lj=["payment_intent","payment_intent_client_secret","redirect_status"];function $j(t,s){return t.historyKey!==s?!1:s!=="default"||qj()}function qj(){try{const[t]=performance.getEntriesByType("navigation");return t?.type==="reload"||t?.type==="back_forward"}catch{return!1}}function hx(t=window.location.search){const s=new URLSearchParams(t);return s.has("payment_intent")||s.has("redirect_status")}function Ij(t){const s=new URLSearchParams(t);for(const n of Lj)s.delete(n);const a=s.toString();return a?`?${a}`:""}function px(t){const s=t?.response;if(s?.status!==403)return null;const a=s.data;return a?.code===Fj&&typeof a.resume_token=="string"?a.resume_token:null}const Oj=5e3,Uj=15e3,_o=6e4;function zj(t){if(t.type!=="card_error"&&t.type!=="validation_error")return!1;const s=t.payment_intent?.status;return s===void 0||s==="requires_payment_method"}const Bj=["ams.korevera.com","localhost","127.0.0.1"],hm=typeof window<"u"?window.location.hostname:"",xx=!Bj.some(t=>hm===t||hm.endsWith(`.${t}`)),Kj=xx?"/api/v1":"https://ams-api.korevera.com/api/v1";let ui=null;function Za(t){ui=t}const Qj=new Set(["/portal/login","/portal/refresh-cookie","/portal/magic-link","/portal/verify-magic-link"]),Wj="/signup/society/";function Vj(t){if(!t)return!1;const s=t.split("?")[0].replace(/^https?:\/\/[^/]+/,"").replace(/^\/api\/v1(?=\/)/,"");return Qj.has(s)||s.startsWith(Wj)}function Gj(){if(xx)return"/portal/login";const t=localStorage.getItem("portal_society_slug")||"";return t?`/${t}/portal/login`:"/"}const Me=Ta.create({baseURL:Kj,withCredentials:!0,headers:{"Content-Type":"application/json"}});Me.interceptors.request.use(t=>{if(localStorage.getItem("portal_impersonated_by")){const a=localStorage.getItem("portal_access_token");a&&(t.headers.Authorization=`Bearer ${a}`)}return ui&&t.method&&!["get","head","options"].includes(t.method.toLowerCase())&&(t.headers["X-Portal-CSRF-Token"]=ui),t});let Oi=!1,jc=[];function pm(t,s=!1){jc.forEach(a=>a(t,s)),jc=[]}function So(t,s=""){$n(),localStorage.removeItem("portal_access_token"),localStorage.removeItem("portal_member"),localStorage.removeItem("portal_society_slug"),localStorage.removeItem("portal_impersonated_by"),ui=null,window.location.href=t+s}Me.interceptors.response.use(t=>t,async t=>{const s=t.config,a=Gj(),n=Vj(s?.url),r=localStorage.getItem("portal_impersonated_by");if(t.response?.status===401&&!n&&!s._retry&&!r){if(Oi)return new Promise((i,l)=>{jc.push((m,c)=>{m?i(Me(s)):c||l(t)})});s._retry=!0,Oi=!0;try{const i=await Me.post("/portal/refresh-cookie");return i.data?.csrf_token&&(ui=i.data.csrf_token),Oi=!1,pm(!0),Me(s)}catch{Oi=!1;const i=!s?.url?.includes("/portal/profile");return pm(!1,i),i?(So(a),new Promise(()=>{})):Promise.reject(t)}}if(t.response?.status===401&&r&&!n)return So(a),new Promise(()=>{});if(t.response?.status===403&&!n){const i=t.response?.data?.detail;(typeof i=="string"?i:"").includes("CSRF")||So(a,"?error=access_restricted")}return Promise.reject(t)});const vc={matchCandidates:async(t,s)=>(await Me.post("/portal/wizard/match-candidates",{event_id:t,role_type_id:s})).data,startLinkChallenge:async t=>(await Me.post("/portal/wizard/start-link-challenge",{challenge_eligible_id:t})).data,verifyLinkChallenge:async(t,s)=>{const a=await Me.post("/portal/wizard/verify-link-challenge",{challenge_id:t,code:s});return a.data.verified&&a.data.csrf_token&&Za(a.data.csrf_token),a.data}},gt={login:async t=>(await Me.post("/portal/login",t)).data,getProfile:async()=>(await Me.get("/portal/profile")).data,getCustomFields:async()=>
1(await Me.get("/portal/custom-fields")).data,logout:async()=>{await Me.post("/portal/logout")},updateProfile:async t=>(await Me.patch("/portal/profile",t)).data,changePassword:async t=>{await Me.post("/portal/change-password",t)},setPassword:async t=>{await Me.post("/portal/set-password",{new_password:t})},getSubscription:async()=>(await Me.get("/portal/subscription")).data,toggleAutoRenew:async t=>{await Me.patch(`/portal/auto-renew?auto_renew=${t}`)},cancelSubscription:async(t=!1)=>{await Me.post("/portal/subscription/cancel",{immediate:t})},reactivateSubscription:async()=>{await Me.post("/portal/subscription/reactivate")},getPayments:async(t=1,s=20)=>(await Me.get("/portal/payments",{params:{page:t,size:s}})).data,getInvoices:async(t=1,s=10,a)=>(await Me.get("/portal/invoices",{params:{page:t,size:s,status:a}})).data,getPaymentMethod:async()=>(await Me.get("/portal/payment-method")).data,createSetupIntent:async()=>(await Me.post("/portal/create-setup-intent")).data,confirmCardUpdate:async t=>{await Me.post("/portal/confirm-card-update",t)},getDashboardStats:async()=>(await Me.get("/portal/dashboard-stats")).data,getMyEvents:async()=>(await Me.get("/portal/my-events")).data,getSignupInfo:async t=>(await Me.get(`/signup/society/${t}`)).data,getPublicEvents:async t=>(await Me.get(`/signup/society/${t}/events`)).data,getPublicProduct:async(t,s)=>(await Me.get(`/signup/society/${t}/product/${s}`)).data,signup:async(t,s)=>(await Me.post(`/signup/society/${t}`,s)).data,confirmSignupPayment:async(t,s,a)=>(await Me.post(`/signup/society/${t}/confirm-payment`,{payment_intent_id:s,member_id:a})).data,resumeSignupPayment:async(t,s)=>(await Me.post(`/signup/society/${t}/resume-payment`,{resume_token:s})).data,logSignupPaymentFailure:async(t,s)=>{await Me.post(`/signup/society/${t}/log-payment-failure`,s)},validateSignupPromoCode:async(t,s)=>(await Me.post(`/signup/society/${t}/validate-promo-code`,null,{params:{code:s}})).data,createRenewalPayment:async t=>(await Me.post("/portal/renew-membership",{auto_renew_opt_in:t})).data,confirmRenewal:async t=>{await Me.post("/portal/confirm-renewal",{payment_intent_id:t})},renewWithSavedCard:async t=>{await Me.post("/portal/renew-with-saved-card",{payment_intent_id:t})},renewMembershipCheck:async()=>(await Me.post("/portal/renew-membership-check")).data,createInvoicePayment:async t=>(await Me.post(`/portal/invoices/${t}/pay`)).data,confirmInvoicePayment:async(t,s)=>{await Me.post(`/portal/invoices/${t}/confirm-payment`,{payment_intent_id:s})},requestEmailChange:async t=>(await Me.post("/portal/request-email-change",{new_email:t})).data,verifyEmailChange:async t=>(await Me.post("/portal/verify-email-change",{token:t})).data,upgradeMembership:async t=>(await Me.post("/portal/upgrade-membership",t)).data,confirmUpgrade:async t=>(await Me.post("/portal/confirm-upgrade",t)).data,getEventAppSsoToken:async()=>(await Me.get("/portal/event-app-sso-token")).data,getVideoLibrarySsoToken:async()=>(await Me.get("/portal/video-library-sso-token")).data,getDirectoryMembers:async t=>{const{customFieldFilters:s,...a}=t,n={};if(s)for(const[i,l]of Object.entries(s))l&&(n[`cf_${i}`]=l);return(await Me.get("/portal/directory",{params:{...a,...n}})).data},getDirectoryFilters:async()=>(await Me.get("/portal/directory/filters")).data,uploadHeadshot:async t=>{const s=new FormData;return s.append("file",t),(await Me.post("/portal/headshot",s,{headers:{"Content-Type":"multipart/form-data"}})).data},deleteHeadshot:async()=>(await Me.delete("/portal/headshot")).data,submitFeedback:async t=>(await Me.post("/portal/feedback",t)).data},Yj=["ams.korevera.com","localhost","127.0.0.1"],xm=typeof window<"u"?window.location.hostname:"",Hj=!Yj.some(t=>xm===t||xm.endsWith(`.${t}`)),Jj=Hj?"/api/v1":"https://ams-api.korevera.com/api/v1",gm=Ta.create({baseURL:Jj,withCredentials:!0,headers:{"Content-Type":"application/json"}}),jn={getRegisterOptions:async()=>(await Me.post("/portal/webauthn/register/options",{})).data,verifyRegistration:async(t,s)=>(await Me.post("/portal/webauthn/register/verify",{credential:t,name:s})).data,getAuthenticateOptions:async(t,s)=>(await gm.post("/portal/webauthn/authenticate/options",{society_slug:t,email:s||null})).data,verifyAuthentication:async(t,s)=>(await gm.post("/portal/webauthn/authenticate/verify",{credential:t,society_slug:s})).data,listCredentials:async()=>(await Me.get("/portal/webauthn/credentials")).data,renameCredential:async(t,s)=>(await Me.patch(`/portal/webauthn/credentials/${t}`,{name:s})).data,deleteCredential:async t=>{await Me.delete(`/portal/webauthn/credentials/${t}`)}},Zj=[["portal","profile"],["portal","price-preview"],["portal","renewal-preview"],["portal","my-registrations"],["portal","my-orders"],["portal","payments"],["portal","invoices"],["portal","payment-method"],["portal","subscription"],["portal","dashboard-stats"],["portal","my-events"],["portal","my-donations"],["portal","my-committees"],["portal","committee-openings"],["portal","my-applications"],["portal","polls"],["portal","poll-results"],["portal","support","conversation"],["portal","events"],["portal","event-detail"]];function fn(t){for(const s of Zj)t.removeQueries({queryKey:s})}const yd="guest";function vi(t){const s=`ams_cart_${t||"default"}`;return{cartKey:s,ownerKey:`${s}_owner`}}function gx(t){const{cartKey:s,ownerKey:a}=vi(t);localStorage.removeItem(s),localStorage.removeItem(a)}function Xj(t,s){const{cartKey:a,ownerKey:n}=vi(t);localStorage.setItem(a,JSON.stringify(s)),localStorage.setItem(n,yd)}function ev(t,s){const{cartKey:a,ownerKey:n}=vi(t);localStorage.getItem(a)!==null&&localStorage.setItem(n,s)}const Co="portal_access_token",Da="portal_member",wa="portal_society_slug",Po="portal_impersonated_by",fx=o.createContext(null);function tv({children:t}){const s=J(),[a,n]=o.useState(()=>
1{try{const w=localStorage.getItem(Da);return w?JSON.parse(w):null}catch{}return null}),[r,i]=o.useState(()=>localStorage.getItem(wa)||""),l=o.useRef(r);o.useEffect(()=>{l.current=r},[r]);const[m]=o.useState(()=>localStorage.getItem(Po)),c=m?!!localStorage.getItem(Co)&&!!a:!!a,d=a?.has_password!==!1;o.useEffect(()=>{m||!a||gt.getProfile().then(w=>{w.csrf_token&&Za(w.csrf_token)}).catch(w=>{})},[]),o.useEffect(()=>{let w=null;try{w=new BroadcastChannel("portal-auth"),w.onmessage=k=>{if(k.data?.type==="phase3-merge"){const S=k.data.societySlug,_=l.current;if(S&&_&&S!==_)return;const y=k.data.payload;if(y.profile&&y.member_id){const C=y.profile,P={id:y.member_id,email:C.email,first_name:C.first_name,last_name:C.last_name,has_password:!0};localStorage.setItem(Da,JSON.stringify(P)),n(P)}y.csrf_token&&Za(y.csrf_token),fn(s)}}}catch{}const v=k=>{if(k.key!==Da||!k.newValue)return;const S=localStorage.getItem(wa),_=l.current;if(!(_&&S&&_!==S))try{const y=JSON.parse(k.newValue);n(y),fn(s)}catch{}};return window.addEventListener("storage",v),()=>{w?.close(),window.removeEventListener("storage",v)}},[s]);const u=o.useCallback(async(w,v,k)=>{const S=await gt.login({email:w,password:v,society_slug:k}),_=S.member;Za(S.csrf_token),localStorage.setItem(Da,JSON.stringify(_)),localStorage.setItem(wa,k),n(_),i(k),fn(s),$n()},[s]),h=o.useCallback(async w=>{const v=await jn.getAuthenticateOptions(w),k=await Oh({optionsJSON:v}),S=await jn.verifyAuthentication(k,w),_=S.member;Za(S.csrf_token),localStorage.setItem(Da,JSON.stringify(_)),localStorage.setItem(wa,w),n(_),i(w),fn(s),$n()},[s]),p=o.useCallback((w,v,k)=>{Za(k),localStorage.setItem(Da,JSON.stringify(w)),localStorage.setItem(wa,v),n(w),i(v),fn(s),$n()},[s]),x=o.useCallback((w,v,k)=>{localStorage.setItem(Co,w),localStorage.setItem(Da,JSON.stringify(k)),localStorage.setItem(wa,v),localStorage.setItem(Po,"admin"),n(k),i(v),fn(s),$n()},[s]),f=o.useCallback(()=>{if(a){const w={...a,has_password:!0};localStorage.setItem(Da,JSON.stringify(w)),n(w)}},[a]),b=o.useCallback(w=>{if(w.profile&&w.member_id){ev(localStorage.getItem(wa)??"default",w.member_id);const v=w.profile,k={id:w.member_id,email:v.email,first_name:v.first_name,last_name:v.last_name,has_password:!0};localStorage.setItem(Da,JSON.stringify(k)),n(k)}w.csrf_token&&Za(w.csrf_token),fn(s);try{const v=w.profile;if(v&&v.is_non_member===!1){const{cartKey:S}=vi(localStorage.getItem(wa)??"default"),_=localStorage.getItem(S);if(_){const y=JSON.parse(_);if(Array.isArray(y)){const C=y.map(P=>P.claimMembershipOffer===!0?{...P,claimMembershipOffer:!1}:P);localStorage.setItem(S,JSON.stringify(C))}}}}catch{}try{const v=new BroadcastChannel("portal-auth");v.postMessage({type:"phase3-merge",societySlug:localStorage.getItem(wa)??null,payload:w}),v.close()}catch{}},[s]),N=o.useCallback(async()=>{try{await gt.logout()}catch{}gx(localStorage.getItem(wa)??"default"),$n(),localStorage.removeItem(Co),localStorage.removeItem(Da),localStorage.removeItem(wa),localStorage.removeItem(Po),Za(null),n(null),i(""),fn(s)},[s]),j=o.useMemo(()=>({member:a,isAuthenticated:c,hasPassword:d,societySlug:r,impersonatedBy:m,login:u,loginWithPasskey:h,loginWithMember:p,loginAsImpersonation:x,markPasswordSet:f,logout:N,applyMergeUpdate:b}),[a,c,d,r,m,u,h,p,x,f,N,b]);return e.jsx(fx.Provider,{value:j,children:t})}function ft(){const t=o.useContext(fx);if(!t)throw new Error("useMemberAuth must be used within a MemberAuthProvider");return t}const yx=o.createContext({domainSlug:null,isResolving:!1,isCustomDomain:!1}),sv=["ams.korevera.com","localhost","127.0.0.1"];function av({children:t}){const[s,a]=o.useState(null),[n,r]=o.useState(!1),i=window.location.hostname,l=!sv.some(m=>i===m||i.endsWith(`.${m}`));return o.useEffect(()=>{if(!l)return;r(!0),fetch(`${l?"":ds}/api/v1/societies/resolve-domain/${i}`).then(c=>{if(!c.ok)throw new Error("Domain not found");return c.json()}).then(c=>{a(c.slug)}).catch(()=>{a(null)}).finally(()=>{r(!1)})},[i,l]),e.jsx(yx.Provider,{value:{domainSlug:s,isResolving:n,isCustomDomain:l},children:t})}function da(){return o.useContext(yx)}function wi(t){const s=on(t);return s!==void 0&&s>=400&&s<500}function on(t){return an(t)?t.response?.status:void 0}function bx(t){if(!Array.isArray(t))return[];const s=[];for(const a of t)typeof a!="object"||a===null||!("msg"in a)||typeof a.msg!="string"||!a.msg.trim()||s.push({loc:"loc"in a&&Array.isArray(a.loc)?a.loc:[],msg:a.msg});return s}function Ni(t,{withField:s=!1}={}){const a=t?.response?.data?.detail;
1if(typeof a=="string"&&a.trim())return a;const[n]=bx(a);if(n){const r=s?nv(n.loc):null;return r?`${r}: ${n.msg}`:n.msg}return null}function jx(t){if(!Array.isArray(t))return null;const s=t[t.length-1];return typeof s=="string"&&s!=="body"?s:null}function nv(t){const s=jx(t);if(!s)return null;const a=s.replace(/_/g," ");return a.charAt(0).toUpperCase()+a.slice(1)}function Xn(t,s){const a=Ni(t,{withField:!0});if(a)return a;const n=t;return n?.isAxiosError&&!n.response?"The server could not be reached.":s}function vx(t){const s=t.trim();return/[.!?]$/.test(s)?s:`${s}.`}function rv(t){const s=t;return s?.response?.status!==422?[]:bx(s.response.data?.detail).flatMap(({loc:a,msg:n})=>{const r=jx(a);return r?[{field:r,message:n}]:[]})}const iv=new Jy({mutationCache:new Zy({onError:(t,s,a,n)=>{if(n.meta?.suppressErrorToast||n.options.onError)return;const r=an(t)?t.response?.status:void 0;r===401||r===422||Ut.error(Xn(t,"Something went wrong. Please try again."))}}),defaultOptions:{queries:{staleTime:1e3*60*5,retry:(t,s)=>{const a=on(s),n=wi(s)&&a!==408&&a!==429;return t<1&&!n},refetchOnWindowFocus:!1}}});function lv({children:t}){return e.jsx(Xy,{client:iv,children:t})}const wx=o.createContext(void 0);function ov(){const t=localStorage.getItem("theme");return t==="light"||t==="dark"?t:window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function cv({children:t}){const[s,a]=o.useState(ov);o.useEffect(()=>{const r=document.documentElement;s==="dark"?r.classList.add("dark"):r.classList.remove("dark"),localStorage.setItem("theme",s)},[s]);const n=()=>a(r=>r==="light"?"dark":"light");return e.jsx(wx.Provider,{value:{theme:s,toggleTheme:n},children:t})}function bd(){const t=o.useContext(wx);if(!t)throw new Error("useTheme must be used within ThemeProvider");return t}const Nx=o.createContext(void 0);function dv(){try{const t=localStorage.getItem("portal-theme");if(t==="dark"||t==="light")return t}catch{}return"light"}function mv({children:t}){const[s,a]=o.useState(dv);o.useEffect(()=>{const r=document.documentElement;s==="dark"?r.classList.add("dark"):r.classList.remove("dark"),r.setAttribute("data-portal-theme",s);try{localStorage.setItem("portal-theme",s)}catch{}return()=>{r.removeAttribute("data-portal-theme");try{localStorage.getItem("theme")==="dark"?r.classList.add("dark"):r.classList.remove("dark")}catch{r.classList.remove("dark")}}},[s]);const n=()=>a(r=>r==="dark"?"light":"dark");return e.jsx(Nx.Provider,{value:{theme:s,toggleTheme:n},children:t})}function uv(){const t=o.useContext(Nx);if(!t)throw new Error("usePortalTheme must be used within PortalThemeProvider");return t}function me(...t){return Wy(Vy(t))}const $r=ab,fs=nb,ys=rb,hs=o.forwardRef(({className:t,sideOffset:s=4,...a},n)=>e.jsx(sb,{children:e.jsx(Uh,{ref:n,sideOffset:s,className:me("z-50 overflow-hidden rounded-md border bg-popover px-3 py-1.5 text-sm text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",t),...a})}));hs.displayName=Uh.displayName;const hv=qc("inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",outline:"border border-input bg-background text-foreground hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-10 px-4 py-2",sm:"h-9 rounded-md px-3",lg:"h-11 rounded-md px-8",icon:"h-10 w-10"}},defaultVariants:{variant:"default",size:"default"}}),g=o.forwardRef(({className:t,variant:s,size:a,asChild:n=!1,...r},i)=>{const l=n?ib:"button";return e.jsx(l,{className:me(hv({variant:s,size:a,className:t})),ref:i,...r})});g.displayName="Button";class Xl extends o.Component{constructor(s){super(s),this.state={hasError:!1}}static getDerivedStateFromError(s){return{hasError:!0,error:s}}componentDidCatch(s,a){console.error("ErrorBoundary caught:",s,a)}handleReset=()=>{this.setState({hasError:!1,error:void 0})};render(){return this.state.hasError?this.props.fallback?this.props.fallback:e.jsxs("div",{className:"flex min-h-[400px] flex-col items-center justify-center p-8 text-center",children:[e.jsx(Bt,{className:"mb-4 h-12 w-12 text-destructive"}),e.jsx("h2",{className:"mb-2 text-xl font-semibold",children:"Something went wrong"}),e.jsx("p",{className:"mb-4 text-muted-foreground",children:"An unexpected error occurred. Please try again."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(g,{onClick:this.handleReset,variant:"outline",children:"Try again"}),e.jsx(g,{onClick:()=>{const s=window.location.pathname.match(/^\/([^/]+)\/portal/);window.location.href=s?`/${s[1]}/portal/dashboard`:"/"},children:"Go to home"})]}),!1]}):this.props.children}}const kx=[{name:"Dashboard",href:"/",icon:Ul}
1],_x=[{label:"Members",items:[{name:"Members",href:"/members",icon:Lt},{name:"Membership types",href:"/membership-types",icon:_b},{name:"Committees",href:"/committees",icon:Kn,module:"committees"}]},{label:"Finance",items:[{name:"Payments",href:"/payments",icon:Qt},{name:"Invoices",href:"/invoices",icon:ii},{name:"Disputes",href:"/disputes",icon:Kc},{name:"Orders",href:"/orders",icon:Qn,module:"commerce"}]},{label:"Commerce",items:[{name:"Events",href:"/events",icon:Yt,module:"commerce"},{name:"Products",href:"/products",icon:Wn,module:"commerce"},{name:"Donations",href:"/donation-campaigns",icon:br,module:"commerce"},{name:"Registration forms",href:"/registration-forms",icon:cs,module:"commerce"},{name:"Promo codes",href:"/promo-codes",icon:xa,module:"commerce"}]},{label:"Engagement",items:[{name:"Emails",href:"/emails",icon:$t},{name:"Polls",href:"/polls",icon:Sa},{name:"Announcements",href:"/announcements",icon:Vn}]},{label:"Admin",items:[{name:"Reports",href:"/reports",icon:cs},{name:"Users",href:"/users",icon:zc,adminOnly:!0},{name:"Audit log",href:"/audit",icon:Sb},{name:"Merged accounts",href:"/admin/members/merged",icon:yp,module:"phase3_link_merge",adminOnly:!0},{name:"Match history",href:"/admin/members/link-history",icon:li,module:"phase3_link_merge",adminOnly:!0},{name:"Import/export",href:"/import-export",icon:en},{name:"Settings",href:"/settings",icon:cn},{name:"Help",href:"/help",icon:zl}]}];function Sx(t,s,a){return t.map(n=>({...n,items:n.items.filter(r=>r.adminOnly&&a?.isAdmin===!1?!1:r.module?r.module==="commerce"?s?.commerce_enabled===!0:r.module==="committees"?s?.committees_enabled===!0:r.module==="mailchimp"?s?.mailchimp_enabled===!0:r.module==="phase3_link_merge"?s?.phase3_link_merge_enabled===!0:!0:!0)})).filter(n=>n.items.length>0)}const Cx=[{name:"Overview",href:"/platform",icon:Ul,end:!0},{name:"Societies",href:"/platform/societies",icon:ga,end:!1},{name:"People & access",href:"/platform/users",icon:zc,end:!1},{name:"Activity",href:"/platform/activity",icon:Bc,end:!1},{name:"Feedback",href:"/platform/feedback",icon:fl,end:!1}],O=o.forwardRef(({className:t,type:s,...a},n)=>e.jsx("input",{type:s,className:me("flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm r
1ing-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",t),ref:n,...a}));O.displayName="Input";const kl=ob,_l=cb,hi=o.forwardRef(({className:t,align:s="start",sideOffset:a=4,...n},r)=>e.jsx(lb,{children:e.jsx(zh,{ref:r,align:s,sideOffset:a,className:me("z-50 w-auto rounded-md border bg-popover p-0 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95",t),...n})}));hi.displayName=zh.displayName;function fm(t={}){const{selectedSocietyId:s}=V();return re({queryKey:["members",s,t],queryFn:()=>Gt.list({society_id:s||void 0,page:t.page,size:t.size,status:t.status,membership_type_id:t.membershipTypeId,query:t.search,filter_field:t.filterField,filter_value:t.filterValue,filter_tag:t.filterTag,expiring_within_days:t.expiringWithinDays,sort_by:t.sortBy,sort_dir:t.sortDir}),enabled:!!s})}function Px(t){const{selectedSocietyId:s}=V();return re({queryKey:["member",t,s],queryFn:()=>Gt.get(t,s||void 0),enabled:!!t&&!!s})}function pv(){const t=J(),{selectedSocietyId:s}=V();return W({mutationFn:a=>Gt.create(a,s||void 0),onSuccess:()=>{t.invalidateQueries({queryKey:["members"]})}})}function xv(){const t=J(),{selectedSocietyId:s}=V();return W({mutationFn:({id:a,data:n})=>Gt.update(a,n,s||void 0),onSuccess:(a,n)=>{t.invalidateQueries({queryKey:["members"]}),t.invalidateQueries({queryKey:["member",n.id]})}})}function Ax(){const t=J(),{selectedSocietyId:s}=V();return W({mutationFn:a=>Gt.delete(a,s||void 0),onSuccess:()=>{t.invalidateQueries({queryKey:["members"]})}})}function gv(){const t=J();return W({mutationFn:({id:s,data:a})=>Gt.overrideStatus(s,a),onSuccess:(s,a)=>{t.invalidateQueries({queryKey:["members"]}),t.invalidateQueries({queryKey:["member",a.id]}),t.invalidateQueries({queryKey:["memberAudit",a.id]})}})}function fv(){const t=J();return W({mutationFn:s=>Gt.approve(s),onSuccess:(s,a)=>{t.invalidateQueries({queryKey:["members"]}),t.invalidateQueries({queryKey:["member",a]}),t.invalidateQueries({queryKey:["memberAudit",a]})}})}function yv(){const t=J();return W({mutationFn:({id:s,reason:a})=>Gt.reject(s,a),onSuccess:(s,a)=>{t.invalidateQueries({queryKey:["members"]}),t.invalidateQueries({queryKey:["member",a.id]}),t.invalidateQueries({queryKey:["memberAudit",a.id]})}})}function bv(t,s=1){return re({queryKey:["memberAudit",t,s],queryFn:()=>Ej.getMemberHistory(t,s),enabled:!!t,placeholderData:sa})}function Ex(t){return re({queryKey:["memberPaymentSummary",t],queryFn:()=>Gt.getPaymentSummary(t),enabled:!!t})}function jv(t){return re({queryKey:["memberDunningStatus",t],queryFn:()=>Gt.getDunningStatus(t),enabled:!!t})}function vv(t){return re({queryKey:["memberEvents",t],queryFn:()=>Gt.getEvents(t),enabled:!!t})}function wv(t,s=1){return re({queryKey:["memberNotes",t,s],queryFn:()=>Gt.listNotes(t,s),enabled:!!t,placeholderData:sa})}function Nv(){const t=J();return W({mutationFn:({memberId:s,content:a})=>Gt.createNote(s,a),onSuccess:(s,a)=>{t.invalidateQueries({queryKey:["memberNotes",a.memberId]})}})}function kv(){const t=J();return W({mutationFn:({memberId:s,noteId:a})=>Gt.deleteNote(s,a),onSuccess:(s,a)=>{t.invalidateQueries({queryKey:["memberNotes",a.memberId]})}})}function Tx(){const t=J();return W({mutationFn:s=>Gt.bulkAction(s),onSuccess:()=>{t.invalidateQueries({queryKey:["members"]})}})}function _v(){const{selectedSocietyId:t}=V();return W({mutationFn:s=>Gt.bulkSendAccessEmail(s,t||void 0)})}function Sv(){const{selectedSocietyId:t}=V();return W({mutationFn:s=>Gt.bulkSendFacultyWelcomeEmail(s,t||void 0)})}const jd={getStatus:async t=>(await F.get("/demo/status",{params:t?{society_id:t}:{}})).data,seed:async t=>(await F.post("/demo/seed",null,{params:t?{society_id:t}:{}})).data,clear:async t=>(await F.post("/demo/clear",null,{params:t?{society_id:t}:{}})).data};function Fx(){const{selectedSocietyId:t}=V();return re({queryKey:["setup-status",t],queryFn:()=>Ks.getSetupStatus(t),enabled:!!t,refetchOnMount:"always"})}function eo(){const{selectedSocietyId:t}=V();return re({queryKey:["dashboard",t],queryFn:()=>Ns.dashboard(t||void 0),enabled:!!t})}function Ao(t){const{selectedSocietyId:s}=V();return re({queryKey:["expiring-members",s,t],queryFn:()=>Ns.expiring(s||void 0,t),enabled:!!s})}function Rx(){const{selectedSocietyId:t}=V();return re({queryKey:["renewal-progress",t],queryFn:()=>Ns.renewalProgress(t||void 0),enabled:!!t})}function Cv(){const{selectedSocietyId:t}=V();return re({queryKey:["revenue-pacing",t],queryFn:()=>Ns.revenuePacing(t||void 0),enabled:!!t})}function ul(t){const{selectedSocietyId:s}=V();
1return re({queryKey:["lapsed-recovery",s,t],queryFn:()=>Ns.lapsedRecovery(s||void 0,t),enabled:!!s})}function Pv(){const{selectedSocietyId:t}=V();return re({queryKey:["at-risk-members",t],queryFn:()=>Ns.atRisk(t||void 0),enabled:!!t})}function Mx(){const{selectedSocietyId:t}=V();return re({queryKey:["demo-status",t],queryFn:()=>jd.getStatus(t||void 0),enabled:!!t})}function Av(){const t=J(),{selectedSocietyId:s}=V();return W({mutationFn:()=>jd.seed(s||void 0),onSuccess:()=>{t.invalidateQueries()},onError:()=>{t.invalidateQueries({queryKey:["demo-status"]})}})}function Dx(){const t=J(),{selectedSocietyId:s}=V();return W({mutationFn:()=>jd.clear(s||void 0),onSuccess:()=>{t.invalidateQueries()}})}function Ev(){const{selectedSocietyId:t}=V();return re({queryKey:["mtd-renewals",t],queryFn:()=>Ns.mtdRenewals(t||void 0),enabled:!!t})}function Tv(){const{selectedSocietyId:t}=V();return re({queryKey:["failed-auto-renewals",t],queryFn:()=>Ns.failedAutoRenewals(t||void 0),enabled:!!t})}function Fv(){const{selectedSocietyId:t}=V();return re({queryKey:["pending-actions",t],queryFn:()=>Ns.pendingActions(t||void 0),enabled:!!t})}function Rv(){const{selectedSocietyId:t}=V();return re({queryKey:["email-health",t],queryFn:()=>Ns.emailHealth(t||void 0),enabled:!!t})}function Mv(){const{selectedSocietyId:t}=V();return re({queryKey:["renewal-funnel",t],queryFn:()=>Ns.renewalFunnel(t||void 0),enabled:!!t})}function Dv(){const{selectedSocietyId:t}=V();return re({queryKey:["event-fill-rates",t],queryFn:()=>Ns.eventFillRates(t||void 0),enabled:!!t})}function Lv(){const{selectedSocietyId:t}=V();return re({queryKey:["membership-type-trends",t],queryFn:()=>Ns.membershipTypeTrends(t||void 0),enabled:!!t})}function $v(){const{selectedSocietyId:t}=V(),s=J();return W({mutationFn:a=>ks.updateSocietySettings({dashboard_widgets:a},t||void 0),onSuccess:()=>{s.invalidateQueries({queryKey:["society"]})}})}function qr(){const{user:t}=V();return re({queryKey:["societies"],queryFn:()=>Ks.listAll(),enabled:t?.role==="super_admin"})}function Ir(t){return re({queryKey:["society",t],queryFn:()=>Ks.get(t),enabled:!!t})}function Qs(){const{selectedSocietyId:t}=V();return Ir(t||void 0)}function oa(t,s){const{selectedSocietyId:a}=V();return re({queryKey:["membership-types",a,t,s],queryFn:()=>Zn.list(a||void 0,t,s),enabled:!!a})}function qv(){const t=J(),{selectedSocietyId:s}=V();return W({mutationFn:a=>{if(!s)throw new Error("No society selected");return Zn.create(s,a)},onSuccess:()=>{t.invalidateQueries({queryKey:["membership-types"]})}})}function Iv(){const t=J();return W({mutationFn:({id:s,data:a})=>Zn.update(s,a),onSuccess:()=>{t.invalidateQueries({queryKey:["membership-types"]})}})}function Ov(){const t=J();return W({mutationFn:s=>Zn.delete(s),onSuccess:()=>{t.invalidateQueries({queryKey:["membership-types"]})}})}function Uv(){const t=J();return W({mutationFn:s=>Zn.reorder(s),onSuccess:()=>{t.invalidateQueries({queryKey:["membership-types"]})}})}function er(){const{selectedSocietyId:t}=V();return re({queryKey:["customFields",t],queryFn:()=>Lr.list(t),enabled:!!t})}function zv(){const{user:t}=V();return re({queryKey:["platform","dashboard"],queryFn:()=>bi.getDashboard(),enabled:t?.role==="super_admin",staleTime:3e4})}const ki={getStatus:async t=>(await F.get(`/societies/${t}/memberclicks/status`)).data,configure:async(t,s)=>(await F.post(`/societies/${t}/memberclicks/configure`,s)).data,test:async t=>(await F.post(`/societies/${t}/memberclicks/test`)).data,disconnect:async t=>(await F.post(`/societies/${t}/memberclicks/disconnect`)).data},ba={getTypes:async t=>(await F.get("/memberclicks/types",{params:t?{society_id:t}:void 0})).data,getStatuses:async t=>(await F.get("/memberclicks/statuses",{params:t?{society_id:t}:void 0})).data,getTypeMappings:async t=>(await F.get("/memberclicks/type-mappings",{params:t?{society_id:t}:void 0})).data,saveTypeMappings:async(t,s)=>(await F.put("/memberclicks/type-mappings",t,{params:s?{society_id:s}:void 0})).data,getStatusMappings:async t=>(await F.get("/memberclicks/status-mappings",{params:t?{society_id:t}:void 0})).data,saveStatusMappings:async(t,s)=>(await F.put("/memberclicks/status-mappings",t,{params:s?{society_id:s}:void 0})).data,getFieldPreview:async t=>(await F.get("/memberclicks/field-preview",{params:t?{society_id:t}:void 0})).data,saveFieldMappings:async(t,s)=>{await F.put("/memberclicks/field-mappings",t,{params:s?{society_id:s}:void 0})},preview:async t=>(await F.post("/memberclicks/preview",null,{params:t?{society_id:t}:void 0})).data,executeImport:async t=>(await F.post("/memberclicks/import",null,{params:t?{society_id:t}:void 0})).data,sync:async t=>(await F.post("/memberclicks/sync",null,{params:t?{society_id:t}:void 0})).data,getSyncLogs:async(t,s=20)=>(await F.get("/memberclicks/sync-logs",{params:{...t?{society_id:t}:{},limit:s}}
1)).data};function Bv(){const t=J();return W({mutationFn:s=>Ks.create(s),meta:{suppressErrorToast:!0},onSuccess:()=>vd(t)})}function Kv(t){return re({queryKey:["society-deletion-impact",t],queryFn:()=>Ks.getDeletionImpact(t),enabled:t!==null,staleTime:0,retry:(s,a)=>!wi(a)&&s<1})}function vd(t){t.invalidateQueries({queryKey:["societies"]}),t.invalidateQueries({queryKey:["platform","dashboard"]})}function Qv(){const t=J();return W({mutationFn:s=>Ks.delete(s),meta:{suppressErrorToast:!0},onSettled:(s,a,n)=>{a&&wi(a)&&on(a)!==404||(vd(t),t.invalidateQueries({queryKey:["society",n]}))}})}function Wv(){const t=J();return W({mutationFn:({societyId:s,file:a})=>Ks.uploadLogo(s,a),onSuccess:(s,{societyId:a})=>{t.invalidateQueries({queryKey:["societies"]}),t.invalidateQueries({queryKey:["society",a]}),t.invalidateQueries({queryKey:["setup-status"]})}})}function Vv(){const t=J();return W({mutationFn:s=>Ks.deleteLogo(s),onSuccess:(s,a)=>{t.invalidateQueries({queryKey:["societies"]}),t.invalidateQueries({queryKey:["society",a]}),t.invalidateQueries({queryKey:["setup-status"]})}})}function Gv(){const t=J();return W({mutationFn:({societyId:s,file:a})=>Ks.uploadFavicon(s,a),onSuccess:(s,{societyId:a})=>{t.invalidateQueries({queryKey:["societies"]}),t.invalidateQueries({queryKey:["society",a]})}})}function Yv(){const t=J();return W({mutationFn:s=>Ks.deleteFavicon(s),onSuccess:(s,a)=>{t.invalidateQueries({queryKey:["societies"]}),t.invalidateQueries({queryKey:["society",a]})}})}function to(t){return re({queryKey:["stripe-status",t],queryFn:()=>yi.getStatus(t),enabled:!!t})}function Lx(){const t=J();return W({mutationFn:({societyId:s,data:a})=>yi.configure(s,a),onSuccess:(s,{societyId:a})=>{t.invalidateQueries({queryKey:["stripe-status",a]})}})}function $x(){const t=J();return W({mutationFn:s=>yi.test(s),onSuccess:(s,a)=>{t.invalidateQueries({queryKey:["stripe-status",a]})}})}function Hv(){const t=J();return W({mutationFn:({societyId:s,mode:a})=>yi.toggleMode(s,a),onSuccess:(s,{societyId:a})=>{t.invalidateQueries({queryKey:["stripe-status",a]})}})}function Jv(){const t=J();return W({mutationFn:s=>yi.disconnect(s),onSuccess:(s,a)=>{t.invalidateQueries({queryKey:["stripe-status",a]})}})}function tr(t){return re({queryKey:["mailchimp-status",t],queryFn:()=>Jn.getStatus(t),enabled:!!t})}function qx(){const t=J();return W({mutationFn:({societyId:s,data:a})=>Jn.configure(s,a),onSuccess:(s,{societyId:a})=>{t.invalidateQueries({queryKey:["mailchimp-status",a]})}})}function Ix(){const t=J();return W({mutationFn:s=>Jn.test(s),onSuccess:(s,a)=>{t.invalidateQueries({queryKey:["mailchimp-status",a]})}})}function Ox(){const t=J();return W({mutationFn:({societyId:s,listId:a})=>Jn.selectList(s,a),onSuccess:(s,{societyId:a})=>{t.invalidateQueries({queryKey:["mailchimp-status",a]})}})}function Zv(){const t=J();return W({mutationFn:s=>Jn.disconnect(s),onSuccess:(s,a)=>{t.invalidateQueries({queryKey:["mailchimp-status",a]})}})}function sr(t){return re({queryKey:["mailerlite-status",t],queryFn:()=>Mr.getStatus(t),enabled:!!t})}function Ux(){const t=J();return W({mutationFn:({societyId:s,data:a})=>Mr.configure(s,a),onSuccess:(s,{societyId:a})=>{t.invalidateQueries({queryKey:["mailerlite-status",a]})}})}function zx(){const t=J();return W({mutationFn:s=>Mr.test(s),onSuccess:(s,a)=>{t.invalidateQueries({queryKey:["mailerlite-status",a]})}})}function Bx(){const t=J();return W({mutationFn:({societyId:s,groupId:a})=>Mr.selectGroup(s,a),onSuccess:(s,{societyId:a})=>{t.invalidateQueries({queryKey:["mailerlite-status",a]})}})}function Xv(){const t=J();return W({mutationFn:s=>Mr.disconnect(s),onSuccess:(s,a)=>{t.invalidateQueries({queryKey:["mailerlite-status",a]})}})}function e0(){return W({mutationFn:({societyId:t,listId:s})=>Jn.sync(t,s)})}function t0(){return W({mutationFn:({societyId:t,groupId:s})=>Mr.sync(t,s)})}function s0(){return W({mutationFn:t=>Jn.syncSuppressions(t)})}function Kx(t){return re({queryKey:["event-app-status",t],queryFn:()=>Dr.getStatus(t),enabled:!!t})}function a0(){const t=J();return W({mutationFn:s=>Dr.disconnect(s),onSuccess:(s,a)=>{t.invalidateQueries({queryKey:["event-app-status",a]})}})}function n0(){const t=J();return W({mutationFn:({societyId:s,data:a})=>Dr.configure(s,a),onSuccess:(s,{societyId:a})=>{t.invalidateQueries({queryKey:["event-app-status",a]})}})}function Or(t){return re({queryKey:["email-status",t],queryFn:()=>Hl.getStatus(t),enabled:!!t})}function r0(){const t=J();return W({mutationFn:({societyId:s,data:a})=>Hl.configure(s,a),onSuccess:(s,{societyId:a})=>{t.invalidateQueries({queryKey:["email-status",a]})}})}function Qx(){const t=J();return W({mutationFn:s=>Hl.test(s),onSuccess:(s,a)=>{t.invalidateQueries({queryKey:["email-status",a]})}})}function i0(){const t=J();return W({mutationFn:s=>Hl.disconnect(s),onSuccess:(s,a)=>{t.invalidateQueries({queryKey:["email-status",a]})}})}function l0(t){return re({queryKey:["mc-status",t],queryFn:()=>ki.getStatus(t),enabled:!!t})}function o0(){const t=J();return W({mutationFn:({societyId:s,data:a})=>ki.configure(s,a),onSuccess:(s,{societyId:a})=>{t.invalidateQueries({queryKey:["mc-status",a]})}})}function c0(){const t=J();return W({mutationFn:s=>ki.test(s),onSuccess:(s,a)=>{t.invalidateQueries({queryKey:["mc-status",a]})}})}function d0(){const t=J();return W({mutationFn:s=>ki.disconnect(s),onSuccess:(s,a)=>{t.invalidateQueries({queryKey:["mc-status",a]})}})}function Wx(t){return re({queryKey:["video-library-status",t],queryFn:()=>xd.getStatus(t),enabled:!!t})}function m0(){const t=J();return W({mutationFn:({societyId:s,data:a})=>xd.configure(s,a),onSuccess:(s,{societyId:a})=>{t.invalidateQueries({queryKey:["video-library-status",a]})}})}function u0(){const t=J();return W({mutationFn:s=>xd.disconnect(s),onSuccess:(s,a)=>{t.invalidateQueries({queryKey:["video-library-status",a]})}})}function h0(t){return re({queryKey:["domain-status",t],queryFn:()=>gd.getStatus(t),enabled:!!t,refetchOnWindowFocus:!1,staleTime:1/0})}function p0(){const t=J();return W({mutationFn:({societyId:s,data:a})=>gd.configure(s,a),onSuccess:(s,{societyId:a})=>{t.invalidateQueries({queryKey:["domain-status",a]}),t.invalidateQueries({queryKey:["societies"]}),t.invalidateQueries({queryKey:["society",a]})}})}function x0(){const t=J();return W({mutationFn:s=>gd.remove(s),onSuccess:(s,a)=>{t.invalidateQueries({queryKey:["domain-status",a]}),t.invalidateQueries({queryKey:["societies"]}),t.invalidateQueries({queryKey:["society",a]})}})}function Vx(t){const s=J();return W({mutationFn:a=>Lr.create(t,a),onSuccess:()=>{s.invalidateQueries({queryKey:["customFields",t]})}})}function g0(t){const s=J();return W({mutationFn:({id:a,data:n})=>Lr.update(a,n),onSuccess:()=>{s.invalidateQueries({queryKey:["customFields",t]})}})}function f0(t){const s=J();return W({mutationFn:({id:a,force:n})=>Lr.delete(a,n),onSuccess:()=>{s.invalidateQueries({queryKey:["customFields",t]})}})}function y0(t){const s=J();return W({mutationFn:a=>Lr.reorder(t,a),onSuccess:()=>{s.invalidateQueries({queryKey:["customFields",t]})}})}function b0(t={}){const{selectedSocietyId:s}=V();return re({queryKey:["payments",s,t],queryFn:()=>Ba.list({society_id:s||void 0,status:t.status,payment_type:t.paymentType,date_from:t.dateFrom,date_to:t.dateTo,needs_review:t.needsReview?!0:void 0,page:t.page,size:t.size}),enabled:!!s})}function j0(t,s=1){return re({queryKey:["memberPayments",t,s],queryFn:()=>Ba.listByMember(t,s),enabled:!!t})}function v0(){return W({mutationFn:t=>Ba.createPaymentIntent(t)})}function w0(){const t=J();return W({mutationFn:({paymentId:s,toEmail:a})=>Ba.sendReceipt(s,a),onSuccess:()=>{t.invalidateQueries({queryKey:["memberInvoices"]})}})}function N0(){const t=J(),{selectedSocietyId:s}=V();return W({mutationFn:a=>Ba.refund(a,s||void 0),onSuccess:()=>{t.invalidateQueries({queryKey:["payments"]}),t.invalidateQueries({queryKey:["dashboard"]}),t.invalidateQueries({queryKey:["revenue-stats"]}),t.invalidateQueries({queryKey:["memberPayments"]})}})}function k0(){const t=J(),{selectedSocietyId:s}=V();return W({mutationFn:({orderId:a,reason:n})=>Ba.markOrderRefunded(a,{reason:n},s||void 0),onSuccess:()=>{t.invalidateQueries({queryKey:["payments"]}),t.invalidateQueries({queryKey:["dashboard"]}),t.invalidateQueries({queryKey:["revenue-stats"]}),t.invalidateQueries({queryKey:["memberPayments"]}),t.invalidateQueries({queryKey:["events"]}),t.invalidateQueries({queryKey:["members"]}),t.invalidateQueries({queryKey:["eventRegistrations"]})}})}function _0(){const t=J();return W({mutationFn:s=>Ba.createManual(s),onSuccess:(s,a)=>{t.invalidateQueries({queryKey:["payments"]}),t.invalidateQueries({queryKey:["memberPayments",a.member_id]}),t.invalidateQueries({queryKey:["memberPaymentSummary",a.member_id]}),t.invalidateQueries({queryKey:["memberAudit",a.member_id]}),t.invalidateQueries({queryKey:["member",a.member_id]}),t.invalidateQueries({queryKey:["dashboard"]}),t.invalidateQueries({queryKey:["revenue-stats"]})}})}function S0(){const t=J(),{selectedSocietyId:s}=V();return W({mutationFn:({paymentId:a,...n})=>Ba.settlementReview(a,n,s||void 0),onSuccess:()=>{t.invalidateQueries({queryKey:["payments"]}),t.invalidateQueries({queryKey:["memberPayments"]}),t.invalidateQueries({queryKey:["dashboard"]}),t.invalidateQueries({queryKey:["revenue-stats"]})}})}function C0(t,s){const{selectedSocietyId:a}=V();return re({queryKey:["report-revenue",a,t,s],queryFn:()=>Ns.revenue(a||void 0,t,s),enabled:!!a})}function P0(){const{selectedSocietyId:t}=V();return re({queryKey:["report-membership",t],queryFn:()=>Ns.membership(t||void 0),enabled:!!t})}function A0(){const{selectedSocietyId:t}=V();return re({queryKey:["report-retention",t],queryFn:()=>Ns.retention(t||void 0),enabled:!!t})}function E0(){const{selectedSocietyId:t}=V();return re({queryKey:["membership-matrix",t],queryFn:()=>Ns.membershipMatrix(t||void 0),enabled:!!t})}function T0(t){const{selectedSocietyId:s}=V();return re({queryKey:["report-expiring",s,t],queryFn:()=>Ns.expiring(s||void 0,t),enabled:!!s})}function Gx(){const{selectedSocietyId:t}=V();return re({queryKey:["member-growth-pacing",t],queryFn:()=>Ns.memberGrowthPacing(t||void 0),enabled:!!t})}function Yx(){const{selectedSocietyId:t}=V();return re({queryKey:["ar-aging",t],queryFn:()=>Ns.arAging(t||void 0),enabled:!!t})}function F0(t={}){const{selectedSocietyId:s}=V();return re({queryKey:["users",s,t],queryFn:()=>Pa.list({society_id:s||void 0,page:t.page,size:t.size,role:t.role,query:t.search}),placeholderData:sa})}function Hx(){const t=J();return W({meta:{suppressErrorToast:!0},mutationFn:s=>Pa.invite(s),onSuccess:s=>{wc(s,"invite"),t.invalidateQueries({queryKey:["users"]})}})}function wc(t,s){const a=t.user.email;if(t.delivery==="failed"){Ut.error(`${s==="invite"?"The invitation was created":"The reset link was created"}, but the email to ${a} couldnât be sent${t.delivery_error?` (${t.delivery_error})`:""}. Check the address and send it again.`);return}Ut.success(s==="invite"?`Invitation sent to ${a}`:`Reset link sent to ${a}`)}function R0(){const t=J(),s=()=>
1t.invalidateQueries({queryKey:["users"]}),a=W({mutationFn:i=>Pa.resendInvitation(i),onSuccess:i=>wc(i,"invite"),onSettled:s}),n=W({mutationFn:i=>Pa.revokeInvitation(i),onSuccess:i=>Ut.success(`Invitation for ${i.email} revoked`),onSettled:s}),r=W({mutationFn:i=>Pa.sendResetLink(i),onSuccess:i=>wc(i,"reset"),onSettled:s});return{resend:a,revoke:n,reset:r}}function M0(){const t=J();return W({meta:{suppressErrorToast:!0},mutationFn:({id:s,data:a})=>Pa.update(s,a),onSuccess:()=>{t.invalidateQueries({queryKey:["users"]})}})}function Jx(t={}){const{selectedSocietyId:s}=V();return re({queryKey:["emailTemplates",s,t],queryFn:()=>ks.list({society_id:s||void 0,template_type:t.templateType})})}function D0(t){return re({queryKey:["emailTemplate",t],queryFn:()=>ks.get(t),enabled:!!t})}function L0(t){return re({queryKey:["emailVariables",t],queryFn:()=>ks.getVariables(t),enabled:!!t})}function $0(){const t=J(),{selectedSocietyId:s}=V();return W({mutationFn:a=>ks.create(a,s||void 0),onSuccess:()=>{t.invalidateQueries({queryKey:["emailTemplates"]})}})}function Zx(){const t=J();return W({mutationFn:({id:s,data:a})=>ks.update(s,a),onSuccess:(s,{id:a})=>{t.invalidateQueries({queryKey:["emailTemplates"]}),t.invalidateQueries({queryKey:["emailTemplate",a]})}})}function q0(){const t=J();return W({mutationFn:s=>ks.delete(s),onSuccess:()=>{t.invalidateQueries({queryKey:["emailTemplates"]})}})}function I0(){return W({mutationFn:t=>ks.sendTest(t)})}function O0(t={}){const{selectedSocietyId:s}=V();return re({queryKey:["emailLogs",s,t],queryFn:()=>ks.listLogs({society_id:s||void 0,page:t.page,size:t.size,status:t.status,template_type:t.templateType,date_from:t.dateFrom,date_to:t.dateTo}),placeholderData:sa})}function U0(){const{selectedSocietyId:t}=V();return re({queryKey:["emailsPaused",t],queryFn:()=>ks.getSocietySettings(t||void 0),select:s=>s.emails_paused})}function z0(){const t=J(),{selectedSocietyId:s}=V();return W({mutationFn:a=>ks.updateEmailsPaused(a,s||void 0),onSuccess:()=>{t.invalidateQueries({queryKey:["emailsPaused"]})}})}function B0(){const t=J(),{selectedSocietyId:s}=V();return W({mutationFn:()=>ks.triggerRenewalReminders(s||void 0),onSuccess:()=>{t.invalidateQueries({queryKey:["emailLogs"]})}})}function K0(t={}){const{selectedSocietyId:s}=V();return re({queryKey:["emailSuppressions",s,t],queryFn:()=>ks.listSuppressions({society_id:s||void 0,page:t.page,size:t.size,reason:t.reason,scope:t.scope,email:t.email}),placeholderData:sa})}function Q0(t){const{selectedSocietyId:s}=V();return re({queryKey:["emailSuppressions",s,{email:t}],queryFn:()=>ks.listSuppressions({society_id:s||void 0,email:t,size:1}),enabled:!!t,select:a=>
1a.items[0]||null})}function W0(){const t=J(),{selectedSocietyId:s}=V();return W({mutationFn:a=>ks.removeSuppression(a,s||void 0),onSuccess:()=>{t.invalidateQueries({queryKey:["emailSuppressions"]})}})}function V0(){const t=J(),{selectedSocietyId:s}=V();return W({mutationFn:a=>ks.createSuppression(a,s||void 0),onSuccess:()=>{t.invalidateQueries({queryKey:["emailSuppressions"]})}})}function G0(){const{selectedSocietyId:t}=V();return re({queryKey:["email-stats",t],queryFn:()=>ks.getStats(t||void 0),enabled:!!t})}function Xx(t){const s=J(),a=re({queryKey:["domain-health",t],queryFn:()=>ks.domainHealth(t,!1),enabled:!!t}),n=W({mutationFn:()=>ks.domainHealth(t,!0),onSuccess:r=>{s.setQueryData(["domain-health",t],r)},onError:()=>{Ut.error("Couldn't check domain health. Please try again.")}});return{data:a.data,isLoading:a.isLoading,isError:a.isError,refresh:()=>n.mutate(),isRefreshing:n.isPending}}function Y0(t={}){const{selectedSocietyId:s}=V();return re({queryKey:["auditLogs",s,t],queryFn:()=>ji.list({society_id:s||void 0,page:t.page,size:t.size,action:t.action,resource_type:t.resourceType,date_from:t.dateFrom,date_to:t.dateTo,user_id:t.userId,system_only:t.systemOnly||void 0}),placeholderData:sa})}function H0(){const{selectedSocietyId:t}=V();return re({queryKey:["auditActors",t],queryFn:()=>ji.getActors(t||void 0),enabled:!!t})}function J0(){return re({queryKey:["auditActions"],queryFn:()=>ji.getActions()})}function Z0(){const{selectedSocietyId:t}=V();return re({queryKey:["auditResourceTypes",t],queryFn:()=>ji.getResourceTypes(t||void 0),enabled:!!t})}function X0(t={}){const{selectedSocietyId:s}=V();return re({queryKey:["invoices",s,t],queryFn:()=>Bs.list({society_id:s||void 0,...t}),enabled:!!s})}function eg(t,s=1){return re({queryKey:["memberInvoices",t,s],queryFn:()=>Bs.listByMember(t,s),enabled:!!t})}function ew(){const{selectedSocietyId:t}=V();return W({mutationFn:s=>Bs.previewBatch(s,t||void 0)})}function tw(){const t=J(),{selectedSocietyId:s}=V();return W({mutationFn:a=>Bs.createBatch(a,s||void 0),onSuccess:()=>{t.invalidateQueries({queryKey:["invoices"]}),t.invalidateQueries({queryKey:["invoiceBatches"]})}})}function sw(){const t=J();return W({mutationFn:({id:s,data:a})=>Bs.markPaid(s,a),onSuccess:()=>{t.invalidateQueries({queryKey:["invoices"]}),t.invalidateQueries({queryKey:["memberInvoices"]}),t.invalidateQueries({queryKey:["invoice"]}),t.invalidateQueries({queryKey:["payments"]})}})}function aw(){const t=J();return W({mutationFn:({id:s,data:a})=>Bs.void(s,a),onSuccess:()=>{t.invalidateQueries({queryKey:["invoices"]}),t.invalidateQueries({queryKey:["memberInvoices"]}),t.invalidateQueries({queryKey:["invoice"]})}})}function nw(){const t=J();return W({mutationFn:s=>Bs.sendBatchEmails(s),onSuccess:()=>{t.invalidateQueries({queryKey:["invoices"]}),t.invalidateQueries({queryKey:["invoiceBatches"]})}})}function rw(){const t=J();return W({mutationFn:({id:s,data:a})=>Bs.sendEmail(s,a),onSuccess:()=>{t.invalidateQueries({queryKey:["invoices"]}),t.invalidateQueries({queryKey:["memberInvoices"]}),t.invalidateQueries({queryKey:["invoice"]})}})}function iw(){const{selectedSocietyId:t}=V();return re({queryKey:["outstandingCount",t],queryFn:()=>Bs.getOutstandingCount(t||void 0),enabled:!!t})}function lw(){const t=J(),{selectedSocietyId:s}=V();return W({mutationFn:a=>Bs.sendReminders(s||void 0,a||void 0),onSuccess:()=>{t.invalidateQueries({queryKey:["invoices"]}),t.invalidateQueries({queryKey:["outstandingCount"]})}})}function ow(){const{selectedSocietyId:t}=V();return W({mutationFn:({file:s,updateExisting:a,allowBlankEmail:n})=>$a.previewImport(s,a,t,n)})}function cw(){const{selectedSocietyId:t}=V(),s=J();return W({mutationFn:({file:a,options:n})=>$a.executeImport(a,n,t),onSuccess:()=>{s.invalidateQueries({queryKey:["members"]})}})}function dw(){const{selectedSocietyId:t}=V();return W({mutationFn:s=>$a.exportMembers(s,t)})}function mw(){const{selectedSocietyId:t}=V();return W({mutationFn:s=>$a.exportPayments(s,t)})}function tg(){const{selectedSocietyId:t}=V();return re({queryKey:["renewalSequenceSteps",t],queryFn:()=>Sn.listSteps(t||void 0)})}function uw(){const t=J(),{selectedSocietyId:s}=V();return W({mutationFn:a=>Sn.createStep(a,s||void 0),onSuccess:()=>{t.invalidateQueries({queryKey:["renewalSequenceSteps"]})}})}function hw(){const t=J(),{selectedSocietyId:s}=V();return W({mutationFn:({id:a,data:n})=>Sn.updateStep(a,n,s||void 0),onSuccess:()=>{t.invalidateQueries({queryKey:["renewalSequenceSteps"]})}})}function pw(){const t=J(),{selectedSocietyId:s}=V();return W({mutationFn:a=>Sn.deleteStep(a,s||void 0),onSuccess:()=>{t.invalidateQueries({queryKey:["renewalSequenceSteps"]})}})}function xw(){const t=J(),{selectedSocietyId:s}=V();return W({mutationFn:()=>Sn.applyDefaults(s||void 0),onSuccess:()=>{t.invalidateQueries({queryKey:["renewalSequenceSteps"]}),t.invalidateQueries({queryKey:["emailTemplates"]})}})}function gw(){const t=J(),{selectedSocietyId:s}=V();return W({mutationFn:a=>Sn.restoreDefaults(a,s||void 0),onSuccess:()=>{t.invalidateQueries({queryKey:["renewalSequenceSteps"]}),t.invalidateQueries({queryKey:["emailTemplates"]})}})}function fw(t={}){const{selectedSocietyId:s}=V();return re({queryKey:["renewalNotificationLog",s,t],queryFn:()=>
1t.memberId?Sn.getMemberLog(t.memberId,{society_id:s||void 0,page:t.page,size:t.size}):Sn.getLog({society_id:s||void 0,page:t.page,size:t.size}),placeholderData:sa})}function sg(t,s){const a=s.trim().toLowerCase();return a?t.name.toLowerCase().includes(a)||t.slug.toLowerCase().includes(a):!0}const _r=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function yw(t){return _r.test(t)||/^\d+$/.test(t)}function bw(t,s){if(t.split("/").some(yw))return"/dashboard";const a=new URLSearchParams(s).get("tab");return a?`${t}?tab=${encodeURIComponent(a)}`:t}function ym(t,s,a,n){const r=[...t?.querySelectorAll("button[data-society]")??[]];if(r.length===0)return;if(a==="first")return r[0].focus();const i=r.indexOf(s);if(a===-1&&i<=0)return n?.focus();r[Math.min(i+a,r.length-1)]?.focus()}function ag(){const{user:t,selectedSocietyId:s,setSelectedSocietyId:a}=V(),{data:n,isError:r,isLoading:i,refetch:l,isFetching:m,fetchStatus:c}=qr(),d=o.useRef(null),u=o.useRef(null),{data:h}=Qs(),[p,x]=o.useState(!1),[f,b]=o.useState(""),N=kt(),{pathname:j,search:w}=ta(),v=o.useId(),k=o.useMemo(()=>(n??[]).filter(_=>sg(_,f)),[n,f]);if(t?.role!=="super_admin")return e.jsx("div",{className:"truncate rounded-md bg-muted px-3 py-2 text-sm font-medium text-foreground",children:h?.name||"Loading..."});const S=_=>{if(x(!1),b(""),_===s)return;a(_);const y=bw(j,w);N(y,{replace:y===`${j}${w}`||y===j})};return e.jsxs(kl,{modal:!0,open:p,onOpenChange:_=>{x(_),_||b("")},children:[e.jsx(_l,{asChild:!0,children:e.jsxs(g,{variant:"outline",className:"w-full justify-between","data-tour":"society-switcher","aria-label":`Switch society (current: ${h?.name??"none"})`,children:[e.jsx("span",{className:"truncate",children:h?.name||"Select societyâ¦"}),e.jsx(Cb,{className:"ml-2 h-4 w-4 shrink-0 opacity-50","aria-hidden":"true"})]})}),e.jsxs(hi,{className:"w-72 p-2",align:"start",children:[e.jsxs("div",{className:"relative",children:[e.jsx(ya,{className:"absolute left-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground","aria-hidden":"true"}),e.jsx(O,{ref:u,autoFocus:!0,value:f,onChange:_=>b(_.target.value),placeholder:"Search by name or slugâ¦","aria-label":"Search societies","aria-controls":v,className:"h-9 pl-8",onKeyDown:_=>{_.key==="Enter"&&k.length===1&&S(k[0].id),_.key==="ArrowDown"&&(_.preventDefault(),ym(d.current,null,"first",u.current))}})]}),e.jsx("div",{className:"mt-2 max-h-72 overflow-y-auto",id:v,ref:d,onKeyDown:_=>{(_.key==="ArrowDown"||_.key==="ArrowUp")&&(_.preventDefault(),ym(d.current,document.activeElement,_.key==="ArrowDown"?1:-1,u.current))},children:i?e.jsx("p",{className:"px-2 py-3 text-sm text-muted-foreground",children:"Loading societiesâ¦"}):c==="paused"&&!n?e.jsx("p",{className:"px-2 py-3 text-sm text-muted-foreground",children:"Societies canât be loaded while youâre offline."}):r&&!n?e.jsxs("div",{className:"px-2 py-3 text-sm",children:[e.jsx("p",{className:"text-destructive",children:"Societies couldnât be loaded."}),e.jsx(g,{type:"button",variant:"outline",size:"sm",className:"mt-2",onClick:()=>{l()},disabled:m,children:m?"Trying againâ¦":"Try again"})]}):k.length===0?e.jsx("p",{className:"px-2 py-3 text-sm text-muted-foreground",children:f.trim()?"No society matches.":"No societies."}):e.jsx("ul",{className:"space-y-0.5",children:k.map(_=>{const y=_.id===s;return e.jsx("li",{children:e.jsxs("button",{type:"button","data-society":!0,onClick:()=>S(_.id),"aria-current":y?"true":void 0,className:me("flex min-h-9 w-full items-center gap-2 rounded-sm px-2 py-1.5 text-left text-sm hover:bg-accent focus-visible:bg-accent focus-visible:outline-none",y&&"bg-accent"),children:[e.jsx(Xt,{className:me("h-4 w-4 shrink-0",y?"opacity-100":"opacity-0"),"aria-hidden":"true"}),e.jsx("span",{className:"min-w-0 flex-1 truncate",children:_.name}),e.jsx("span",{className:"shrink-0 text-xs text-muted-foreground",children:_.slug})]})},_.id)})})}),n&&e.jsx("p",{role:"status",className:"mt-2 px-2 text-xs text-muted-foreground",children:f.trim()?`${k.length} of ${n.length}`:`${n.length} ${n.length===1?"society":"societies"}`})]})]})}function ng(){const t=kt();return o.useCallback(()=>
1{t("/platform",{state:{exitWorkspace:!0}})},[t])}function rg({onNavigate:t}){const{user:s}=V(),a=ng();return s?.role!=="super_admin"?null:e.jsxs("button",{type:"button",onClick:()=>{t?.(),a()},className:"flex min-h-11 w-full items-center gap-2 rounded-md px-2 text-sm font-medium text-muted-foreground transition-colors hover:bg-accent hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring lg:min-h-9",children:[e.jsx(es,{className:"h-4 w-4 shrink-0","aria-hidden":"true"}),"Back to platform"]})}function ig(){const{selectedSocietyId:t}=V();return async()=>{const a=window.open("about:blank","_blank");try{const{data:n}=await F.get("/video-library-sso-token",{params:t?{society_id:t}:void 0}),r=`${n.base_url.replace(/\/$/,"")}/api/auth/verify-member?token=${encodeURIComponent(n.token)}&redirect=/video-library/admin`;a?a.location.href=r:window.open(r,"_blank")}catch{a&&a.close(),alert("Could not open Video Library. Please check that it is configured.")}}}const pn="/assets/korevera-wordmark-JljHL-9h.png",jw={Members:"nav-members"};function lg({item:t}){const s=jw[t.name];return e.jsxs(_a,{to:t.href,end:t.href==="/",className:({isActive:a})=>me("group flex items-center gap-x-3 rounded-md px-2 py-2 text-sm font-medium leading-6 transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",a?"bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300":"text-foreground/80 hover:bg-accent hover:text-foreground"),...s?{"data-tour":s}:{},children:[e.jsx(t.icon,{className:"h-5 w-5 shrink-0","aria-hidden":"true"}),t.name]})}function vw({group:t,defaultOpen:s=!1}){const[a,n]=o.useState(s);return e.jsxs("div",{children:[e.jsxs("button",{type:"button",onClick:()=>n(!a),"aria-expanded":a,"data-tour":`nav-group-${t.label.toLowerCase()}`,className:"flex w-full items-center justify-between rounded-md px-2 py-1.5 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[t.label,e.jsx(ps,{className:me("h-3.5 w-3.5 transition-transform",a&&"rotate-180"),"aria-hidden":"true"})]}),a&&e.jsx("ul",{className:"mt-1 space-y-0.5",children:t.items.map(r=>e.jsx("li",{children:e.jsx(lg,{item:r})},r.name))})]})}function ww(){const{data:t}=Qs(),{user:s}=V(),a=s?.role==="super_admin"||s?.role==="society_admin",n=Sx(_x,t?.settings,{isAdmin:a}),r=t?.settings?.video_library_enabled===!0,i=ig();return e.jsx("div",{className:"hidden lg:fixed lg:inset-y-0 lg:z-50 lg:flex lg:w-64 lg:flex-col",children:e.jsxs("div",{className:"relative flex grow flex-col gap-y-4 overflow-y-auto border-r border-border bg-sidebar px-5 pb-4",children:[e.jsx("div",{"aria-hidden":!0,className:"pointer-events-none absolute -top-20 right-0 h-40 w-40 rounded-full bg-brand-navy/[0.04] blur-3xl dark:bg-brand-navy/15"}),e.jsx("div",{className:"relative flex h-16 shrink-0 items-center justify-center",children:e.jsx("img",{src:pn,alt:"Korevera",className:"h-7 object-contain dark:invert"})}),e.jsxs("div",{className:"relative space-y-1",children:[e.jsx(rg,{}),e.jsx(ag,{})]}),e.jsxs("nav",{"aria-label":"Society",className:"relative flex flex-1 flex-col","data-tour":"sidebar-nav","data-desktop-nav":!0,children:[e.jsx("ul",{className:"space-y-0.5",children:kx.map(l=>e.jsx("li",{children:e.jsx(lg,{item:l})},l.name))}),e.jsx("div",{className:"mt-4 space-y-2",children:n.map(l=>e.jsx(vw,{group:l,defaultOpen:l.label==="Members"||l.label==="Finance"},l.label))}),r&&e.jsx("div",{className:"mt-4",children:e.jsxs("button",{onClick:i,className:"group flex w-full items-center gap-x-3 rounded-md px-2 py-2 text-sm font-medium leading-6 text-foreground/80 transition-colors hover:bg-accent hover:text-foreground",children:[e.jsx(Qc,{className:"h-5 w-5 shrink-0","aria-hidden":"true"}),"Video library",e.jsx(Rs,{className:"ml-auto h-3.5 w-3.5 shrink-0 self-center text-muted-foreground","aria-hidden":"true"})]})})]})]})})}const Nw="(min-width: 1024px)";function og(t,s,a=Nw){const n=ta(),r=Oy(),i=o.useRef(n.key);o.useEffect(()=>{i.current!==n.key&&(i.current=n.key,r!=="REPLACE"&&s())},[n.key,r,s]),o.useEffect(()=>{if(!t||typeof window.matchMedia!="function")return;const l=window.matchMedia(a),m=()=>{l.matches&&s()};return l.addEventListener?(l.addEventListener("change",m),()=>l.removeEventListener("change",m)):(l.addListener(m),()=>l.removeListener(m))},[t,s,a])}function cg(t,s){if(!s||getComputedStyle(s).display!=="none")return;const a=document.querySelector('[data-desktop-nav] a[aria-current="page"]')??document.querySelector("[data-desktop-nav] a");a&&(t.preventDefault(),a.focus())}const Ws=mb,Vs=ub,kw=o.forwardRef(({className:t,inset:s,children:a,...n},r)=>e.jsxs(Bh,{ref:r,className:me("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent",s&&"pl-8",t),...n,children:[a,e.jsx(ts,{className:"ml-auto h-4 w-4"})]}));kw.displayName=Bh.displayName;const _w=o.forwardRef(({className:t,...s},a)=>e.jsx(Kh,{ref:a,className:me("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:sli
1de-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",t),...s}));_w.displayName=Kh.displayName;const $s=o.forwardRef(({className:t,sideOffset:s=4,...a},n)=>e.jsx(db,{children:e.jsx(Qh,{ref:n,sideOffset:s,className:me("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",t),...a})}));$s.displayName=Qh.displayName;const wt=o.forwardRef(({className:t,inset:s,...a},n)=>e.jsx(Wh,{ref:n,className:me("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",s&&"pl-8",t),...a}));wt.displayName=Wh.displayName;const dg=o.forwardRef(({className:t,children:s,checked:a,...n},r)=>e.jsxs(Vh,{ref:r,className:me("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),checked:a,...n,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(Gh,{children:e.jsx(Xt,{className:"h-4 w-4"})})}),s]}));dg.displayName=Vh.displayName;const Sw=o.forwardRef(({className:t,children:s,...a},n)=>e.jsxs(Yh,{ref:n,className:me("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),...a,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(Gh,{children:e.jsx(Bl,{className:"h-2 w-2 fill-current"})})}),s]}));Sw.displayName=Yh.displayName;const so=o.forwardRef(({className:t,inset:s,...a},n)=>e.jsx(Hh,{ref:n,className:me("px-2 py-1.5 text-sm font-semibold",s&&"pl-8",t),...a}));so.displayName=Hh.displayName;const Aa=o.forwardRef(({className:t,...s},a)=>e.jsx(Jh,{ref:a,className:me("-mx-1 my-1 h-px bg-muted",t),...s}));Aa.displayName=Jh.displayName;const ao=o.forwardRef(({className:t,...s},a)=>e.jsx(Zh,{ref:a,className:me("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",t),...s}));ao.displayName=Zh.displayName;const Cw=o.forwardRef(({className:t,...s},a)=>e.jsx(Xh,{ref:a,className:me("aspect-square h-full w-full",t),...s}));Cw.displayName=Xh.displayName;const no=o.forwardRef(({className:t,...s},a)=>e.jsx(ep,{ref:a,className:me("flex h-full w-full items-center justify-center rounded-full bg-muted",t),...s}));no.displayName=ep.displayName;const Pw={"":"Dashboard",members:"Members",payments:"Payments",emails:"Emails",reports:"Reports","import-export":"Import/export",settings:"Settings",edit:"Edit"};function Aw(){const s=ta().pathname.split("/").filter(a=>a);return e.jsx("nav",{className:"flex","aria-label":"Breadcrumb",children:e.jsxs("ol",{className:"flex items-center space-x-2",children:[e.jsx("li",{children:e.jsxs(je,{to:"/",className:"text-muted-foreground hover:text-foreground",children:[e.jsx(Pb,{className:"h-4 w-4 flex-shrink-0","aria-hidden":"true"}),e.jsx("span",{className:"sr-only",children:"Home"})]})}),s.map((a,n)=>{if(_r.test(a))return null;const r=`/${s.slice(0,n+1).join("/")}`,i=n===s.length-1||n<s.length-1&&_r.test(s[n+1]),l=Pw[a]||a;return e.jsxs("li",{className:"flex items-center",children:[e.jsx(ts,{className:"h-4 w-4 flex-shrink-0 text-muted-foreground","aria-hidden":"true"}),i?e.jsx("span",{className:"ml-2 text-sm font-medium text-muted-foreground",children:l}):e.jsx(je,{to:r,className:"ml-2 text-sm font-medium text-muted-foreground hover:text-foreground",children:l})]},r)})]})})}function mg({item:t,onClose:s}){return e.jsxs(_a,{to:t.href,end:t.href==="/",onClick:s,className:({isActive:a})=>me("flex min-h-11 items-center gap-x-3 rounded-lg px-3 py-2 text-base font-medium leading-7 transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",a?"bg-brand-navy
1/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300":"text-foreground/80 hover:bg-accent hover:text-foreground"),children:[e.jsx(t.icon,{className:"h-6 w-6 shrink-0","aria-hidden":"true"}),t.name]})}function Ew({group:t,defaultOpen:s=!1,onClose:a}){const[n,r]=o.useState(s);return e.jsxs("div",{children:[e.jsxs("button",{type:"button",onClick:()=>r(!n),"aria-expanded":n,className:"flex min-h-11 w-full items-center justify-between rounded-md px-3 py-1.5 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[t.label,e.jsx(ps,{className:me("h-3.5 w-3.5 transition-transform",n&&"rotate-180"),"aria-hidden":"true"})]}),n&&e.jsx("ul",{className:"mt-1 space-y-0.5",children:t.items.map(i=>e.jsx("li",{children:e.jsx(mg,{item:i,onClose:a})},i.name))})]})}function Tw({open:t,onOpenChange:s,trigger:a}){const n=()=>s(!1),r=o.useRef(null),{data:i}=Qs(),{user:l}=V(),m=l?.role==="super_admin"||l?.role==="society_admin",c=Sx(_x,i?.settings,{isAdmin:m}),d=i?.settings?.video_library_enabled===!0,u=ig();return e.jsxs(Ic,{open:t,onOpenChange:s,children:[e.jsx(tp,{asChild:!0,ref:r,children:a}),e.jsxs(Oc,{children:[e.jsx($l,{className:"fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0"}),e.jsxs(ql,{onCloseAutoFocus:h=>cg(h,r.current),className:"fixed inset-y-0 left-0 z-50 w-full overflow-y-auto bg-sidebar px-6 py-6 text-foreground shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm sm:ring-1 sm:ring-border",children:[e.jsxs(sp,{children:[e.jsx(Il,{children:"Navigation"}),e.jsx(Ol,{children:"Society administration destinations"})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("img",{src:pn,alt:"Korevera",className:"h-7 object-contain dark:invert"}),e.jsx(Uc,{asChild:!0,children:e.jsxs(g,{variant:"ghost",size:"icon",className:"h-11 w-11",children:[e.jsx("span",{className:"sr-only",children:"Close navigation"}),e.jsx(ms,{className:"h-6 w-6","aria-hidden":"true"})]})})]}),e.jsxs("div",{className:"mt-6 flow-root",children:[e.jsx(rg,{onNavigate:n}),e.jsx(ag,{}),e.jsxs("nav",{"aria-label":"Society",className:"mt-6",children:[e.jsx("ul",{className:"space-y-0.5",children:kx.map(h=>e.jsx("li",{children:e.jsx(mg,{item:h,onClose:n})},h.name))}),e.jsx("div",{className:"mt-4 space-y-2",children:c.map(h=>e.jsx(Ew,{group:h,defaultOpen:h.label==="Members"||h.label==="Finance",onClose:n},h.label))}),d&&e.jsx("div",{className:"mt-4",children:e.jsxs("button",{type:"button",onClick:()=>{n(),u()},className:"flex min-h-11 w-full items-center gap-x-3 rounded-lg px-3 py-2 text-base font-medium leading-7 text-foreground/80 transition-colors hover:bg-accent hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[e.jsx(Qc,{className:"h-6 w-6 shrink-0","aria-hidden":"true"}),"Video library",e.jsx(Rs,{className:"ml-auto h-4 w-4 shrink-0 self-center text-muted-foreground","aria-hidden":"true"})]})})]})]})]})]})]})}function ro(t){const s=t?.first_name?.trim()??"",a=t?.last_name?.trim()??"",n=[s,a].filter(Boolean).join(" "),r=(`${s.charAt(0)}${a.charAt(0)}`||(t?.email?.charAt(0)??"")).toUpperCase();return{fullName:n,initials:r}}function ug(){const{toggleTheme:t}=bd();return e.jsxs(g,{variant:"ghost",size:"icon",onClick:t,className:"relative",children:[e.jsx(pc,{className:"h-5 w-5 rotate-0 scale-100 transition-transform dark:-rotate-90 dark:scale-0"}),e.jsx(xc,{className:"absolute h-5 w-5 rotate-90 scale-0 transition-transform dark:rotate-0 dark:scale-100"}),e.jsx("span",{className:"sr-only",children:"Toggle theme"})]})}function Fw(){const t=kt(),{user:s,logout:a,selectedSocietyId:n}=V(),[r,i]=o.useState(!1),l=o.useCallback(()=>i(!1),[]);og(r,l);const[m,c]=o.useState(""),[d,u]=o.useState([]),[h,p]=o.useState(!1),[x,f]=o.useState(!1),b=o.useRef(void 0),N=o.useRef(null);o.useEffect(()=>{if(!m||m.length<2||!n){u([]),p(!1);return}return clearTimeout(b.current),b.current=setTimeout(async()=>{f(!0);try{const S=await Gt.list({query:m,size:8,society_id:n});u(S.items),p(!0)}catch{u([])}finally{f(!1)}},300),()=>clearTimeout(b.current)},[m,n]),o.useEffect(()=>{const S=_=>{N.current&&!N.current.contains(_.target)&&p(!1)};
1return document.addEventListener("mousedown",S),()=>document.removeEventListener("mousedown",S)},[]);const{fullName:j,initials:w}=ro(s),v=s?.role==="super_admin",k=ng();return e.jsx(e.Fragment,{children:e.jsxs("div",{className:"sticky top-0 z-40 flex h-16 shrink-0 items-center gap-x-4 border-b border-border bg-card/80 px-4 backdrop-blur-md sm:gap-x-6 sm:px-6 lg:px-8",children:[e.jsx(Tw,{open:r,onOpenChange:i,trigger:e.jsxs("button",{type:"button",className:"-m-2.5 rounded-md p-2.5 text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring lg:hidden",children:[e.jsx("span",{className:"sr-only",children:"Open navigation"}),e.jsx(Wc,{className:"h-6 w-6","aria-hidden":"true"})]})}),e.jsx("div",{className:"h-6 w-px bg-border lg:hidden","aria-hidden":"true"}),e.jsxs("div",{className:"flex flex-1 gap-x-4 self-stretch lg:gap-x-6",children:[e.jsx("div",{className:"flex flex-1 items-center gap-x-4",children:e.jsx("div",{className:"lg:hidden",children:e.jsx(Aw,{})})}),e.jsxs("div",{className:"flex items-center gap-x-3 lg:gap-x-4",children:[n&&e.jsxs("div",{className:"relative hidden sm:block",ref:N,"data-tour":"member-search",children:[e.jsx(ya,{className:"pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(O,{id:"header-member-search",name:"header-member-search",placeholder:"Search membersâ¦",className:"h-9 w-48 rounded-lg pl-9 lg:w-64",value:m,onChange:S=>c(S.target.value),onFocus:()=>{d.length>0&&p(!0)},autoComplete:"off","aria-label":"Quick member search"}),x&&e.jsx("p",{className:"absolute top-full mt-1 text-xs text-muted-foreground",children:"Searchingâ¦"}),h&&d.length>0&&e.jsx("div",{className:"absolute left-0 right-0 top-full z-50 mt-1 max-h-64 overflow-y-auto rounded-md border bg-card shadow-lg",children:d.map(S=>e.jsxs("button",{type:"button",className:"min-h-[44px] w-full border-b px-3 py-3 text-left text-sm last:border-b-0 hover:bg-muted",onClick:()=>{t(`/members/${S.id}`),c(""),p(!1)},children:[e.jsxs("span",{className:"font-medium",children:[S.first_name," ",S.last_name]}),e.jsx("span",{className:"ml-2 text-xs text-muted-foreground",children:S.email})]},S.id))}),h&&m.length>=2&&!x&&d.length===0&&e.jsx("div",{className:"absolute left-0 right-0 top-full z-50 mt-1 rounded-md border bg-card px-3 py-2 shadow-lg",children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"No members found"})})]}),e.jsx(ug,{}),e.jsx("div",{className:"hidden lg:block lg:h-6 lg:w-px lg:bg-border","aria-hidden":"true"}),e.jsxs(Ws,{children:[e.jsx(Vs,{asChild:!0,children:e.jsx(g,{variant:"ghost",className:"relative h-11 w-11 rounded-full lg:h-8 lg:w-8","aria-label":j?`Account menu for ${j}`:"Account menu",children:e.jsx(ao,{className:"h-8 w-8",children:e.jsx(no,{"aria-hidden":"true",children:w})})})}),e.jsxs($s,{className:"w-56",align:"end",children:[e.jsx(so,{className:"font-normal",children:e.jsxs("div",{className:"flex flex-col space-y-1",children:[e.jsx("p",{className:"text-sm font-medium leading-none",children:j}),e.jsx("p",{className:"text-xs leading-none text-muted-foreground",children:s?.email})]})}),e.jsx(Aa,{}),e.jsx(wt,{asChild:!0,children:e.jsxs(je,{to:"/account",children:[e.jsx(Vc,{className:"mr-2 h-4 w-4","aria-hidden":"true"}),e.jsx("span",{children:"Your account"})]})}),e.jsx(Aa,{}),v&&e.jsxs(e.Fragment,{children:[e.jsxs(wt,{onClick:k,children:[e.jsx(ga,{className:"mr-2 h-4 w-4","aria-hidden":"true"}),e.jsx("span",{children:"Back to platform"})]}),e.jsx(Aa,{})]}),e.jsxs(wt,{onClick:()=>a(),children:[e.jsx(oi,{className:"mr-2 h-4 w-4","aria-hidden":"true"}),e.jsx("span",{children:"Log out"})]})]})]})]})]})]})})}const bm="/favicon-32.png?v=3",jm="/favicon-192.png?v=3";function Ra(t){o.useEffect(()=>{const s=document.querySelector('link[rel="icon"][sizes="32x32"]'),a=document.querySelector('link[rel="icon"][sizes="192x192"]');if(t){const n=`${ds}${t}`;s&&(s.href=n),a&&(a.href=n);let r=document.querySelector('link[rel="apple-touch-icon"]');r||(r=document.createElement("link"),r.rel="apple-touch-icon",document.head.appendChild(r)),r.href=n}else{s&&(s.href=bm),a&&(a.href=jm);const n=document.querySelector('link[rel="apple-touch-icon"]');n&&n.remove()}return()=>{s&&(s.href=bm),a&&(a.href=jm);const n=document.querySelector('link[rel="apple-touch-icon"]');n&&n.remove()}},[t])}function ls(){const{data:t}=Qs();return Ra(t?.favicon_url),o.useEffect(()=>{document.title=t?.slug?`${t.slug.toUpperCase()} â AMS`:"AMS"},[t?.slug]),e.jsxs("div",{className:"min-h-screen w-full max-w-full overflow-x-hidden bg-background",children:[e.jsx(ww,{}),e.jsxs("div",{className:"min-w-0 lg:pl-64",children:[e.jsx(Fw,{}),e.jsx("main",{className:"py-6",children:e.jsx("div",{className:"mx-auto min-w-0 max-w-7xl px-4 sm:px-6 lg:px-8",children:e.jsx(Xl,{children:e.jsx($c,{})})})})]})]})}function Rw(){return e.jsx("div",{className:"hidden lg:fixed lg:inset-y-0 lg:z-50 lg:flex lg:w-64 lg:flex-col",children:e.jsxs("div",{className:"flex grow flex-col gap-y-5 overflow-y-auto border-r border-white/10 bg-[#0f1729] px-6 pb-4",children:[e.jsx("div",{className:"flex h-16 shrink-0 items-center",children:e.jsx("img",{src:pn,alt:"Korevera",className:"h-7 brightness-0 invert"})}),e.jsx("div",{className:"rounded-md bg-white/10 px-3 py-2 text-sm font-medium text-white/70",children:"Platform Admin"}),e.jsx("nav",{"aria-label":"Platform","data-desktop-nav":!0,className:"flex flex-1 flex-col",children:e.jsx("ul",{role:"list",className:"flex flex-1 flex-col gap-y-7",children:e.jsx("li",{children:e.jsx("ul",{role:"list",className:"-mx-2 space-y-1",children:Cx.map(t=>e.jsx("li",{children:e.jsxs(_a,{to:t.href,end:t.end,className:({isActive:s})=>me(s?"bg-white/10 text-white":"text-white/70 hover:bg-white/5 hover:text-white","group flex gap-x-3 rounded-md p-2 text-sm font-semibold leading-6 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-white/70"),children:[e.jsx(t.icon,{className:"h-6 w-6 shrink-0","aria-hidden":"true"}),t.name]})},t.name))})})})})]})})}function Mw(){const{user:t,logout:s}=V(),[a,n]=o.useState(!1),r=o.useCallback(()=>n(!1),[]),i=o.useRef(null);og(a,r);const{fullName:l,initials:m}=ro(t);return e.jsx(e.Fragment,{children:e.jsxs("div",{className:"sticky top-0 z-40 flex h-16 shrink-0 items-center gap-x-4 border-b border-border bg-card px-4 shadow-sm sm:gap-x-6 sm:px-6 lg:px-8",children:[e.jsxs(Ic,{open:a,onOpenChange:n,children:[e.jsx(tp,{asChild:!0,ref:i,children:e.jsxs("button",{type:"button",className:"-m-2.5 rounded-md p-2.5 text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring lg:hidden",children:[e.jsx("span",{className:"sr-only",children:"Open navigation"}),e.jsx(Wc,{className:"h-6 w-6","aria-hidden":"true"})]})}),e.jsxs(Oc,{children:[e.jsx($l,{className:"fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0"}),e.jsxs(ql,{onCloseAutoFocus:c=>cg(c,i.current),className:"fixed inset-y-0 left-0 z-50 w-full overflow-y-auto bg-[#0f1729] px-6 py-6 text-white shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm sm:ring-1 sm:ring-white/10",children:[e.jsxs(sp,{children:[e.jsx(Il,{children:"Platform navigation"}),e.jsx(Ol,{children:"Platform administration destinations"})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("img",{src:pn,alt:"Korevera",className:"h-7 brightness-0 invert"}),e.jsx(Uc,{asChild:!0,children:e.jsxs("button",{type:"button",className:"-m-2.5 rounded-md p-2.5 text-white/70 hover:text-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-white/70",children:[e.jsx("span",{className:"sr-only",children:"Close navigation"}),e.jsx(ms,{className:"h-6 w-6","aria-hidden":"true"})]})})]}),e.jsx("div",{className:"mt-4 rounded-md bg-white/10 px-3 py-2 text-sm font-medium text-white/70",children:"Platform Admin"}),e.jsx("nav",{"aria-label":"Platform",className:"mt-6",children:e.jsx("ul",{className:"space-y-2",children:Cx.map(c=>e.jsx("li",{children:e.jsxs(_a,{to:c.href,end:c.end,onClick:()=>n(!1),className:({isActive:d})=>me(d?"bg-white/10 text-white":"text-white/70 hover:bg-white/5 hover:text-white","flex min-h-11 items-center gap-x-3 rounded-lg px-3 py-2 text-base font-semibold leading-7 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-white/70"),children:[e.jsx(c.icon,{className:"h-6 w-6 shrink-0","aria-hidden":"true"}),c.name]})},c.name))})})]})]})]}),e.jsx("div",{className:"h-6 w-px bg-border lg:hidden","aria-hidden":"true"}),e.jsxs("div",{className:"flex flex-1 gap-x-4 self-stretch lg:gap-x-6",children:[e.jsx("div",{className:"flex flex-1 items-center",children:e.jsx("span",{className:"text-sm text-muted-foreground",children:"Korevera Platform"})}),e.jsxs("div",{className:"flex items-center gap-x-4 lg:gap-x-6",children:[e.jsx(ug,{}),e.jsx("div",{className:"hidden lg:block lg:h-6 lg:w-px lg:bg-border","aria-hidden":"true"}),e.jsxs(Ws,{children:[e.jsx(Vs,{asChild:!0,children:e.jsx(g,{variant:"ghost",className:"relative h-11 w-11 rounded-full lg:h-8 lg:w-8","aria-label":l?`Account menu for ${l}`:"Account menu",children:e.jsx(ao,{className:"h-8 w-8",children:e.jsx(no,{"aria-hidden":"true",children:m})})})}),e.jsxs($s,{className:"w-56",align:"end",children:[e.jsx(so,{className:"font-normal",children:e.jsxs("div",{className:"flex flex-col space-y-1",children:[e.jsx("p",{className:"text-sm font-medium leading-none",children:l}),e.jsx("p",{className:"text-xs leading-none text-muted-foreground",children:t?.email})]})}),e.jsx(Aa,{}),e.jsx(wt,{asChild:!0,children:e.jsxs(je,{to:"/platform/account",children:[e.jsx(Vc,{className:"mr-2 h-4 w-4","aria-hidden":"true"}),e.jsx("span",{children:"Your account"})]})}),e.jsx(Aa,{}),e.jsxs(wt,{onClick:()=>s(),children:[e.jsx(oi,{className:"mr-2 h-4 w-4","aria-hidden":"true"}),e.jsx("span",{children:"Log out"})]})]})]})]})]})]})})}function Dw(){return Ra(null),o.useEffect(()=>{document.title="Korevera â Platform Admin"},[]),e.jsxs("div",{className:"min-h-screen w-full max-w-full overflow-x-hidden bg-background",children:[e.jsx(Rw,{}),e.jsxs("div",{className:"min-w-0 lg:pl-64",children:[e.jsx(Mw,{}),e.jsx("main",{className:"py-6",children:e.jsx("div",{className:"mx-auto min-w-0 max-w-7xl px-4 sm:px-6 lg:px-8",children:e.jsx(Xl,{children:e.jsx($c,{})})})})]})]})}function qs(){const{societySlug:t}=Ds(),{domainSlug:s}=da();return s||t||""}function us(){const{isCustomDomain:t}=da(),s=qs();return o.useCallback(a=>t?`/portal${a}`:`/${s}/portal${a}`,[t,s])}const hg=o.createContext(null);function vm(t){return t??yd}function Lw({children:t}){const s=qs(),{member:a}=ft(),n=a?.id??null,{cartKey:r,ownerKey:i}=vi(s),[l,m]=o.useState({forMember:void 0,items:[]}),c=l.items;o.useEffect(()=>{let w=[];try{const v=localStorage.getItem(r),k=localStorage.getItem(i);if(v!==null){const S=JSON.parse(v),_=Array.isArray(S),y=k===vm(n),C=k===yd&&n!==null;_&&(y||C)?(w=S,C&&localStorage.setItem(i,n)):(localStorage.removeItem(r),localStorage.removeItem(i))}}catch{}m({forMember:n,items:w})},[r,i,n]),o.useEffect(()=>{l.forMember===n&&(l.items.length>0?(localStorage.setItem(r,JSON.stringify(l.items)),localStorage.setItem(i,vm(n))):(localStorage.removeItem(r),localStorage.removeItem(i)))},[l,n,r,i]);const d=o.useCallback(w=>{m(v=>({...v,items:w(v.items)}))},[]),u=o.useCallback(w=>{d(v=>{if(w.type==="event"&&v.find(S=>S.type==="event"&&S.id===w.id))return v;
1if(w.type==="product"){const k=v.findIndex(S=>S.type==="product"&&S.id===w.id);if(k>=0){const S=[...v];return S[k]={...S[k],quantity:S[k].quantity+w.quantity},S}}return[...v,w]})},[d]),h=o.useCallback((w,v)=>{d(k=>k.filter(S=>!(S.type===w&&S.id===v)))},[d]),p=o.useCallback((w,v,k)=>{if(k<=0){d(S=>S.filter(_=>!(_.type===w&&_.id===v)));return}d(S=>S.map(_=>_.type===w&&_.id===v?{..._,quantity:k}:_))},[d]),x=o.useCallback((w,v,k)=>{d(S=>S.map(_=>_.type===w&&_.id===v?{..._,formResponses:k}:_))},[d]),f=o.useCallback(()=>{d(()=>[]),localStorage.removeItem(r),localStorage.removeItem(i)},[d,r,i]),b=o.useMemo(()=>c.reduce((w,v)=>w+v.unitPrice*v.quantity,0),[c]),N=o.useMemo(()=>c.reduce((w,v)=>w+v.quantity,0),[c]),j=o.useMemo(()=>({items:c,addItem:u,removeItem:h,updateQuantity:p,updateItemFormResponses:x,clearCart:f,total:b,itemCount:N}),[c,u,h,p,x,f,b,N]);return e.jsx(hg.Provider,{value:j,children:t})}function _i(){const t=o.useContext(hg);if(!t)throw new Error("useCart must be used within a CartProvider");return t}function ar(){const{isAuthenticated:t}=ft();return re({queryKey:["portal","profile"],queryFn:async()=>{const s=await gt.getProfile();return s.csrf_token&&Za(s.csrf_token),s.profile},enabled:t})}function $w(){const{isAuthenticated:t}=ft();return re({queryKey:["portal","custom-fields"],queryFn:async()=>gt.getCustomFields(),enabled:t})}function pg(){const t=J();return W({mutationFn:s=>gt.updateProfile(s),onSuccess:()=>{t.invalidateQueries({queryKey:["portal","profile"]})}})}function qw(){return W({mutationFn:t=>gt.changePassword(t)})}function Iw(){return W({mutationFn:t=>gt.setPassword(t)})}function xg(){const{isAuthenticated:t}=ft();return re({queryKey:["portal","subscription"],queryFn:()=>gt.getSubscription(),enabled:t})}function gg(){const t=J();return W({mutationFn:s=>gt.toggleAutoRenew(s),onSuccess:()=>{t.invalidateQueries({queryKey:["portal","subscription"]}),t.invalidateQueries({queryKey:["portal","profile"]})}})}function Ow(){const t=J();return W({mutationFn:s=>gt.cancelSubscription(s),onSuccess:()=>{t.invalidateQueries({queryKey:["portal","subscription"]}),t.invalidateQueries({queryKey:["portal","profile"]})}})}function Uw(){const t=J();return W({mutationFn:()=>gt.reactivateSubscription(),onSuccess:()=>{t.invalidateQueries({queryKey:["portal","subscription"]}),t.invalidateQueries({queryKey:["portal","profile"]})}})}function zw(){const{isAuthenticated:t}=ft();return re({queryKey:["portal","payment-method"],queryFn:()=>gt.getPaymentMethod(),enabled:t})}function Bw(){return W({mutationFn:()=>gt.createSetupIntent()})}function Kw(){const t=J();return W({mutationFn:s=>gt.confirmCardUpdate(s),onSuccess:()=>{t.invalidateQueries({queryKey:["portal","payment-method"]})}})}function Qa(){const{isAuthenticated:t}=ft();return re({queryKey:["portal","dashboard-stats"],queryFn:()=>gt.getDashboardStats(),enabled:t})}function Qw(){const{isAuthenticated:t}=ft();return re({queryKey:["portal","my-events"],queryFn:()=>gt.getMyEvents(),enabled:t})}function fg(t=1,s=20){const{isAuthenticated:a}=ft();return re({queryKey:["portal","payments",t,s],queryFn:()=>gt.getPayments(t,s),enabled:a,placeholderData:sa})}function Nc(t=1,s=10,a){const{isAuthenticated:n}=ft();return re({queryKey:["portal","invoices",t,s,a],queryFn:()=>gt.getInvoices(t,s,a),enabled:n,placeholderData:sa})}function Ww(t){return re({queryKey:["public","events",t],queryFn:()=>gt.getPublicEvents(t),enabled:!!t})}function Vw(t,s){return re({queryKey:["public","product",t,s],queryFn:()=>gt.getPublicProduct(t,s),enabled:!!t&&!!s})}function ma(t){return re({queryKey:["portal","signup",t],queryFn:()=>gt.getSignupInfo(t),enabled:!!t})}function yg(){return W({mutationFn:({slug:t,data:s})=>gt.signup(t,s),meta:{suppressErrorToast:!0}})}function Gw(){return W({mutationFn:t=>gt.createRenewalPayment(t)})}function Yw(){const t=J();return W({mutationFn:()=>gt.renewMembershipCheck(),onSuccess:()=>{t.invalidateQueries({queryKey:["portal","subscription"]}),t.invalidateQueries({queryKey:["portal","invoices"]})}})}function Hw(){const t=J();return W({mutationFn:s=>gt.confirmRenewal(s),onSuccess:()=>{t.invalidateQueries({queryKey:["portal","subscription"]}),t.invalidateQueries({queryKey:["portal","payments"]}),t.invalidateQueries({queryKey:["portal","profile"]}),t.invalidateQueries({queryKey:["portal","invoices"]}),t.invalidateQueries({queryKey:["portal","dashboard-stats"]})}})}function Jw(){const t=J();return W({mutationFn:s=>gt.renewWithSavedCard(s),onSuccess:()=>{t.invalidateQueries({queryKey:["portal","subscription"]}),t.invalidateQueries({queryKey:["portal","payments"]}),t.invalidateQueries({queryKey:["portal","profile"]}),t.invalidateQueries({queryKey:["portal","invoices"]}),t.invalidateQueries({queryKey:["portal","dashboard-stats"]})}})}function Zw(){return W({mutationFn:t=>gt.createInvoicePayment(t)})}function Xw(){const t=J();return W({mutationFn:({invoiceId:s,paymentIntentId:a})=>gt.confirmInvoicePayment(s,a),onSuccess:()=>{t.invalidateQueries({queryKey:["portal","invoices"]}),t.invalidateQueries({queryKey:["portal","payments"]}),t.invalidateQueries({queryKey:["portal","subscription"]}),t.invalidateQueries({queryKey:["portal","dashboard-stats"]})}})}function eN(){return W({mutationFn:t=>gt.requestEmailChange(t)}
1)}function tN(){return W({mutationFn:t=>gt.upgradeMembership(t)})}function sN(t=1,s=20,a,n){const{isAuthenticated:r}=ft(),i=n?.customFieldFilters?JSON.stringify(n.customFieldFilters):"";return re({queryKey:["portal","directory",t,s,a,n?.membership_type_id,n?.state,i],queryFn:()=>gt.getDirectoryMembers({page:t,size:s,search:a||void 0,membership_type_id:n?.membership_type_id||void 0,state:n?.state||void 0,customFieldFilters:n?.customFieldFilters}),enabled:r,placeholderData:sa})}function bg(){const{isAuthenticated:t}=ft();return re({queryKey:["portal","directory-filters"],queryFn:()=>gt.getDirectoryFilters(),enabled:t})}function jg(){return W({mutationFn:()=>gt.getEventAppSsoToken()})}function aN(){return W({mutationFn:()=>gt.getVideoLibrarySsoToken()})}function nN(){const t=J();return W({mutationFn:s=>gt.uploadHeadshot(s),onSuccess:()=>{t.invalidateQueries({queryKey:["portal","profile"]}),t.invalidateQueries({queryKey:["portal","directory"]})}})}function rN(){const t=J();return W({mutationFn:()=>gt.deleteHeadshot(),onSuccess:()=>{t.invalidateQueries({queryKey:["portal","profile"]}),t.invalidateQueries({queryKey:["portal","directory"]})}})}function iN(){const t=J();return W({mutationFn:s=>gt.confirmUpgrade(s),onSuccess:()=>{t.invalidateQueries({queryKey:["portal","subscription"]}),t.invalidateQueries({queryKey:["portal","profile"]}),t.invalidateQueries({queryKey:["portal","dashboard-stats"]}),t.invalidateQueries({queryKey:["portal","payments"]}),t.invalidateQueries({queryKey:["portal","invoices"]})}})}function lN(){const{logout:t,member:s}=ft(),a=us(),n=kt(),[r,i]=o.useState(!1),l=qs(),{data:m}=ma(l||void 0),c=m?.society?.website_url,d=m?.society?.name,u=m?.society?.logo_url?`${ds}${m.society.logo_url}`:null,{theme:h,toggleTheme:p}=uv(),{itemCount:x}=_i(),{data:f}=ar(),{data:b}=Qa(),N=!!f?.membership_type_name,j=b?.is_real_member===!0,w=b?.feature_modules?.commerce_enabled===!0,v=b?.feature_modules?.committees_enabled===!0,k=[{to:a("/dashboard"),label:"Dashboard",icon:Ul},...w?[{to:a("/events"),label:"Events",icon:Yt},{to:a("/products"),label:"Shop",icon:Wn}]:[]],S=[{to:a("/profile"),label:"Edit profile",icon:gc},{to:a("/payments"),label:"Payments",icon:Qt},{to:a("/invoices"),label:"Invoices",icon:cs},...w?[{to:a("/orders"),label:"Orders",icon:Cr}]:[],{to:a("/subscription"),label:N?"Subscription":"Join as member",icon:St},...v&&j?[{to:a("/committees"),label:"Committees",icon:Kn}]:[]],_=()=>{t(),n(a("/login"))},y=()=>{const P=`ams_portal_tour_done_${s?.id??"unknown"}`;localStorage.removeItem(P),i(!1),n(a("/dashboard")),window.location.reload()},C=s?`${s.first_name?.[0]||""}${s.last_name?.[0]||""}`.toUpperCase():"";return e.jsx("header",{className:"sticky top-0 z-50 border-b border-white/10 shadow-sm",style:{backgroundColor:"var(--portal-primary, #ffffff)",color:"var(--portal-primary-fg, #111827)"},children:e.jsxs("div",{className:"mx-auto max-w-4xl px-4 sm:px-6",children:[e.jsxs("div",{className:"flex h-14 items-center justify-between gap-4",children:[e.jsxs(_a,{to:a("/dashboard"),className:"group flex min-w-0 shrink items-center gap-2.5",style:{color:"var(--portal-primary-fg)"},children:[u&&e.jsx("img",{src:u,alt:"",className:"h-7 w-auto shrink-0 object-contain sm:h-8"}),e.jsx("span",{className:"hidden whitespace-nowrap text-base font-medium opacity-80 transition-opacity group-hover:opacity-100 sm:inline",children:"Member Portal"})]}),e.jsxs("nav",{className:"hidden min-w-0 items-center gap-0.5 overflow-hidden md:flex","data-tour":"portal-nav",children:[c&&e.jsxs(e.Fragment,{children:[e.jsxs("a",{href:c,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1.5 whitespace-nowrap rounded-md px-3 py-1.5 text-sm font-medium opacity-80 transition-all hover:bg-white/10 hover:opacity-100",style:{color:"var(--portal-primary-fg)"},children:[e.jsx(Rs,{className:"h-3.5 w-3.5 shrink-0"}),"Website"]}),e.jsx("div",{className:"mx-1 h-4 w-px shrink-0 bg-white/20"})]}),k.map(P=>e.jsxs(_a,{to:P.to,className:({isActive:A})=>`flex items-center gap-1.5 whitespace-nowrap rounded-md px-3 py-1.5 text-sm font-medium transition-all ${A?"bg-white/20 shadow-sm":"opacity-80 hover:bg-white/10 hover:opacity-100"}`,style:{color:"var(--portal-primary-fg)"},..."dataTour"in P&&{"data-tour":P.dataTour},children:[e.jsx(P.icon,{className:"h-4 w-4 shrink-0"}),P.label]},P.to))]}),e.jsxs("div",{className:"hidden shrink-0 items-center gap-1 md:flex",children:[w&&e.jsxs(_a,{to:a("/cart"),className:"relative flex items-center justify-center rounded-md p-2 opacity-80 transition-all hover:bg-white/10 hover:opacity-100",style:{color:"var(--portal-primary-fg)"},children:[e.jsx(Qn,{className:"h-4 w-4"}),x>0&&e.jsx("span",{className:"absolute -right-0.5 -top-0.5 flex h-4 min-w-[16px] items-center justify-center rounded-full bg-white px-1 text-[10px] font-bold shadow-sm",style:{color:"var(--portal-primary)"},children:x})]}),e.jsxs(Ws,{children:[e.jsx(Vs,{asChild:!0,children:e.jsxs(g,{variant:"ghost",className:"gap-2 px-2 text-sm hover:bg-white/10",style:{color:"var(--portal-primary-fg)"},"data-tour":"portal-account-menu",children:[C?e.jsx("span",{className:"flex h-7 w-7 items-center justify-center rounded-full bg-white/20 text-[11px] font-semibold",children:C}):e.jsx(gc,{className:"h-5 w-5"}
1),e.jsx("span",{className:"hidden lg:inline",children:"My Account"}),e.jsx(ps,{className:"h-3.5 w-3.5 opacity-70"})]})}),e.jsxs($s,{align:"end",className:"w-56",children:[s&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"px-2 py-1.5 text-xs",children:[e.jsxs("p",{className:"truncate font-medium text-foreground",children:[s.first_name," ",s.last_name]}),e.jsx("p",{className:"truncate text-muted-foreground",children:s.email})]}),e.jsx(Aa,{})]}),S.map(P=>e.jsxs(wt,{onClick:()=>n(P.to),children:[e.jsx(P.icon,{className:"mr-2 h-4 w-4"}),P.label]},P.to)),e.jsx(Aa,{}),e.jsxs(wt,{onClick:p,children:[h==="dark"?e.jsx(pc,{className:"mr-2 h-4 w-4"}):e.jsx(xc,{className:"mr-2 h-4 w-4"}),h==="dark"?"Light mode":"Dark mode"]}),e.jsxs(wt,{onClick:y,children:[e.jsx(jr,{className:"mr-2 h-4 w-4"}),"Take a tour"]}),e.jsx(Aa,{}),e.jsxs(wt,{onClick:_,children:[e.jsx(oi,{className:"mr-2 h-4 w-4"}),"Sign out"]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-1 md:hidden",children:[w&&e.jsxs(_a,{to:a("/cart"),className:"relative flex min-h-[44px] min-w-[44px] items-center justify-center p-2.5",style:{color:"var(--portal-primary-fg)"},children:[e.jsx(Qn,{className:"h-5 w-5"}),x>0&&e.jsx("span",{className:"absolute right-1 top-1 flex h-4 min-w-[16px] items-center justify-center rounded-full bg-white px-1 text-[10px] font-bold shadow-sm",style:{color:"var(--portal-primary)"},children:x})]}),e.jsx("button",{className:"min-h-[44px] min-w-[44px] p-2.5",style:{color:"var(--portal-primary-fg)"},onClick:()=>i(!r),children:r?e.jsx(ms,{className:"h-5 w-5"}):e.jsx(Wc,{className:"h-5 w-5"})})]})]}),r&&e.jsxs("nav",{className:"space-y-3 border-t border-white/15 py-3 md:hidden",children:[s&&e.jsxs("div",{className:"flex items-center gap-2.5 px-3 pb-2",children:[C&&e.jsx("span",{className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-white/20 text-xs font-semibold",children:C}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("p",{className:"truncate text-sm font-semibold",children:[s.first_name," ",s.last_name]}),e.jsx("p",{className:"truncate text-xs opacity-75",style:{color:"var(--portal-primary-fg)"},children:s.email})]})]}),c&&e.jsxs("a",{href:c,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-2.5 rounded-md px-3 py-2.5 text-sm font-medium opacity-80 transition-all hover:bg-white/10 hover:opacity-100",style:{color:"var(--portal-primary-fg)"},children:[e.jsx(Rs,{className:"h-4 w-4"}),d?`${d} Website`:"Back to Website"]}),e.jsxs("div",{className:"space-y-0.5",children:[e.jsx("p",{className:"px-3 text-[10px] font-semibold uppercase tracking-wider opacity-60",style:{color:"var(--portal-primary-fg)"},children:"Navigation"}),k.map(P=>e.jsxs(_a,{to:P.to,onClick:()=>i(!1),className:({isActive:A})=>`flex items-center gap-2.5 rounded-md px-3 py-2.5 text-sm font-medium transition-all ${A?"bg-white/20 shadow-sm":"opacity-80 hover:bg-white/10 hover:opacity-100"}`,style:{color:"var(--portal-primary-fg)"},children:[e.jsx(P.icon,{className:"h-4 w-4"}),P.label]},P.to))]}),e.jsxs("div",{className:"space-y-0.5",children:[e.jsx("p",{className:"px-3 text-[10px] font-semibold uppercase tracking-wider opacity-60",style:{color:"var(--portal-primary-fg)"},children:"Account"}),S.map(P=>e.jsxs(_a,{to:P.to,onClick:()=>i(!1),className:({isActive:A})=>`flex items-center gap-2.5 rounded-md px-3 py-2.5 text-sm font-medium transition-all ${A?"bg-white/20 shadow-sm":"opacity-80 hover:bg-white/10 hover:opacity-100"}`,style:{color:"var(--portal-primary-fg)"},children:[e.jsx(P.icon,{className:"h-4 w-4"}),P.label]},P.to))]}),e.jsxs("div",{className:"space-y-0.5 border-t border-white/15 pt-2",children:[e.jsxs("button",{onClick:()=>{p(),i(!1)},className:"flex w-full items-center gap-2.5 rounded-md px-3 py-2.5 text-sm font-medium opacity-80 transition-all hover:bg-white/10 hover:opacity-100",style:{color:"var(--portal-primary-fg)"},children:[h==="dark"?e.jsx(pc,{className:"h-4 w-4"}):e.jsx(xc,{className:"h-4 w-4"}),h==="dark"?"Light mode":"Dark mode"]}),e.jsxs("button",{onClick:y,className:"flex w-full items-center gap-2.5 rounded-md px-3 py-2.5 text-sm font-medium opacity-80 transition-all hover:bg-white/10 hover:opacity-100",style:{color:"var(--portal-primary-fg)"},children:[e.jsx(jr,{className:"h-4 w-4"}),"Take a tour"]}
1),e.jsxs("button",{onClick:_,className:"flex w-full items-center gap-2.5 rounded-md px-3 py-2.5 text-sm font-medium opacity-80 transition-all hover:bg-white/10 hover:opacity-100",style:{color:"var(--portal-primary-fg)"},children:[e.jsx(oi,{className:"h-4 w-4"}),"Sign out"]})]})]})]})})}const Fe=Ic,oN=Oc,vg=o.forwardRef(({className:t,...s},a)=>e.jsx($l,{ref:a,className:me("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",t),...s}));vg.displayName=$l.displayName;let ri=null;typeof document<"u"&&(document.addEventListener("pointerdown",t=>{const s=t.target instanceof Element?t.target.closest('button, a[href], input:not([type="hidden"]), select, textarea, summary, [contenteditable], [role="button"], [role="menuitem"], [role="option"], [tabindex]:not([tabindex="-1"])'):null;ri=s?{control:new WeakRef(s),at:Date.now()}:null},!0),document.addEventListener("keydown",()=>ri=null,!0));const wm="[data-radix-popper-content-wrapper] > *";function cN(){const t=ri&&Date.now()-ri.at<1e3?ri.control.deref():null,a=(t&&(t.isConnected||t.closest(wm))?t:null)??document.activeElement;if(!(a instanceof HTMLElement)||a===document.body)return null;let n=a;for(let r=0;r<4;r++){const i=n.closest(wm);if(!i)break;const l=d=>d instanceof HTMLElement&&!i.contains(d)?d:null,c=(i.getAttribute("aria-labelledby")??"").split(/\s+/).filter(Boolean).map(d=>l(document.getElementById(d))).find(Boolean)??(i.id?[...document.querySelectorAll("[aria-controls]")].map(d=>d.getAttribute("aria-controls")===i.id?l(d):null).find(Boolean):null);if(!c)break;n=c}return n}const Te=o.forwardRef(({className:t,children:s,onOpenAutoFocus:a,onCloseAutoFocus:n,...r},i)=>{const l=o.useRef(null);return e.jsxs(oN,{children:[e.jsx(vg,{}),e.jsxs(ql,{ref:i,onOpenAutoFocus:m=>{l.current=cN(),a?.(m)},onCloseAutoFocus:m=>{n?.(m);const c=l.current;l.current=null,!(m.defaultPrevented||!c?.isConnected)&&(c.focus({preventScroll:!0}),document.activeElement===c&&m.preventDefault())},className:me("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",t),...r,children:[s,e.jsxs(Uc,{className:"absolute right-4 top-4 roun
1ded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",children:[e.jsx(ms,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]})});Te.displayName=ql.displayName;const Ae=({className:t,...s})=>e.jsx("div",{className:me("flex flex-col space-y-1.5 text-center sm:text-left",t),...s});Ae.displayName="DialogHeader";const Ge=({className:t,...s})=>e.jsx("div",{className:me("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",t),...s});Ge.displayName="DialogFooter";const Ee=o.forwardRef(({className:t,...s},a)=>e.jsx(Il,{ref:a,className:me("text-lg font-semibold leading-none tracking-tight",t),...s}));Ee.displayName=Il.displayName;const tt=o.forwardRef(({className:t,...s},a)=>e.jsx(Ol,{ref:a,className:me("text-sm text-muted-foreground",t),...s}));tt.displayName=Ol.displayName;const It=o.forwardRef(({className:t,...s},a)=>e.jsx("textarea",{className:me("flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-base ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",t),ref:a,...s}));It.displayName="Textarea";function dN({raised:t=!1}){const[s,a]=o.useState(!1),[n,r]=o.useState(""),[i,l]=o.useState(!1),[m,c]=o.useState(!1),d=()=>{a(!1),r(""),c(!1)};return e.jsxs(e.Fragment,{children:[e.jsxs("button",{onClick:()=>{a(!0),c(!1)},className:`fixed ${t?"bottom-24":"bottom-5"} right-5 z-40 flex items-center gap-2 rounded-full bg-blue-600 px-4 py-2.5 text-sm font-medium text-white shadow-lg transition-colors hover:bg-blue-700`,"aria-label":"Leave Feedback",children:[e.jsx(fl,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Feedback"})]}),e.jsx(Fe,{open:s,onOpenChange:u=>{i||(u?a(!0):d())},children:e.jsxs(Te,{className:"sm:max-w-md",children:[e.jsx(Ae,{children:e.jsxs(Ee,{className:"flex items-center gap-2",children:[e.jsx(fl,{className:"h-5 w-5 text-blue-600"}),"Leave Feedback"]})}),m?e.jsxs("div",{className:"space-y-2 py-6 text-center",children:[e.jsx("p",{className:"text-sm font-medium text-green-700 dark:text-green-400",children:"Thank you for your feedback!"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Your message has been submitted."})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(It,{placeholder:"Report a bug, suggest an improvement, or share your thoughtsâ¦",value:n,onChange:u=>r(u.target.value.slice(0,2e3)),rows:5,disabled:i}),e.jsxs("p",{className:"text-right text-xs text-muted-foreground",children:[n.length,"/2000"]})]}),e.jsxs(Ge,{children:[e.jsx(g,{variant:"outline",type:"button",onClick:d,disabled:i,children:"Cancel"}),e.jsx(g,{type:"button",className:"bg-blue-600 text-white hover:bg-blue-700",disabled:i||n.trim().length===0,onClick:async()=>{l(!0);try{await gt.submitFeedback({content:n.trim(),page_url:window.location.pathname}),r(""),c(!0)}catch(u){console.error("Feedback submission failed:",u)}finally{l(!1)}},children:i?"Submitting...":"Submit"})]})]})]})})]})}const wd={getConversation:async()=>(await Me.get("/portal/support/conversation")).data,send:async t=>(await Me.post("/portal/support/messages",{body:t})).data,markSeen:async()=>{await Me.post("/portal/support/seen")}};function mN(t,s){return re({queryKey:["portal","support","conversation"],queryFn:()=>wd.getConversation(),enabled:s,refetchInterval:t?3e3:3e4})}function uN(){const t=J();return W({mutationFn:s=>wd.send(s),onSuccess:()=>{t.invalidateQueries({queryKey:["portal","support","conversation"]})}})}function hN(){return W({mutationFn:()=>wd.markSeen()})}function pN(){const[t,s]=o.useState(!1),[a,n]=o.useState(""),[r,i]=o.useState(0),{data:l}=mN(t,!0),m=uN(),{mutate:c}=hN(),d=o.useRef(null),u=l?.messages??[],h=u.reduce((f,b)=>Math.max(f,b.seq),0),p=u.filter(f=>f.seq>r&&f.sender_type==="staff").length;o.useEffect(()=>{new URLSearchParams(window.location.search).get("support")==="open"&&s(!0)},[]),o.useEffect(()=>{if(!t)return;c(),i(h),d.current?.scrollTo({top:d.current.scrollHeight});const f=setInterval(()=>c(),2e4);return()=>clearInterval(f)},[t,h,c]);const x=()=>{const f=a.trim();f&&(m.mutate(f),n(""))};return e.jsxs(e.Fragment,{children:[!t&&e.jsxs("button",{onClick:()=>s(!0),className:"fixed bottom-5 right-5 z-40 flex h-14 w-14 items-center justify-center rounded-full bg-blue-600 text-white shadow-lg hover:bg-blue-700","aria-label":"Open support chat",children:[e.jsx(Gc,{
1className:"h-6 w-6"}),p>0&&e.jsx("span",{className:"absolute -right-1 -top-1 flex h-5 min-w-5 items-center justify-center rounded-full bg-red-500 px-1 text-xs font-bold",children:p})]}),t&&e.jsxs("div",{className:"fixed inset-0 z-50 flex flex-col bg-card sm:inset-auto sm:bottom-5 sm:right-5 sm:h-[32rem] sm:w-96 sm:rounded-lg sm:border sm:shadow-xl",children:[e.jsxs("div",{className:"flex items-center justify-between border-b bg-blue-600 px-4 py-3 text-white sm:rounded-t-lg",children:[e.jsx("span",{className:"font-semibold",children:"Support"}),e.jsx("button",{onClick:()=>s(!1),"aria-label":"Close support chat",className:"flex h-11 w-11 items-center justify-center",children:e.jsx(ms,{className:"h-5 w-5"})})]}),e.jsxs("div",{ref:d,className:"flex-1 space-y-3 overflow-y-auto p-4",children:[u.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:l?.response_time_text??"Send us a message and we'll get back to you."}),u.map(f=>e.jsxs("div",{className:f.sender_type==="member"?"ml-auto max-w-[80%] rounded-lg bg-blue-600 px-3 py-2 text-sm text-white":f.sender_type==="system"?"mx-auto max-w-[90%] text-center text-xs text-muted-foreground":"mr-auto max-w-[80%] rounded-lg bg-muted px-3 py-2 text-sm text-foreground",children:[f.sender_type==="staff"&&f.sender_name&&e.jsx("div",{className:"mb-0.5 text-xs font-semibold opacity-70",children:f.sender_name}),f.body]},f.id))]}),e.jsxs("div",{className:"flex items-center gap-2 border-t p-3",children:[e.jsx("input",{value:a,onChange:f=>n(f.target.value),onKeyDown:f=>f.key==="Enter"&&x(),placeholder:"Type a messageâ¦",className:"min-h-[44px] flex-1 rounded-md border bg-background px-3 text-sm text-foreground",maxLength:4e3}),e.jsx("button",{onClick:x,disabled:m.isPending||!a.trim(),className:"flex h-11 w-11 items-center justify-center rounded-md bg-blue-600 text-white hover:bg-blue-700 disabled:opacity-50","aria-label":"Send message",children:e.jsx(Pr,{className:"h-5 w-5"})})]})]})]})}const wg="#1a365d";function Ng(t){const s=t.replace("#",""),a=parseInt(s.slice(0,2),16),n=parseInt(s.slice(2,4),16),r=parseInt(s.slice(4,6),16);return(.299*a+.587*n+.114*r)/255>.5?"#1a1a1a":"#ffffff"}function kg(t,s=.15){const a=t.replace("#",""),n=Math.round(parseInt(a.slice(0,2),16)*(1-s)),r=Math.round(parseInt(a.slice(2,4),16)*(1-s)),i=Math.round(parseInt(a.slice(4,6),16)*(1-s));return`#${n.toString(16).padStart(2,"0")}${r.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}function kc(t,s=.9){const a=t.replace("#",""),n=Math.round(parseInt(a.slice(0,2),16)+(255-parseInt(a.slice(0,2),16))*s),r=Math.round(parseInt(a.slice(2,4),16)+(255-parseInt(a.slice(2,4),16))*s),i=Math.round(parseInt(a.slice(4,6),16)+(255-parseInt(a.slice(4,6),16))*s);return`#${n.toString(16).padStart(2,"0")}${r.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}function Si(t){const s=t||wg;return{"--portal-primary":s,"--portal-primary-hover":kg(s,.15),"--portal-primary-fg":Ng(s),"--portal-primary-light":kc(s,.9)}}const xN="#f2bd69";function gN(t){const s=(t||"").trim();return/^#[0-9a-f]{6}$/i.test(s)?s:/^#[0-9a-f]{3}$/i.test(s)?`#${s[1]}${s[1]}${s[2]}${s[2]}${s[3]}${s[3]}`:wg}function Nd(t){const s=gN(t),a=Ng(s)!=="#ffffff";return{...Si(s),"--login-deep":kg(s,a?.72:.5),"--login-glow":kc(s,.15),"--login-streak":kc(s,.5),"--login-accent":xN}}function _g(t){const s=t.split(/\s+/).filter(Boolean);if(s.length===1)return s[0];const a=s.filter(n=>/^[A-Z]/.test(n)).map(n=>n[0]).join("");return a.length>=2&&a.length<=6?a:t}function fN(){const{member:t,impersonatedBy:s}=ft();if(!s)return null;const a=t?`${t.first_name} ${t.last_name}`:"member",n=()=>{const r=t?.id;gx(localStorage.getItem("portal_society_slug")??"default"),localStorage.removeItem("portal_access_token"),localStorage.removeItem("portal_member"),localStorage.removeItem("portal_society_slug"),localStorage.removeItem("portal_impersonated_by"),$n(),window.location.href=r?`/members/${r}`:"/"};return e.jsxs("div",{className:"sticky top-0 z-50 flex items-center justify-center gap-4 bg-amber-400 px-4 py-2 text-sm font-medium text-amber-950",children:[e.jsxs("span",{children:["Viewing as ",a," â Admin Impersonation"]}),e.jsx("button",{onClick:n,className:"rounded bg-amber-600 px-3 py-1 text-xs font-semibold text-white hover:bg-amber-700",children:"Exit"})]})}function Nm(){const t=qs(),{data:s}=ma(t||void 0),a=Si(s?.society?.primary_color);return Ra(s?.society?.favicon_url),o.useEffect(()=>{document.title=t?`${t.toUpperCase()} â Member Portal`:"Member Portal"},[t]),e.jsx(mv,{children:e.jsx(Lw,{children:e.jsxs("div",{className:"min-h-screen w-full max-w-full overflow-x-hidden bg-background",style:a,children:[e.jsx(fN,{}),e.jsx(lN,{}),e.jsx("main",{className:"py-6",children:e.jsx("div",{className:"mx-auto max-w-4xl px-4 sm:px-6",children:e.jsx(Xl,{children:e.jsx($c,{})})})}),e.jsx(dN,{raised:s?.settings?.support_chat_enabled===!0}),s?.settings?.support_chat_enabled===!0&&e.jsx(pN,{})]})})})}const yN=qc("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),T=o.forwardRef(({className:t,...s},a)=>e.jsx(ap,{ref:a,className:me(yN(),t),...s}));T.displayName=ap.displayName;const L=o.forwardRef(({className:t,...s},a)=>e.jsx("div",{ref:a,className:me("rounded-lg border bg-card text-card-foreground shadow-sm",t),...s}));
1L.displayName="Card";const ne=o.forwardRef(({className:t,...s},a)=>e.jsx("div",{ref:a,className:me("flex flex-col space-y-1.5 p-6",t),...s}));ne.displayName="CardHeader";const ie=o.forwardRef(({className:t,...s},a)=>e.jsx("h3",{ref:a,className:me("text-2xl font-semibold leading-none tracking-tight",t),...s}));ie.displayName="CardTitle";const Ci=o.forwardRef(({className:t,...s},a)=>e.jsx("p",{ref:a,className:me("text-sm text-muted-foreground",t),...s}));Ci.displayName="CardDescription";const $=o.forwardRef(({className:t,...s},a)=>e.jsx("div",{ref:a,className:me("p-6 pt-0",t),...s}));$.displayName="CardContent";const Sg=o.forwardRef(({className:t,...s},a)=>e.jsx("div",{ref:a,className:me("flex items-center p-6 pt-0",t),...s}));Sg.displayName="CardFooter";function io(){return o.useMemo(()=>Gy(),[])}const bN={not_authorized:"That Google account canât sign in here. Use your company Google account, or ask a platform admin for access.",invitation_pending:"Accept the invitation in your email first; after that you can sign in with Google.",too_many_attempts:"This account is temporarily locked. Try again in a few minutes.",google_unavailable:"Google sign-in isnât available right now. Sign in with your password."},jN="Google sign-in didnât complete. Please try again.";function vN(){const[t,s]=ws(),a=t.get("google_error"),[n,r]=o.useState(""),[i,l]=o.useState(""),[m,c]=o.useState(a&&a!=="google_cancelled"?bN[a]??jN:""),[d,u]=o.useState(!1),[h,p]=o.useState(!1),{login:x,loginWithPasskey:f}=V(),b=kt(),N=ta(),j=io(),{data:w}=re({queryKey:["auth","providers"],queryFn:Nn.providers,staleTime:1/0}),[v,k]=o.useState(!1);o.useEffect(()=>{const C=P=>{P.persisted&&k(!1)};return window.addEventListener("pageshow",C),()=>window.removeEventListener("pageshow",C)},[]),o.useEffect(()=>{if(a===null)return;const C=new URLSearchParams(t);C.delete("google_error"),s(C,{replace:!0})},[a,t,s]);const S=hd(t.get("next"))??N.state?.from?.pathname??"/",_=async C=>{C.preventDefault(),c(""),u(!0);try{await x(n,i),b(S,{replace:!0})}catch{c("Invalid email or password")}finally{u(!1)}},y=async()=>{c(""),p(!0);try{await f(),b(S,{replace:!0})}catch(C){C instanceof Error&&C.name==="NotAllowedError"||c("Passkey authentication failed. Try signing in with your password.")}finally{p(!1)}};return e.jsxs("div",{className:"flex min-h-screen flex-col items-center justify-center bg-muted px-4",children:[e.jsxs(L,{className:"w-full max-w-md",children:[e.jsxs(ne,{className:"space-y-1 text-center",children:[e.jsx(ie,{className:"text-2xl font-semibold tracking-tight",children:"AMS Admin"}),e.jsx(Ci,{children:"Sign in to your account to continue"})]}),e.jsxs($,{children:[e.jsxs("form",{onSubmit:_,className:"space-y-4",children:[m&&e.jsx("div",{className:"rounded-md bg-destructive/10 p-3 text-sm text-destructive",children:m}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"email",children:"Email"}),e.jsx(O,{id:"email",type:"email",placeholder:"[email protected]",value:n,onChange:C=>r(C.target.value),required:!0,autoComplete:"email"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"password",children:"Password"}),e.jsx(O,{id:"password",type:"password",value:i,onChange:C=>l(C.target.value),onKeyDown:C=>{C.key==="Enter"&&C.currentTarget.form?.requestSubmit()},required:!0,autoComplete:"current-password"})]}),e.jsx(g,{type:"submit",className:"w-full",disabled:d,children:d?"Signing in...":"Sign in"})]}),(j||w?.google)&&e.jsxs("div",{className:"relative my-4",children:[e.jsx("div",{className:"absolute inset-0 flex items-center",children:e.jsx("span",{className:"w-full border-t"})}),e.jsx("div",{className:"relative flex justify-center text-xs uppercase",children:e.jsx("span",{className:"bg-card px-2 text-muted-foreground",children:"or"})})]}),e.jsxs("div",{className:"space-y-2",children:[w?.google&&e.jsx(g,{type:"button",variant:"outline",className:"w-full",disabled:v,onClick:()=>{k(!0),window.location.assign(Nn.googleSignInUrl(S))},children:v?"Opening Googleâ¦":"Sign in with Google"}),j&&e.jsx(g,{type:"button",variant:"outline",className:"w-full",onClick:y,disabled:h,children:h?"Waiting for device...":"Sign in with Passkey"})]})]})]}),e.jsxs("div",{className:"mt-8 flex items-center gap-2 text-muted-foreground",children:[e.jsx("span",{className:"text-sm",children:"Powered by"}),e.jsx("img",{src:pn,alt:"Korevera",className:"h-5 object-contain"})]})]})}function Y({className:t,...s}){return e.jsx("div",{className:me("animate-pulse rounded-md bg-muted",t),...s})}function wN({current:t,previous:s}){if(s===0)return null;const a=t-s,n=(a/s*100).toFixed(1),r=a>0;return a===0?null:e.jsxs("div",{className:`mt-1 inline-flex items-center gap-0.5 text-xs font-medium ${r?"text-emerald-600 dark:text-emerald-400":"text-red-600 dark:text-red-400"}`,children:[r?e.jsx(zs,{className:"h-3 w-3"}):e.jsx(Hn,{className:"h-3 w-3"}),e.jsxs("span",{children:[r?"+":"",n,"% YoY"]})]})}function NN({data:t,isLoading:s}){const a=kt(),n=t?.expiring_soon?.next_30_days??0,r=Number(t?.revenue_mtd?.total_revenue??0),i=Number(t?.revenue_mtd?.total_refunded??0),l=t?.revenue_mtd?.refund_count??0,m=t?.yoy,c=[{name:"Current roster",value:t?.membership?.total_members??0,icon:Lt,iconClass:"bg-brand-navy
1/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",current:t?.membership?.total_members??0,previous:m?.total_members_prev??0,link:"/members"},{name:"Active members",value:t?.membership?.active_members??0,icon:Kl,iconClass:"bg-emerald-100 text-emerald-600 dark:bg-emerald-900/30 dark:text-emerald-400",current:t?.membership?.active_members??0,previous:m?.active_members_prev??0,link:"/members?status=active"},{name:"Expiring soon",value:n,icon:bp,iconClass:"bg-amber-100 text-amber-600 dark:bg-amber-900/30 dark:text-amber-400",current:0,previous:0,link:"/members?status=grace"},{name:"MTD revenue",value:`$${r.toLocaleString()}`,icon:Ua,iconClass:"bg-emerald-100 text-emerald-600 dark:bg-emerald-900/30 dark:text-emerald-400",current:r,previous:Number(m?.revenue_mtd_prev??0),link:"/payments"}];return s?e.jsx("div",{className:"grid gap-4 md:grid-cols-2 xl:grid-cols-4",children:[...Array(4)].map((d,u)=>e.jsxs(L,{children:[e.jsx(ne,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx(Y,{className:"h-7 w-7 rounded-lg"}),e.jsx(Y,{className:"h-4 w-24"})]})}),e.jsx($,{children:e.jsx(Y,{className:"h-8 w-20"})})]},u))}):e.jsx("div",{className:"grid gap-4 md:grid-cols-2 xl:grid-cols-4",children:c.map(d=>e.jsxs(L,{className:"min-w-0 cursor-pointer overflow-hidden transition-shadow hover:shadow-md",onClick:()=>a(d.link),children:[e.jsx(ne,{className:"pb-2",children:e.jsxs(ie,{className:"flex items-center gap-2.5",children:[e.jsx("span",{className:`flex h-7 w-7 shrink-0 items-center justify-center rounded-lg ${d.iconClass}`,children:e.jsx(d.icon,{className:"h-4 w-4"})}),d.name]})}),e.jsxs($,{children:[e.jsx("div",{className:"text-2xl font-semibold tracking-tight",children:d.value}),e.jsx(wN,{current:d.current,previous:d.previous}),d.name==="Active members"&&(t?.membership?.auto_renew_count??0)>0&&e.jsxs("p",{className:"mt-1 flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(Ar,{className:"h-3 w-3"}),t.membership.auto_renew_count," (",Math.round(t.membership.auto_renew_count/t.membership.active_members*100),"%) auto-renew"]}),d.name==="MTD revenue"&&l>0&&e.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:["net of $",i.toLocaleString()," refunded (",l," refund",l!==1?"s":"",")"]})]})]},d.name))})}const kN=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],km=t=>`$${t.toLocaleString(void 0,{minimumFractionDigits:0,maximumFractionDigits:0})}`;function _N({active:t,payload:s,label:a,onUpdate:n}){if(t&&s?.length){const r={month:a,current:s.find(i=>i.dataKey==="current")?.value??null,previous:s.find(i=>i.dataKey==="previous")?.value??null};queueMicrotask(()=>n(r))}return null}function SN(){const{data:t,isLoading:s,isError:a}=Cv(),[n,r]=o.useState(null),i=o.useRef(null),l=o.useCallback(w=>{w.month!==i.current&&(i.current=w.month,r(w))},[]),m=o.useCallback(()=>{i.current=null,r(null)},[]);if(s)return e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(zs,{className:"h-4 w-4"})}),"Revenue pacing"]})}),e.jsx($,{children:e.jsx(Y,{className:"h-[300px] w-full"})})]});if(a||!t)return e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(zs,{className:"h-4 w-4"})}),"Revenue pacing"]})}),e.jsx($,{children:e.jsx("div",{className:"flex h-[300px] items-center justify-center text-sm text-muted-foreground",children:"Unable to load revenue pacing data."})})]});const c={},d={};for(const w of t.current_year){const v=parseInt(w.month.split("-")[1],10);c[v]=w.cumulative}for(const w of t.previous_year){const v=parseInt(w.month.split("-")[1],10);d[v]=w.cumulative}const u=Math.max(...Object.keys(c).map(Number),...Object.keys(d).map(Number),1),h=[];for(let w=1;w<=u;w++)h.push({month:kN[w-1],current:c[w]??null,previous:d[w]??null});if(!(t.current_year.length>0||t.previous_year.length>0))return e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy
1/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(zs,{className:"h-4 w-4"})}),"Revenue pacing"]})}),e.jsx($,{children:e.jsx("div",{className:"flex h-[300px] items-center justify-center text-sm text-muted-foreground",children:"No revenue data available yet."})})]});const x=Math.max(...Object.keys(c).map(Number),0),f=x>0?c[x]??0:0,b=x>0?d[x]??0:0,N=b>0?(f-b)/b*100:0,j=f>b;return e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsxs(ne,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(zs,{className:"h-4 w-4"})}),"Revenue pacing"]}),b>0&&e.jsxs("div",{className:`flex items-center gap-1 text-xs font-medium ${j?"text-emerald-600 dark:text-emerald-400":"text-red-600 dark:text-red-400"}`,children:[j?e.jsx(zs,{className:"h-3 w-3"}):e.jsx(Hn,{className:"h-3 w-3"}),e.jsxs("span",{children:[j?"+":"",N.toFixed(1),"% vs ",t.previous_year_label]})]})]}),e.jsx("p",{className:"h-4 pl-[60px] text-xs transition-opacity duration-150",children:n?e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx("span",{className:"font-normal text-muted-foreground/50",children:n.month}),e.jsx("span",{className:"text-muted-foreground/20",children:"|"}),e.jsxs("span",{className:"font-normal",style:{color:"#3b82f6"},children:[t.current_year_label,":"]}),e.jsx("span",{className:"font-medium",style:{color:"#3b82f6"},children:n.current!=null?km(n.current):"â"}),e.jsx("span",{className:"text-muted-foreground/20",children:"|"}),e.jsxs("span",{className:"font-normal",style:{color:"#94a3b8"},children:[t.previous_year_label,":"]}),e.jsx("span",{className:"font-medium",style:{color:"#94a3b8"},children:n.previous!=null?km(n.previous):"â"})]}):e.jsxs("span",{className:"text-muted-foreground",children:["Cumulative revenue: ",t.current_year_label," vs ",t.previous_year_label]})})]}),e.jsx($,{children:e.jsx("div",{className:"h-[300px] w-full",children:e.jsx(nn,{width:"100%",height:"100%",children:e.jsxs(Wp,{data:h,margin:{top:10,right:30,left:0,bottom:0},onMouseLeave:m,children:[e.jsx(Yl,{strokeDasharray:"3 3",vertical:!1,stroke:"hsl(var(--border))"}),e.jsx(_n,{dataKey:"month",tick:{fontSize:12,fill:"hsl(var(--muted-foreground))"},stroke:"hsl(var(--border))"}),e.jsx(rn,{tick:{fontSize:12,fill:"hsl(var(--muted-foreground))"},stroke:"hsl(var(--border))",tickFormatter:w=>`$${(w/1e3).toFixed(0)}k`}),e.jsx(ln,{content:e.jsx(_N,{onUpdate:l}),cursor:!1,isAnimationActive:!1}),n&&e.jsx(Vp,{x:n.month,stroke:"hsl(var(--muted-foreground))",strokeWidth:1,strokeDasharray:"4 3"}),e.jsx(Gp,{formatter:w=>w==="current"?t.current_year_label:t.previous_year_label}),e.jsx(di,{type:"monotone",dataKey:"previous",stroke:"#94a3b8",strokeWidth:2,strokeDasharray:"6 3",dot:!1,activeDot:{r:4,stroke:"#94a3b8",fill:"hsl(var(--card))",strokeWidth:2},connectNulls:!0}),e.jsx(di,{type:"monotone",dataKey:"current",stroke:"#3b82f6",strokeWidth:2.5,dot:{fill:"#3b82f6",r:3},activeDot:{r:5,stroke:"#3b82f6",fill:"hsl(var(--card))",strokeWidth:2},connectNulls:!0})]})})})})]})}const CN=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function PN(t){const s=[];for(let a=0;a<12;a++){const n=(t-1+a)%12;s.push(CN[n])}return s}const _m=t=>t.toLocaleString();function AN({active:t,payload:s,label:a,onUpdate:n}){if(t&&s?.length){const r={month:a,current:s.find(i=>i.dataKey==="current")?.value??null,previous:s.find(i=>i.dataKey==="previous")?.value??null};queueMicrotask(()=>n(r))}return null}function Cg(){const{data:t,isLoading:s,isError:a}=Gx(),[n,r]=o.useState(null),i=o.useRef(null),l=o.useCallback(v=>{v.month!==i.current&&(i.current=v.month,r(v))},[]),m=o.useCallback(()=>{i.current=null,r(null)},[]);if(s)return e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy
1/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(Lt,{className:"h-4 w-4"})}),"Member growth"]})}),e.jsx($,{children:e.jsx(Y,{className:"h-[300px] w-full"})})]});if(a||!t)return e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(Lt,{className:"h-4 w-4"})}),"Member growth"]})}),e.jsx($,{children:e.jsx("div",{className:"flex h-[300px] items-center justify-center text-sm text-muted-foreground",children:"Unable to load member growth data."})})]});const c=PN(t.cycle_start_month),d={},u={};t.current_year.forEach((v,k)=>{d[k]=v.total}),t.previous_year.forEach((v,k)=>{u[k]=v.total});const h=Math.max(t.current_year.length,t.previous_year.length,1),p=[];for(let v=0;v<h;v++)p.push({month:c[v]??`M${v+1}`,current:d[v]??null,previous:u[v]??null});if(!(t.current_year.length>0||t.previous_year.length>0))return e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(Lt,{className:"h-4 w-4"})}),"Member growth"]})}),e.jsx($,{children:e.jsx("div",{className:"flex h-[300px] items-center justify-center text-sm text-muted-foreground",children:"No membership data available yet."})})]});const f=t.current_year.length-1,b=f>=0?d[f]??0:0,N=f>=0?u[f]??0:0,j=N>0?(b-N)/N*100:0,w=b>N;return e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsxs(ne,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(Lt,{className:"h-4 w-4"})}),"Member growth"]}),N>0&&e.jsxs("div",{className:`flex items-center gap-1 text-xs font-medium ${w?"text-emerald-600 dark:text-emerald-400":"text-red-600 dark:text-red-400"}`,children:[w?e.jsx(zs,{className:"h-3 w-3"}):e.jsx(Hn,{className:"h-3 w-3"}),e.jsxs("span",{children:[w?"+":"",j.toFixed(1),"% vs ",t.previous_year_label]})]})]}),e.jsx("p",{className:"h-4 pl-[60px] text-xs transition-opacity duration-150",children:n?e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx("span",{className:"font-normal text-muted-foreground/50",children:n.month}),e.jsx("span",{className:"text-muted-foreground/20",children:"|"}),e.jsxs("span",{className:"font-normal",style:{color:"#3b82f6"},children:[t.current_year_label,":"]}),e.jsx("span",{className:"font-medium",style:{color:"#3b82f6"},children:n.current!=null?_m(n.current):"â"}),e.jsx("span",{className:"text-muted-foreground/20",children:"|"}),e.jsxs("span",{className:"font-normal",style:{color:"#94a3b8"},children:[t.previous_year_label,":"]}),e.jsx("span",{className:"font-medium",style:{color:"#94a3b8"},children:n.previous!=null?_m(n.previous):"â"})]}):e.jsxs("span",{className:"text-muted-foreground",children:["Total membership: ",t.current_year_label," vs ",t.previous_year_label]})})]}),e.jsx($,{children:e.jsx("div",{className:"h-[300px] w-full",children:e.jsx(nn,{width:"100%",height:"100%",children:e.jsxs(Wp,{data:p,margin:{top:10,right:30,left:0,bottom:0},onMouseLeave:m,children:[e.jsx(Yl,{strokeDasharray:"3 3",vertical:!1,stroke:"hsl(var(--border))"}),e.jsx(_n,{dataKey:"month",tick:{fontSize:12,fill:"hsl(var(--muted-foreground))"},stroke:"hsl(var(--border))"}),e.jsx(rn,{tick:{fontSize:12,fill:"hsl(var(--muted-foreground))"},stroke:"hsl(var(--border))",tickFormatter:v=>v.toLocaleString()}),e.jsx(ln,{content:e.jsx(AN,{onUpdate:l}),cursor:!1,isAnimationActive:!1}),n&&e.jsx(Vp,{x:n.month,stroke:"hsl(var(--muted-foreground))",strokeWidth:1,strokeDasharray:"4 3"}),e.jsx(Gp,{formatter:v=>v==="current"?t.current_year_label:t.previous_year_label}),e.jsx(di,{type:"monotone",dataKey:"previous",stroke:"#94a3b8",strokeWidth:2,strokeDasharray:"6 3",dot:!1,activeDot:{r:4,stroke:"#94a3b8",fill:"hsl(var(--card))",strokeWidth:2},connectNulls:!0}),e.jsx(di,{type:"monotone",dataKey:"current",stroke:"#3b82f6",strokeWidth:2.5,dot:{fill:"#3b82f6",r:3},activeDot:{r:5,stroke:"#3b82f6",fill:"hsl(var(--card))",strokeWidth:2},connectNulls:!0})]})})})})]})}function Ct(t){const s=t.includes("T"),a=/(?:Z|[+-]\d{2}:?\d{2})$/.test(t);return new Date(s&&!a?t+"Z":t)}function Ps(t){return t.includes("T")?Ct(t):new Date(t+"T00:00:00")}function kd(){const t=new Date,s=String(t.getMonth()+1).padStart(2,"0"),a=String(t.getDate()).padStart(2,"0");return`${t.getFullYear()}-${s}-${a}`}function _d(t,s=!1){return new Intl.DateTimeFormat("en-US",{timeZone:"UTC",month:"short",day:"numeric",year:"numeric",...s?{hour:"numeric",minute:"2-digit"}:{}}).format(Ct(t))}function Sm(t){if(!/^\d{4}-\d{2}-\d{2}$/.test(t))return!1;const s=new Date(`${t}T00:00:00Z`);return!Number.isNaN(s.getTime())&&s.toISOString().slice(0,10)===t}function Yn(t){const s=Math.min(Ct(t).getTime(),Date.now());return Yp(s,{addSuffix:!0})}function Pg({percentage:t,size:s=120,strokeWidth:a=10,colorOverride:n}){const r=(s-a)/2,i=2*Math.PI*r,l=i-Math.min(t,100)/100*i,m=n??(t>=80?"#10b981":t>=60?"#f59e0b":"#ef4444");return e.jsxs("div",{className:"relative shrink-0",style:{width:s,height:s},children:[e.jsxs("svg",{width:s,height:s,className:"-rotate-90",children:[e.jsx("circle",{cx:s/2,cy:s/2,r,fill:"none",stroke:"currentColor",strokeWidth:a,className:"text-muted/20"}),e.jsx("circle",{cx:s/2,cy:s/2,r,fill:"none",stroke:m,strokeWidth:a,strokeLinecap:"round",strokeDasharray:i,strokeDashoffset:l,style:{transition:"stroke-dashoffset 0.6s ease"}})]}),e.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center",children:[e.jsxs("span",{className:me("font-semibold tracking-tight",s<110?"text-lg":"text-2xl"),children:[t.toFixed(1),"%"]}),e.jsx("span",{className:"text-[10px] text-muted-foreground",children:"Renewed"})]})]})}function EN(t){const s=a=>Ps(a).toLocaleDateString("en-US",{month:"short",year:"numeric"});return`${s(t.cycle_start)} â ${s(t.cycle_end)}`}function Cm({delta:t,suffix:s}){return e.jsxs("div",{className:"mt-3 flex items-center gap-1.5 border-t pt-3 text-xs",children:[t>0?e.jsx(zs,{className:"h-3.5 w-3.5 text-emerald-600 dark:text-emerald-400"}):t<0?e.jsx(Hn,{className:"h-3.5 w-3.5 text-red-600 dark:text-red-400"}):null,e.jsxs("span",{className:t>0?"font-medium text-emerald-600 dark:text-emerald-400":t<0?"font-medium text-red-600 dark:text-red-400":"text-muted-foreground",children:[t>0?"+":"",t.toFixed(1),"pp"]}),e.jsx("span",{className:"text-muted-foreground",children:s})]})}function Pm({panel:t,title:s,isOpenPanel:a,inCampaign:n,closedRate:r,hasClosedData:i}){const l=a&&n;return e.jsxs("div",{className:"min-w-0 flex-1 px-5 pb-4 pt-1",children:[e.jsxs("div",{className:"mb-2.5 flex items-baseline justify-between gap-2",children:[e.jsx("span",{className:"text-[11px] font-semibold uppercase tracking-wider text-muted-foreground",children:s}),e.jsx("span",{className:"text-[11px] text-muted-foreground",children:EN(t)})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(Pg,{percentage:t.renew
1al_rate,size:96,strokeWidth:8,colorOverride:l?"#0ea5e9":void 0}),e.jsxs("div",{className:"min-w-0 flex-1 space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:l?"Renewed so far":"Renewed"}),e.jsx("span",{className:"font-semibold text-emerald-600 dark:text-emerald-400",children:t.renewed})]}),e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:a?n?"Not yet renewed":"Outstanding":"Did not renew"}),e.jsx("span",{className:me("font-semibold",!l&&"text-red-600 dark:text-red-400"),children:t.not_renewed})]}),a&&t.auto_renew_pending>0&&e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("span",{className:"flex items-center gap-1 text-muted-foreground",children:[e.jsx(Ar,{className:"h-3 w-3 text-amber-500"}),"Auto-renew queued"]}),e.jsx("span",{className:"font-semibold text-amber-600 dark:text-amber-400",children:t.auto_renew_pending})]}),e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:l?"Up for renewal":"Total due"}),e.jsx("span",{className:"font-semibold",children:t.total_due})]})]})]}),l&&t.pacing_prev_rate!==null&&e.jsx(Cm,{delta:t.renewal_rate-t.pacing_prev_rate,suffix:`vs this point last year (${t.pacing_prev_rate.toFixed(1)}%)`}),a&&!n&&i&&e.jsx(Cm,{delta:t.renewal_rate-r,suffix:`vs previous cycle (${r.toFixed(1)}%)`})]})}function Ui({children:t}){return e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(zs,{className:"h-4 w-4"})}),"Renewal progress"]})}),t]})}function TN(){const{data:t,isLoading:s,isError:a}=Rx();if(s)return e.jsx(Ui,{children:e.jsx($,{children:e.jsx(Y,{className:"h-[200px] w-full"})})});const n=t?.mode==="cycle"&&(!t.closed_cycle||!t.open_cycle||t.closed_cycle.total_due===0&&t.open_cycle.total_due===0),r=t?.mode!=="cycle"&&(t?.total_due??0)===0;if(a||!t||n||r)return e.jsx(Ui,{children:e.jsx($,{children:e.jsx("div",{className:"flex h-[200px] items-center justify-center text-sm text-muted-foreground",children:"No renewal data available yet."})})});if(t.mode==="cycle"&&t.closed_cycle&&t.open_cycle){const c=t.closed_cycle.total_due>0;return e.jsx(Ui,{children:e.jsxs("div",{className:"grid grid-cols-1 divide-y divide-border sm:grid-cols-2 sm:divide-x sm:divide-y-0",children:[e.jsx(Pm,{panel:t.closed_cycle,title:t.in_campaign?"Current cycle":"Previous cycle",isOpenPanel:!1,inCampaign:t.in_campaign,closedRate:0,hasClosedData:c}),e.jsx(Pm,{panel:t.open_cycle,title:t.in_campaign?"Upcoming cycle":"Current cycle",isOpenPanel:!0,inCampaign:t.in_campaign,closedRate:t.closed_cycle.renewal_rate,hasClosedData:c})]})})}const i=t.previous_cycle?.renewal_rate??0,l=t.renewal_rate-i,m=(t.previous_cycle?.total_due??0)>0;return e.jsx(Ui,{children:e.jsxs($,{children:[e.jsxs("div",{className:"flex items-center gap-6",children:[e.jsx(Pg,{percentage:t.renewal_rate}),e.jsxs("div",{className:"flex-1 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Renewed"}),e.jsx("span",{className:"text-sm font-semibold text-emerald-600 dark:text-emerald-400",children:t.renewed})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Outstanding"}),e.jsx("span",{className:"text-sm font-semibold text-red-600 dark:text-red-400",children:t.not_renewed})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Total due"}),e.jsx("span",{className:"text-sm font-semibold",children:t.total_due})]}),t.auto_renew_pending>0&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"flex items-center gap-1 text-sm text-muted-foreground",children:[e.jsx(Ar,{className:"h-3 w-3 text-amber-500"}),"Auto-renew queued"]}),e.jsx("span",{className:"text-sm font-semibold text-amber-600 dar
1k:text-amber-400",children:t.auto_renew_pending})]})]})]}),m&&e.jsxs("div",{className:"mt-4 flex items-center gap-1.5 border-t pt-3 text-xs",children:[l>0?e.jsx(zs,{className:"h-3.5 w-3.5 text-emerald-600 dark:text-emerald-400"}):l<0?e.jsx(Hn,{className:"h-3.5 w-3.5 text-red-600 dark:text-red-400"}):null,e.jsxs("span",{className:l>0?"font-medium text-emerald-600 dark:text-emerald-400":l<0?"font-medium text-red-600 dark:text-red-400":"text-muted-foreground",children:[l>0?"+":"",l.toFixed(1),"pp"]}),e.jsxs("span",{className:"text-muted-foreground",children:["vs previous cycle (",i.toFixed(1),"%)"]})]})]})})}const FN=[7,30,90],Eo={7:"next_7_days",30:"next_30_days",90:"next_90_days"};function RN(){const[t,s]=o.useState(30),[a,n]=o.useState(null),r=a??t,i=Ao(7),l=Ao(30),m=Ao(90),d={7:i,30:l,90:m}[r];if(l.isLoading)return e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(ea,{className:"h-4 w-4"})}),"Expiring soon"]})}),e.jsx($,{children:e.jsx("div",{className:"space-y-4",children:[...Array(5)].map((f,b)=>e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(Y,{className:"h-4 w-32"}),e.jsx(Y,{className:"h-3 w-48"})]}),e.jsx(Y,{className:"h-5 w-20"})]},b))})})]});const p=(d.data?.expiring_members||[]).slice(0,5),x=l.data?.[Eo[r]]??0;return e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsxs(ne,{className:"flex flex-row items-center justify-between pb-3",children:[e.jsxs("div",{children:[e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(ea,{className:"h-4 w-4"})}),"Expiring soon"]}),e.jsxs("p",{className:"mt-1 text-sm text-muted-foreground",children:[x," member",x!==1?"s":""," within ",r," days"]})]}),e.jsx("div",{className:"inline-flex overflow-hidden rounded-full border",onMouseLeave:()=>n(null),children:FN.map(f=>{const b=l.data?.[Eo[f]]??0,N=`${Eo[f]}_auto_renew`,j=l.data?.[N]??0,w=r===f;return e.jsxs(fs,{children:[e.jsx(ys,{asChild:!0,children:e.jsxs("button",{type:"button",className:`cursor-pointer px-2.5 py-0.5 text-xs font-semibold transition-colors ${w?"bg-primary text-primary-foreground":"text-foreground hover:bg-muted"}`,onMouseEnter:()=>n(f),onClick:()=>{s(f),n(null)},children:[b," in ",f,"d"]})}),j>0&&e.jsxs(hs,{children:[j," auto-renew"]})]},f)})})]}),e.jsx($,{children:p.length===0?e.jsxs("p",{className:"py-4 text-center text-sm text-muted-foreground",children:["No members expiring in the next ",r," days"]}):e.jsxs("div",{className:"space-y-4",children:[p.map(f=>e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(je,{to:`/members/${f.id}`,className:"font-medium hover:underline",children:f.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:f.email})]}),e.jsxs(fs,{children:[e.jsx(ys,{asChild:!0,children:e.jsxs("span",{className:"inline-flex cursor-default items-center gap-1.5 whitespace-nowrap",children:[e.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-muted-foreground/60"}),e.jsx("span",{className:"text-xs font-medium",children:Be(Ps(f.expires),"MMM d, yyyy")})]})}),e.jsx(hs,{children:"Membership expiration date"})]})]},f.id)),x>5&&e.jsxs(je,{to:`/members?expiring_within_days=${r}`,className:"block text-center text-sm text-muted-foreground hover:text-foreground",children:["View all ",x," members"]})]})})]})}const MN=[{days:90,label:"90d"},{days:180,label:"6mo"},{days:365,label:"12mo"}];function DN(){const[t,s]=o.useState(365),[a,n]=o.useState(null),r=a??t,i=ul(90),l=ul(180),m=ul(365),d={90:i,180:l,365:m}[r];if(m.isLoading)return e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy
1/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(tm,{className:"h-4 w-4"})}),"Lapsed recovery"]})}),e.jsx($,{children:e.jsxs("div",{className:"space-y-4",children:[e.jsx(Y,{className:"h-4 w-48"}),e.jsx(Y,{className:"h-3 w-full"}),[...Array(3)].map((j,w)=>e.jsxs("div",{className:"space-y-1",children:[e.jsx(Y,{className:"h-4 w-32"}),e.jsx(Y,{className:"h-3 w-48"})]},w))]})})]});const u=d.data,h=u?.total_lapsed??0,p=u?.recovered??0,x=u?.still_lapsed??0,f=u?.recovery_rate??0,b=(u?.still_lapsed_members??[]).slice(0,5),N=h>0?p/h*100:0;return e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsxs(ne,{className:"flex flex-row items-center justify-between pb-3",children:[e.jsxs("div",{children:[e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(tm,{className:"h-4 w-4"})}),"Lapsed recovery"]}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:h===0?"No lapsed members in this period":`${p} of ${h} recovered (${f}%)`})]}),e.jsx("div",{className:"inline-flex overflow-hidden rounded-full border",onMouseLeave:()=>n(null),children:MN.map(({days:j,label:w})=>{const v=r===j;return e.jsx("button",{type:"button",className:`cursor-pointer px-2.5 py-0.5 text-xs font-semibold transition-colors ${v?"bg-primary text-primary-foreground":"text-foreground hover:bg-muted"}`,onMouseEnter:()=>n(j),onClick:()=>{s(j),n(null)},children:w},j)})})]}),e.jsxs($,{children:[h>0&&e.jsxs("div",{className:"mb-4",children:[e.jsx("div",{className:"h-2.5 overflow-hidden rounded-full bg-muted",children:e.jsx("div",{className:"h-full rounded-full bg-emerald-500 transition-all duration-300",style:{width:`${N}%`}})}),e.jsxs("div",{className:"mt-1 flex justify-between text-xs text-muted-foreground",children:[e.jsxs("span",{children:[p," recovered"]}),e.jsxs("span",{children:[x," still lapsed"]})]})]}),b.length>0?e.jsxs("div",{className:"space-y-3",children:[e.jsxs("p",{className:"text-sm font-medium text-muted-foreground",children:["Still lapsed (",x,")"]}),b.map(j=>e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(je,{to:`/members/${j.id}`,className:"text-sm font-medium hover:underline",children:j.name}),e.jsx("p",{className:"text-xs text-muted-foreground",children:j.email})]}),e.jsxs("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:["Lapsed"," ",j.lapsed_date?Be(Ps(j.lapsed_date),"MMM d, yyyy"):"â"]})]},j.id)),x>5&&e.jsxs(je,{to:"/members?status=lapsed",className:"block text-center text-sm text-muted-foreground hover:text-foreground",children:["View all ",x," members"]})]}):h>0?e.jsx("p",{className:"py-4 text-center text-sm text-muted-foreground",children:"All lapsed members have been recovered"}):e.jsx("p",{className:"py-4 text-center text-sm text-muted-foreground",children:"No members became lapsed in this period"})]})]})}function LN({data:t,isLoading:s}){if(s)return e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(sm,{className:"h-4 w-4"})}),"Recent activity"]})}),e.jsx($,{children:e.jsx("div",{className:"space-y-4",children:[...Array(5)].map((n,r)=>e.jsxs("div",{className:"flex items-start space-x-3",children:[e.jsx(Y,{className:"mt-2 h-2 w-2 rounded-full"}),e.jsxs("div",{className:"flex-1 space-y-1",children:[e.jsx(Y,{className:"h-4 w-full"}),e.jsx(Y,{className:"h-3 w-24"})]})]},r))})})]});const a=t?.recent_activity?.slice(0,10)||[];return e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy
1/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(sm,{className:"h-4 w-4"})}),"Recent activity"]})}),e.jsx($,{children:a.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No recent activity"}):e.jsx("div",{className:"space-y-4",children:a.map((n,r)=>e.jsxs("div",{className:"flex items-start space-x-3",children:[e.jsx("div",{className:"mt-2 h-2 w-2 rounded-full bg-primary"}),e.jsxs("div",{className:"flex-1 space-y-1",children:[e.jsx("p",{className:"text-sm",children:n.description}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Hp(Ct(n.created_at),{addSuffix:!0})})]})]},r))})})]})}const $N=[{key:"active",label:"Active",color:"text-green-700 dark:text-green-400",bg:"bg-green-50 dark:bg-green-900/20"},{key:"pending",label:"Pending",color:"text-yellow-700 dark:text-yellow-400",bg:"bg-yellow-50 dark:bg-yellow-900/20"},{key:"grace",label:"Grace",color:"text-orange-700 dark:text-orange-400",bg:"bg-orange-50 dark:bg-orange-900/20"},{key:"lapsed",label:"Lapsed",color:"text-red-700 dark:text-red-400",bg:"bg-red-50 dark:bg-red-900/20"},{key:"expired",label:"Expired",color:"text-gray-500 dark:text-gray-400",bg:"bg-gray-50 dark:bg-gray-800/30"},{key:"cancelled",label:"Cancelled",color:"text-gray-500 dark:text-gray-400",bg:"bg-gray-50 dark:bg-gray-800/30"},{key:"suspended",label:"Suspended",color:"text-gray-500 dark:text-gray-400",bg:"bg-gray-50 dark:bg-gray-800/30"},{key:"rejected",label:"Rejected",color:"text-red-700 dark:text-red-400",bg:"bg-red-50 dark:bg-red-900/20"},{key:"archived",label:"Archived",color:"text-gray-400",bg:"bg-gray-50 dark:bg-gray-800/30"}];function qN(t,s){return t[s]>0}function IN({count:t,statusKey:s,color:a,membershipTypeId:n}){const r=kt();if(t===0)return e.jsx("span",{className:"text-muted-foreground",children:"0"});const i=new URLSearchParams({status:s});return n&&i.set("membership_type_id",n),e.jsx("button",{onClick:()=>r(`/members?${i.toString()}`),className:`font-semibold ${a} cursor-pointer hover:underline`,children:t.toLocaleString()})}function ON(){const{data:t,isLoading:s,isError:a}=E0();if(s)return e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(Lt,{className:"h-4 w-4"})}),"Membership overview"]})}),e.jsx($,{children:e.jsxs("div",{className:"space-y-3",children:[e.jsx(Y,{className:"h-8 w-full"}),e.jsx(Y,{className:"h-6 w-full"}),e.jsx(Y,{className:"h-6 w-full"}),e.jsx(Y,{className:"h-6 w-full"}),e.jsx(Y,{className:"h-6 w-full"})]})})]});if(a||!t)return e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(Lt,{className:"h-4 w-4"})}),"Membership overview"]})}),e.jsx($,{children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"Failed to load membership data."})})]});const n=$N.filter(r=>qN(t.totals,r.key));return t.by_type.length===0?e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(Lt,{className:"h-4 w-4"})}),"Membership overview"]})}),e.jsx($,{children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"No members found."})})]}):e.jsxs(L,{children:[e.jsxs(ne,{children:[e.jsx(ie,{children:"Membership overview"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"All statuses for real member types â includes cancelled/su
1spended/archived; guest/non-member types and members without a type are not shown. See Current roster below for the dashboard headline."})]}),e.jsxs($,{children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-muted/30",children:e.jsxs("tr",{className:"border-b",children:[e.jsx("th",{className:"py-2 pl-4 pr-4 text-left text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Member type"}),n.map(r=>e.jsx("th",{className:"px-3 py-2 text-right text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:r.label},r.key)),e.jsx("th",{className:"py-2 pl-3 pr-4 text-right text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Total"})]})}),e.jsx("tbody",{children:t.by_type.map(r=>{const i=n.reduce((l,m)=>l+r[m.key],0);return e.jsxs("tr",{className:"border-b transition-colors last:border-0 hover:bg-brand-navy/[0.04] dark:hover:bg-brand-navy/10",children:[e.jsx("td",{className:"py-2.5 pl-4 pr-4 font-medium",children:r.membership_type_name}),n.map(l=>e.jsx("td",{className:"px-3 py-2.5 text-right",children:e.jsx(IN,{count:r[l.key],statusKey:l.key,color:l.color,membershipTypeId:r.membership_type_id})},l.key)),e.jsx("td",{className:"py-2.5 pl-3 pr-4 text-right font-semibold",children:i.toLocaleString()})]},r.membership_type_id)})}),e.jsx("tfoot",{children:e.jsxs("tr",{className:"border-t-2 bg-muted/20",children:[e.jsx("td",{className:"py-2.5 pl-4 pr-4 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground",children:"Total (member types)"}),n.map(r=>e.jsx("td",{className:`px-3 py-2.5 text-right font-semibold ${r.color}`,children:t.totals[r.key].toLocaleString()},r.key)),e.jsx("td",{className:"py-2.5 pl-3 pr-4 text-right text-base font-semibold tracking-tight",children:t.totals.total.toLocaleString()})]})})]})}),e.jsxs("p",{className:"mt-2 text-xs text-muted-foreground",children:["Current roster: ",(t.totals.roster_total??0).toLocaleString()," â matches the dashboard headline (all non-terminal statuses, real member types)."]})]})]})}const Sd={getPreferences:()=>F.get("/auth/me/preferences").then(t=>t.data),postTourEvent:t=>F.post("/auth/me/tour-events",t).then(s=>s.data),patchPreferences:t=>F.patch("/auth/me/preferences",t).then(s=>s.data)};function Sl(t){return["onboarding-preferences",t]}function Ag(){const{user:t}=V();return re({queryKey:Sl(t?.id),queryFn:Sd.getPreferences,enabled:!!t})}function Eg(t){const{user:s,selectedSocietyId:a}=V(),n=J(),r=W({meta:{suppressErrorToast:!0},mutationFn:l=>Sd.postTourEvent({tour_id:t,event:l.event,step_index:l.stepIndex,total_steps:l.totalSteps,society_id:a??void 0}),onMutate:l=>{const m=l.event;m!=="completed"&&m!=="skipped"||n.setQueryData(Sl(s?.id),c=>{if(!c)return c;const d=c.tours[t];return m==="skipped"&&d?.status==="completed"?c:{...c,tours:{...c.tours,[t]:{status:m,at:new Date().toISOString(),step:l.stepIndex}}}})},onSuccess:l=>{n.setQueryData(Sl(s?.id),l)}}),{mutate:i}=r;return o.useCallback((l,m,c)=>{i({event:l,stepIndex:m,totalSteps:c})},[i])}function Cd(){const{user:t}=V(),s=J();return W({mutationFn:a=>Sd.patchPreferences(a),onSuccess:a=>{s.setQueryData(Sl(t?.id),a)}})}const Pd={dashboard:{id:"dashboard",path:"/dashboard",steps:[{selector:'[data-tour="stats-cards"]',title:"Your society at a glance",description:"Check your society's pulse here â members, expirations, and revenue update live.",placement:"bottom"},{selector:'[data-tour="sidebar-nav"]',title:"Everything lives here",description:"Jump to any area from the sidebar â start with Members.",desktopOnly:!0,placement:"right"},{selector:'[data-tour="member-search"]',title:"Find anyone fast",description:"Find any member in two keystrokes â try typing a name.",desktopOnly:!0,placement:"bottom"},{selector:'[data-tour="society-switcher"]',title:"Switch societies",description:"Jump between the societies you manage.",desktopOnly:!0,superAdminOnly:!0,placement:"right"},{selector:'[data-tour="nav-members"]',title:"Your member list",description:"Open Members to view, filter, and manage everyone in one place.",desktopOnly:!0,placement:"right"},{selector:'[data-tour="nav-group-admin"]',title:"Setup lives under Admin",description:"Stripe, email, imports, and settings live under Admin â the checklist below walks you through setup.",desktopOnly:!0,placement:"right"},{selector:'[data-tour="nav-group-commerce"]',title:"Events and commerce",description:"Create events, products, and donation campaigns under Commerce.",desktopOnly:!0,module:"commerce",placement:"right"}]},"connect-stripe":{id:"connect-stripe",path:"/settings?tab=integrations",steps:[{selector:'[data-tour="stripe-card"]',title:"Payments start here",description:"This is where payments come alive â Korevera charges through your own Stripe account.",placement:"bottom"},{selector:'[data-tour="stripe-keys-form"]',title:"Add your keys",description:"Paste your publishable and secret keys from the Stripe dashboard, then Save keys and Test connection.",placement:"top"}]},"membership-types":{id:"membership-types",path:"/membership-types",steps:[{selector:'[data-tour="mt-list"]',title:"Membership types",description:"Membership types define who your members are and what they pay.",placement:"bottom"},{selector:'[data-tour="mt-create-btn"]',title:"Create your first type",description:"Create your first type â the form takes it from there.",placement:"bottom"}]},"email-templates":{id:"email-templates",path:"/emails/templates",steps:[{selector:'[data-tour="templates-list"]',title:"Emails your members receive",description:"These are the emails your members receive â the defaults work, but they don't sound like you yet.",placement:"top"},{selector:'[data-tour="template-section"]',title:"Make one yours",description:"Expand a section and click a template's name to open the editor â customizing one completes this step.",placement:"bottom"}]},"renewal-sequence":{id:"renewal-sequence",path:"/emails/renewals",steps:[{selector:'[data-tour="renewal-steps"]',title:"Automatic renew
1al reminders",description:"These emails go out automatically as renewals approach.",placement:"top"},{selector:'[data-tour="renewal-add-step"]',title:"Schedule the first reminder",description:"Add a step to schedule your first reminder â the form takes it from there.",placement:"bottom"}]},"upload-logo":{id:"upload-logo",path:"/settings?tab=branding",steps:[{selector:'[data-tour="logo-upload"]',title:"Your logo, everywhere",description:"Your logo appears on the portal, emails, and invoices â upload a PNG or JPEG here.",placement:"bottom"}]},"add-members":{id:"add-members",path:"/members",steps:[{selector:'[data-tour="members-add-btn"]',title:"Add your first member",description:"Add members one at a time here â the form takes it from there.",placement:"bottom"},{selector:'[data-tour="nav-group-admin"]',title:"Or import a roster",description:"Have a spreadsheet? Open Admin â Import/export to bring in your whole roster.",desktopOnly:!0,placement:"right"}]},"invoice-settings":{id:"invoice-settings",path:"/settings?tab=general",steps:[{selector:'[data-tour="invoice-settings"]',title:"Invoice details",description:"Set who checks are payable to â it prints on every invoice.",placement:"bottom"}]},"phone-orders":{id:"phone-orders",path:"/events",steps:[{selector:'[data-tour="event-registrants"]',title:"Open an event's registrants",description:"Click the registrants icon on an event to see who is signed up.",placement:"left",advanceOnTargetClick:!0},{selector:'[data-tour="add-registrations-btn"]',title:"Start a batch",description:"Click Add registrations to start registering people by phone.",placement:"bottom",waitForSelector:!0,advanceOnTargetClick:!0},{selector:'[data-tour="reg-member-search"]',title:"Pick your registrants",description:"Search and add up to 25 members to this batch. When the event has child sessions, an add-on checkbox appears under each registrant so you can include them too.",placement:"top",waitForSelector:!0},{selector:'[data-tour="reg-forms"]',title:"Fill each required form",description:"Every registrant's required questions appear here. Fill them in, then click the wizard's Review pricing button â the tour follows along automatically.",placement:"top",waitForSelector:!0},{selector:'[data-tour="reg-review"]',title:"Review the pricing",description:"Each line shows its resolved rate. Type a new amount to override a price (a reason is required), or set it to $0 to comp the registration.",placement:"top",waitForSelector:!0},{selector:'[data-tour="reg-payment"]',title:"Take payment",description:"Key in a card, or charge a member's card on file. The attestation checkbox confirms the payer authorized charging their saved card.",placement:"top",waitForSelector:!0}]}};function Tg(t){return t in Pd}function Fg(t){const s=Pd[t],[a,n=""]=s.path.split("?"),r=new URLSearchParams(n);return r.set("tour",t),`${a}?${r.toString()}`}function Rg({forceVisible:t=!1}){const{data:s,isLoading:a}=Fx(),{selectedSocietyId:n}=V(),r=J(),i=Cd(),[l,m]=o.useState(!1),c=()=>i.mutate({checklist_dismissed:{society_id:n,dismissed:!0}},{onSuccess:()=>{r.invalidateQueries({queryKey:["setup-status"]}),Ut.success("Hidden â reopen anytime from Help")}});if(a||!s||s.dismissed&&!t)return null;const d=s.items.filter(x=>!x.platform_only),u=d.filter(x=>x.configured).length,h=d.length,p=h>0?Math.round(u/h*100):0;return e.jsxs(L,{className:s.all_complete?"min-w-0 overflow-hidden border-emerald-200 bg-emerald-50/50 dark:border-emerald-800 dark:bg-emerald-950/20":"min-w-0 overflow-hidden",children:[e.jsxs(ne,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(Yc,{className:"h-4 w-4"})}),"Setup checklist"]}),e.jsx("span",{className:"text-sm text-muted-foreground",children:s.all_complete?"Nice work â you're fully set up":`${u} of ${h} complete`})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(g,{variant:"ghost",size:"sm",className:"text-xs text-muted-foreground",onClick:c,disabled:i.isPending,children:"Dismiss"}),!s.all_complete&&e.jsx(g,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>m(!l),children:l?e.jsx(ps,{className:"h-4 w-4"}):e.jsx(Gn,{className:"h-4 w-4"})})]})]}),!s.all_complete&&e.jsx("div",{className:"mt-2 h-1.5 w-full overflow-hidden rounded-full bg-muted",children:e.jsx("div",{className:"h-full rounded-full bg-primary transition-all",style:{width:`${p}%`}})})]}),!l&&!s.all_complete&&e.jsx($,{className:"pt-0",children:e.jsx("ul",{className:"space-y-2",children:d.map(x=>e.jsxs("li",{className:"flex items-center justify-between gap-2 text-sm",children:[e.jsx("span",{className:"flex min-w-0 items-center gap-2",children:x.configured?e.jsxs(e.Fragment,{children:[e.jsx(Kt,{className:"h-4 w-4 shrink-0 text-emerald-600 dark:text-emerald-400"}),e.jsx("span",{className:"truncate text-muted-foreground line-through",children:x.label})]}):e.jsxs(e.Fragment,{children:[e.jsx(Bl,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),e.jsx(je,{to:x.url,className:"truncate text-primary hover:underline",children:x.label})]})}),!x.configured&&x.tour_id&&Tg(x.tour_id)&&e.jsxs(je,{to:Fg(x.tour_id),className:"flex shrink-0 items-center gap-1 rounded px-2 py-1 text-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",children:[e.jsx(jr,{className:"h-3 w-3"}),"Show me"]})]},x.key))})})]})}function UN(){const{data:t,isLoading:s}=Mx(),a=Dx(),[n,r]=o.useState(!1);return s||!t||!t.has_demo_data?null:e.jsxs(e.Fragment,{children:[e.jsxs(L,{className:"min-w-0 overflow-hidden border-dashed border-amber-300 bg-amber-50/50 dark:border-amber-700 dark:bg-amber-950/20",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy
1/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(jp,{className:"h-4 w-4"})}),"Demo data active"]})}),e.jsx($,{children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-3 gap-3 sm:grid-cols-6",children:[e.jsx(or,{label:"Members",count:t.counts.members}),e.jsx(or,{label:"Events",count:t.counts.events}),e.jsx(or,{label:"Polls",count:t.counts.polls}),e.jsx(or,{label:"Committees",count:t.counts.committees}),e.jsx(or,{label:"Announcements",count:t.counts.announcements}),e.jsx(or,{label:"Campaigns",count:t.counts.campaigns})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(g,{variant:"outline",size:"sm",className:"border-red-300 text-red-600 hover:bg-red-50 hover:text-red-700 dark:border-red-700 dark:text-red-400 dark:hover:bg-red-950/30 dark:hover:text-red-300",onClick:()=>r(!0),disabled:a.isPending,children:[a.isPending?e.jsx(He,{className:"mr-1 h-4 w-4 animate-spin"}):e.jsx(Ft,{className:"mr-1 h-4 w-4"}),"Clear demo data"]}),a.isError&&e.jsx("span",{className:"text-sm text-red-600",children:a.error?.message||"Failed to clear"})]})]})})]}),e.jsx(Fe,{open:n,onOpenChange:r,children:e.jsxs(Te,{children:[e.jsxs(Ae,{children:[e.jsx(Ee,{children:"Clear demo data?"}),e.jsx(tt,{children:"This will permanently delete all demo members, payments, events, polls, committees, and announcements. Real data is not affected."})]}),e.jsxs(Ge,{children:[e.jsx(g,{variant:"outline",onClick:()=>r(!1),children:"Cancel"}),e.jsx(g,{variant:"destructive",onClick:()=>{a.mutate(),r(!1)},children:"Clear all demo data"})]})]})})]})}function or({label:t,count:s}){return e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"text-lg font-semibold tracking-tight",children:s}),e.jsx("div",{className:"text-xs text-muted-foreground",children:t})]})}const Mg={list:async(t,s=1,a=20,n)=>{const r={page:s,size:a};t&&(r.society_id=t),n&&(r.status=n);const{data:i}=await F.get("/disputes",{params:r});return i},summary:async t=>{const s={};t&&(s.society_id=t);const{data:a}=await F.get("/disputes/summary",{params:s});return a},get:async(t,s)=>{const a={};s&&(a.society_id=s);const{data:n}=await F.get(`/disputes/${t}`,{params:a});return n}};function zN(t=1,s=20,a){const{selectedSocietyId:n}=V();return re({queryKey:["disputes",n,t,s,a],queryFn:()=>Mg.list(n||void 0,t,s,a),enabled:!!n})}function Dg(){const{selectedSocietyId:t}=V();return re({queryKey:["dispute-summary",t],queryFn:()=>Mg.summary(t||void 0),enabled:!!t})}function BN(){const{data:t,isLoading:s}=Dg(),a=kt();if(s||!t||t.open_count===0)return null;const n=new Intl.NumberFormat("en-US",{style:"currency",currency:"USD"}).format(Number(t.total_disputed));return e.jsx(L,{className:"min-w-0 overflow-hidden border-red-300 bg-red-50/50 dark:border-red-700 dark:bg-red-950/20",children:e.jsx($,{className:"py-4",children:e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Bt,{className:"h-5 w-5 shrink-0 text-red-600"}),e.jsxs("div",{children:[e.jsxs("p",{className:"font-semibold text-red-800 dark:text-red-200",children:[t.open_count," open dispute",t.open_count!==1?"s":""," â ",n," at risk"]}),e.jsx("p",{className:"text-sm text-red-600 dark:text-red-400",children:"Respond before the evidence deadline to avoid losing funds"})]})]}),e.jsx(g,{variant:"outline",size:"sm",className:"shrink-0 border-red-300 text-red-700 hover:bg-red-100 dark:border-red-700 dark:text-red-400 dark:hover:bg-red-950/30",onClick:()=>a("/disputes"),children:"View disputes"})]})})})}function KN(){const{data:t,isLoading:s}=eo();if(s)return e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(St,{className:"h-4 w-4"})}),"Auto-renew adoption"]})}),e.jsxs($,{children:[e.jsx(Y,{className:"mb-2 h-6 w-24"}),e.jsx(Y,{className:"h-3 w-full"})]})]});const a=t?.membership?.auto_renew_count??0,n=t?.membership?.active_members??0,r=n>0?Math.round(a/n*100):0,i=r>=60?"bg-emerald-500":r>=30?"bg-amber-500":"bg-red-500",l=r>=60?"text-emerald-600 dark:text-emerald-400":r>
1=30?"text-amber-600 dark:text-amber-400":"text-red-600 dark:text-red-400";return e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(St,{className:"h-4 w-4"})}),"Auto-renew adoption"]})}),e.jsxs($,{children:[e.jsxs("div",{className:`text-2xl font-semibold tracking-tight ${l}`,children:[r,"%"]}),e.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:[a.toLocaleString()," of ",n.toLocaleString()," active members"]}),e.jsx("div",{className:"mt-3 h-2 overflow-hidden rounded-full bg-muted",children:e.jsx("div",{className:`h-full rounded-full transition-all ${i}`,style:{width:`${Math.min(r,100)}%`}})}),e.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:r>=60?"Strong adoption â next cycle retention is well-secured":r>=30?"Moderate adoption â room to grow auto-renew enrollment":"Low adoption â consider promoting auto-renew benefits"})]})]})}const QN=qc("inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground hover:bg-primary/80",secondary:"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",destructive:"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",outline:"text-foreground",success:"border-transparent bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400",warning:"border-transparent bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-400"}},defaultVariants:{variant:"default"}});function Ts({className:t,variant:s,...a}){return e.jsx("div",{className:me(QN({variant:s}),t),...a})}function WN(){const{data:t,isLoading:s}=Pv();return s?e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-amber-100 text-amber-600 dark:bg-amber-900/30 dark:text-amber-400",children:e.jsx(Dt,{className:"h-4 w-4"})}),"At-risk members"]})}),e.jsx($,{className:"space-y-3",children:[...Array(3)].map((a,n)=>e.jsx(Y,{className:"h-10 w-full"},n))})]}):!t||t.count===0?e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-amber-100 text-amber-600 dark:bg-amber-900/30 dark:text-amber-400",children:e.jsx(Dt,{className:"h-4 w-4"})}),"At-risk members"]})}),e.jsx($,{children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"No members at risk of lapsing"})})]}):e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-amber-100 text-amber-600 dark:bg-amber-900/30 dark:text-amber-400",children:e.jsx(Dt,{className:"h-4 w-4"})}),"At-risk members"]}),e.jsxs(Ts,{variant:"destructive",className:"text-xs",children:[t.count," at risk"]})]})}),e.jsxs($,{children:[e.jsx("p",{className:"mb-3 text-xs text-muted-foreground",children:"Expiring within 30 days, no auto-renew enabled"}),e.jsx("div",{className:"max-h-64 space-y-2 overflow-y-auto",children:t.members.map(a=>e.jsxs("div",{className:"flex items-center justify-between rounded-md border px-3 py-2 text-sm",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate font-medium",children:a.name}),e.jsx("p",{className:"truncate text-xs text-muted-foreground",children:a.email})]}),e.jsxs("div",{className:"ml-3 shrink-0 text-right",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5 whitespace-nowrap",children:[e.jsx("span",{className:`h-1.5 w-1.5 shrink-0 rounded-full ${a.days_until_expiry<=7?"bg-red-500":"bg-amber-500"}`}),e.jsxs("span",{className:"text-xs font-medium",children:[a.days_until_expiry,"d left"]})]}),a.membership_type&&e.jsx("p",{className:"mt-0.5 text-xs text-muted-foreground",children:a.membership_type})]})]},a.id))}),t.count>t.members.length&&e.jsxs("p",{className:"mt-2 text-center text-xs text-muted-foreground",children:["Showing ",t.members.length," of ",t.count," at-risk members"]})]})]})}function VN(){const{data:t,isLoading:s}=Ev();if(s)return e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy
1/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(St,{className:"h-4 w-4"})}),"MTD renewals"]})}),e.jsxs($,{children:[e.jsx(Y,{className:"mb-2 h-8 w-20"}),e.jsx(Y,{className:"h-3 w-full"})]})]});if(!t)return null;const a=t.count-t.last_month,n=t.count-t.same_month_last_year;return e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(St,{className:"h-4 w-4"})}),"MTD renewals"]})}),e.jsxs($,{children:[e.jsx("div",{className:"text-3xl font-semibold tracking-tight",children:t.count}),e.jsxs("div",{className:"mt-3 space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-1 text-sm",children:[a>0?e.jsx(yl,{className:"h-4 w-4 text-emerald-600 dark:text-emerald-400"}):a<0?e.jsx(fc,{className:"h-4 w-4 text-red-600 dark:text-red-400"}):e.jsx(am,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{className:a>0?"text-emerald-600 dark:text-emerald-400":a<0?"text-red-600 dark:text-red-400":"text-muted-foreground",children:[Math.abs(a)," vs last month"]}),e.jsxs("span",{className:"text-muted-foreground",children:["(",t.last_month,")"]})]}),e.jsxs("div",{className:"flex items-center gap-1 text-sm",children:[n>0?e.jsx(yl,{className:"h-4 w-4 text-emerald-600 dark:text-emerald-400"}):n<0?e.jsx(fc,{className:"h-4 w-4 text-red-600 dark:text-red-400"}):e.jsx(am,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{className:n>0?"text-emerald-600 dark:text-emerald-400":n<0?"text-red-600 dark:text-red-400":"text-muted-foreground",children:[Math.abs(n)," vs same month last year"]}),e.jsxs("span",{className:"text-muted-foreground",children:["(",t.same_month_last_year,")"]})]})]})]})]})}function GN(){const{data:t,isLoading:s}=Tv(),a=kt();return s?e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-red-100 text-red-600 dark:bg-red-900/30 dark:text-red-400",children:e.jsx(Dt,{className:"h-4 w-4"})}),"Failed auto-renewals"]})}),e.jsx($,{className:"space-y-3",children:[...Array(3)].map((n,r)=>e.jsx(Y,{className:"h-10 w-full"},r))})]}):!t||t.count===0?e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-red-100 text-red-600 dark:bg-red-900/30 dark:text-red-400",children:e.jsx(Dt,{className:"h-4 w-4"})}),"Failed auto-renewals"]})}),e.jsx($,{children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"No failed auto-renewals"})})]}):e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-red-100 text-red-600 dark:bg-red-900/30 dark:text-red-400",children:e.jsx(Dt,{className:"h-4 w-4"})}),"Failed auto-renewals"]}),e.jsx(Ts,{variant:"destructive",className:"text-xs",children:t.count})]})}),e.jsxs($,{children:[e.jsx("div",{className:"max-h-64 space-y-2 overflow-y-auto",children:t.members.slice(0,5).map(n=>e.jsxs("div",{className:"flex cursor-pointer items-center justify-between rounded-md border px-3 py-2 text-sm transition-colors hover:bg-muted/50",onClick:()=>a(`/members/${n.member_id}`),children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("p",{className:"truncate font-medium",children:[n.first_name," ",n.last_name]}),n.membership_type&&e.jsx("p",{className:"truncate text-xs text-muted-foreground",children:n.membership_type})]}),e.jsxs("div",{className:"ml-3 shrink-0 text-right",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5 whitespace-nowrap",children:[e.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-red-500"}),e.jsxs("span",{className:"text-xs font-medium",children:[n.days_since_failure,"d ago"]})]}),e.jsxs("p",{className:"mt-0.5 text-xs text-muted-foreground",children:[n.retry_count," ",n.retry_count===1?"retry":"retries"]})]})]},n.member_id))}),t.count>5&&e.jsxs("p",{className:"mt-2 text-center text-xs text-muted-foreground",children:["Showing 5 of ",t.count," failed renewals"]})]})]})}const Am=["bg-emerald-500","bg-amber-500","bg-orange-500","bg-red-500","bg-red-800"];function YN(){const{selectedSocietyId:t}=V(),{data:s,isLoading:a}=re({queryKey:["ar-aging",t],queryFn:()=>Ns.arAging(t||void 0),enabled:!!t});if(a)return e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy
1/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(ea,{className:"h-4 w-4"})}),"A/R aging"]})}),e.jsxs($,{children:[e.jsx(Y,{className:"mb-3 h-6 w-32"}),e.jsx(Y,{className:"mb-3 h-6 w-full"}),e.jsx(Y,{className:"h-16 w-full"})]})]});if(!s)return null;const n=s.total_outstanding,r=s.buckets.filter(i=>i.total_amount>0);return e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(ea,{className:"h-4 w-4"})}),"A/R aging"]})}),e.jsxs($,{children:[e.jsxs("div",{className:"text-2xl font-semibold tracking-tight",children:["$",n.toLocaleString(void 0,{minimumFractionDigits:2,maximumFractionDigits:2})]}),e.jsxs("p",{className:"mb-3 text-xs text-muted-foreground",children:[s.total_invoice_count," outstanding"," ",s.total_invoice_count===1?"invoice":"invoices"]}),r.length>0&&e.jsx("div",{className:"mb-3 flex h-6 overflow-hidden rounded-full",children:s.buckets.map((i,l)=>{if(i.total_amount===0)return null;const m=i.total_amount/n*100;return e.jsx("div",{className:`${Am[l]||"bg-gray-500"} transition-all`,style:{width:`${m}%`},title:`${i.label}: $${i.total_amount.toLocaleString(void 0,{minimumFractionDigits:2})}`},i.label)})}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:s.buckets.map((i,l)=>e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx("div",{className:`h-3 w-3 shrink-0 rounded-full ${Am[l]||"bg-gray-500"}`}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("span",{className:"text-muted-foreground",children:i.label}),e.jsxs("span",{className:"ml-1 font-medium",children:["$",i.total_amount.toLocaleString(void 0,{minimumFractionDigits:2,maximumFractionDigits:2})]})]})]},i.label))})]})]})}function HN(){const{data:t,isLoading:s}=Fv(),{data:a}=Qs(),n=kt();if(s)return e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(nm,{className:"h-4 w-4"})}),"Pending actions"]})}),e.jsx($,{className:"space-y-2",children:[...Array(4)].map((m,c)=>e.jsx(Y,{className:"h-10 w-full"},c))})]});if(!t)return null;const r=a?.settings?.committees_enabled===!0,i=t.items.filter(m=>!(!r&&m.label==="Committee Applications")),l=i.reduce((m,c)=>m+c.count,0);return e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(nm,{className:"h-4 w-4"})}),"Pending actions"]}),l>0&&e.jsx(Ts,{variant:"secondary",className:"text-xs",children:l})]})}),e.jsx($,{children:e.jsx("div",{className:"space-y-1",children:i.map(m=>e.jsxs("div",{className:`flex cursor-pointer items-center justify-between rounded-md px-3 py-2 text-sm transition-colors hover:bg-muted/50 ${m.count===0?"opacity-50":""}`,onClick:()=>n(m.link),children:[e.jsx("span",{className:"font-medium",children:m.label}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ts,{variant:m.count>0?"default":"secondary",className:"text-xs",children:m.count}),e.jsx(ts,{className:"h-4 w-4 text-muted-foreground"})]})]},m.label))})})]})}function JN(){const{data:t,isLoading:s}=Rv();if(s)return e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy
1/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx($t,{className:"h-4 w-4"})}),"Email health"]})}),e.jsx($,{children:e.jsx("div",{className:"grid grid-cols-2 gap-3",children:[...Array(4)].map((r,i)=>e.jsx(Y,{className:"h-16 w-full"},i))})})]});if(!t)return null;const a=t.total_sent>0,n=a?t.delivery_rate>=95?"text-emerald-600 dark:text-emerald-400":t.delivery_rate>=90?"text-amber-600 dark:text-amber-400":"text-red-600 dark:text-red-400":"text-muted-foreground";return e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx($t,{className:"h-4 w-4"})}),"Email health"]})}),e.jsxs($,{children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"rounded-md border p-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Delivery rate"}),e.jsx("p",{className:`text-xl font-semibold tracking-tight ${n}`,children:a?`${t.delivery_rate.toFixed(1)}%`:"â"})]}),e.jsxs("div",{className:"rounded-md border p-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Bounce rate"}),e.jsxs("p",{className:"text-xl font-semibold tracking-tight",children:[t.bounce_rate.toFixed(1),"%"]})]}),e.jsxs("div",{className:"rounded-md border p-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Complaint rate"}),e.jsxs("p",{className:"text-xl font-semibold tracking-tight",children:[t.complaint_rate.toFixed(2),"%"]})]}),e.jsxs("div",{className:"rounded-md border p-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Suppressions"}),e.jsx("p",{className:"text-xl font-semibold tracking-tight",children:t.suppression_count.toLocaleString()})]})]}),e.jsxs("p",{className:"mt-3 text-center text-xs text-muted-foreground",children:[t.total_sent.toLocaleString()," emails sent (30 days)",t.blocked>0&&e.jsxs("span",{className:"text-amber-600 dark:text-amber-400",children:[" ","· ",t.blocked.toLocaleString()," blocked (suppressed)"]}),t.failed>0&&e.jsxs("span",{className:"text-red-600 dark:text-red-400",children:[" ","· ",t.failed.toLocaleString()," failed to send"]})]})]})]})}function ZN(){const{data:t,isLoading:s}=Mv();if(s)return e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx($t,{className:"h-4 w-4"})}),"Renewal email funnel"]})}),e.jsx($,{className:"space-y-3",children:[...Array(4)].map((n,r)=>e.jsx(Y,{className:"h-12 w-full"},r))})]});if(!t||t.steps.length===0)return e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx($t,{className:"h-4 w-4"})}),"Renewal email funnel"]})}),e.jsx($,{children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"No renewal sequence data"})})]});const a=Math.max(...t.steps.map(n=>n.emails_sent),1);return e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx($t,{className:"h-4 w-4"})}),"Renewal email funnel"]}),e.jsxs(Ts,{variant:"secondary",className:"text-xs",children:[t.total_renewals," renewed"]})]})}),e.jsx($,{children:e.jsx("div",{className:"space-y-3",children:t.steps.map(n=>{const r=n.emails_sent/a*100;return e.jsxs("div",{children:[e.jsx("div",{className:"mb-1 flex items-center justify-between text-sm",children:e.jsx("span",{className:"truncate font-medium",children:n.step_name})}),e.jsx("div",{className:"relative h-4 overflow-hidden rounded bg-muted",children:e.jsx("div",{className:"h-full rounded bg-blue-500 transition-all",style:{width:`${r}%`}})}),e.jsxs("div",{className:"mt-1 flex gap-3 text-xs text-muted-foreground",children:[e.jsxs("span",{children:["Sent: ",n.emails_sent]}),e.jsxs("span",{children:["Delivered: ",n.emails_delivered]}),e.jsxs("span",{children:["Renewed: ",n.renewals_attributed]})]})]}
1,n.step_name)})})})]})}function XN(){const{selectedSocietyId:t}=V(),{data:s,isLoading:a}=re({queryKey:["retention",t],queryFn:()=>Ns.retention(t||void 0),enabled:!!t});if(a)return e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(Sa,{className:"h-4 w-4"})}),"Cohort retention"]})}),e.jsxs($,{children:[e.jsx(Y,{className:"mb-3 h-6 w-24"}),[...Array(4)].map((r,i)=>e.jsx(Y,{className:"mb-2 h-8 w-full"},i))]})]});if(!s)return null;const n=s.retention_rate>=80?"text-emerald-600 dark:text-emerald-400":s.retention_rate>=60?"text-amber-600 dark:text-amber-400":"text-red-600 dark:text-red-400";return e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(Sa,{className:"h-4 w-4"})}),"Cohort retention"]}),e.jsxs("span",{className:`text-lg font-semibold tracking-tight ${n}`,children:[s.retention_rate.toFixed(1),"%"]})]})}),e.jsx($,{children:s.cohorts.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No cohort data available"}):e.jsx("div",{className:"space-y-2",children:s.cohorts.map(r=>{const i=r.started===0,l=r.rate>=80?"bg-emerald-500":r.rate>=60?"bg-amber-500":"bg-red-500";return e.jsxs("div",{children:[e.jsxs("div",{className:"mb-1 flex items-center justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:r.period}),e.jsx("span",{className:"font-medium",children:i?e.jsx("span",{className:"text-muted-foreground",children:"â"}):e.jsxs(e.Fragment,{children:[r.retained,"/",r.started," (",r.rate.toFixed(0),"%)"]})})]}),e.jsx("div",{className:"h-2 overflow-hidden rounded-full bg-muted",children:e.jsx("div",{className:`h-full rounded-full transition-all ${l}`,style:{width:`${Math.min(r.rate,100)}%`}})})]},r.period)})})})]})}function ek(){const{data:t,isLoading:s}=Lv();if(s)return e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(zs,{className:"h-4 w-4"})}),"Membership type trends"]})}),e.jsx($,{children:e.jsx(Y,{className:"h-32 w-full"})})]});if(!t)return null;if(!t.has_sufficient_data)return e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(zs,{className:"h-4 w-4"})}),"Membership type trends"]})}),e.jsx($,{children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"Collecting data â trends will appear once there are at least 2 months of snapshots."})})]});const a=[...new Set(t.data_points.map(i=>i.month))].sort(),n=[...new Set(t.data_points.map(i=>i.type_name))].sort(),r=new Map;for(const i of t.data_points)r.set(`${i.type_name}|${i.month}`,i.active_count);return e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy
1/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(zs,{className:"h-4 w-4"})}),"Membership type trends"]})}),e.jsx($,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-muted/30",children:e.jsxs("tr",{className:"border-b",children:[e.jsx("th",{className:"h-10 px-4 text-left text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Type"}),a.map(i=>e.jsx("th",{className:"h-10 whitespace-nowrap px-4 text-right text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:i},i))]})}),e.jsx("tbody",{children:n.map(i=>e.jsxs("tr",{className:"border-b transition-colors last:border-0 hover:bg-brand-navy/[0.04] dark:hover:bg-brand-navy/10",children:[e.jsx("td",{className:"max-w-[150px] truncate py-2 pl-4 pr-4 font-medium",children:i}),a.map(l=>e.jsx("td",{className:"px-4 py-2 text-right",children:r.get(`${i}|${l}`)??0},l))]},i))})]})})})]})}function tk(){const{data:t,isLoading:s}=Dv();return s?e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(Yt,{className:"h-4 w-4"})}),"Event fill rates"]})}),e.jsx($,{className:"space-y-3",children:[...Array(3)].map((a,n)=>e.jsx(Y,{className:"h-10 w-full"},n))})]}):!t||t.events.length===0?e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(Yt,{className:"h-4 w-4"})}),"Event fill rates"]})}),e.jsx($,{children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"No upcoming events"})})]}):e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(Yt,{className:"h-4 w-4"})}),"Event fill rates"]})}),e.jsx($,{children:e.jsx("div",{className:"max-h-64 space-y-3 overflow-y-auto",children:t.events.map(a=>e.jsxs("div",{children:[e.jsxs("div",{className:"mb-1 flex items-center justify-between text-sm",children:[e.jsx("span",{className:"truncate font-medium",children:a.event_name}),e.jsxs("span",{className:"ml-2 shrink-0 text-muted-foreground",children:[a.registration_count,a.capacity!=null&&` / ${a.capacity}`]})]}),a.capacity!=null?e.jsx("div",{className:"h-2 overflow-hidden rounded-full bg-muted",children:e.jsx("div",{className:`h-full rounded-full transition-all ${(a.fill_percent??0)>=90?"bg-red-500":(a.fill_percent??0)>=70?"bg-amber-500":"bg-blue-500"}`,style:{width:`${Math.min(a.fill_percent??0,100)}%`}})}):e.jsx("p",{className:"text-xs text-muted-foreground",children:"Unlimited capacity"})]},a.event_id))})})]})}function Em(t){return typeof t!="string"?null:/filename="?([^"]+)"?/.exec(t)?.[1]??null}const Wt={getEvents:async t=>(await F.get("/commerce/events",{params:{society_id:t}})).data,createEvent:async(t,s)=>(await F.post("/commerce/events",t,{params:{society_id:s}})).data,createEventWithChildren:async(t,s)=>(await F.post("/commerce/events/with-children",t,{params:{society_id:s}})).data,getEvent:async(t,s)=>(await F.get(`/commerce/events/${t}`,{params:{society_id:s}})).data,updateEvent:async(t,s,a)=>(await F.patch(`/commerce/events/${t}`,s,{params:{society_id:a}})).data,switchEventPricingSource:async(t,s,a)=>(await F.post(`/commerce/events/${t}/pricing-source`,{pricing_source:s},{params:{society_id:a}})).data,deleteEvent:async(t,s,a)=>{await F.delete(`/commerce/events/${t}`,{params:{society_id:s},data:a?{confirm_slug:a}:void 0})},getEventRegistrations:async(t,s)=>(await F.get(`/commerce/events/${t}/registrations`,{params:{society_id:s}})).data,retryPush:async(t,s,a)=>(await F.post(`/commerce/events/${t}/registrations/${s}/push-to-event-app`,null,{params:{society_id:a}})).data,pushEventMetadata:async(t,s)=>(await F.post(`/commerce/events/${t}/push-metadata`,null,{params:{society_id:s}})).data,uploadEventHero:async(t,s,a)=>{const n=new FormData;return n.append("file",s),(await F.post(`/commerce/events/${t}/hero-image`,n,{params:{society_id:a},headers:{"Content-Type":"multipart/form-data"}})).data},deleteEventHero:async(t,s)=>(await F.delete(`/commerce/events/${t}/hero-image`,{params:{society_id:s}})).data,getUnpushedRegistrations:async t=>(await F.get("/commerce/event-app-unpushed",{params:{society_id:t}})).data,getProducts:async t=>(await F.get("/commerce/products",{params:{society_id:t}})).data,createProduct:async(t,s)=>(await F.post("/commerce/products",t,{params:{society_id:s}})).data,updateProduct:async(t,s,a)=>(await F.patch(`/commerce/products/${t}`,s,{params:{society_id:a}})).data,deleteProduct:async(t,s)=>{await F.delete(`/commerce/products/${t}`,{params:{society_id:s}})},getCampaigns:async t=>(await F.get("/commerce/donation-campaigns",{params:{society_id:t}})).data,createCampaign:async(t,s)=>(await F.post("/commerce/donation-campaigns",t,{params:{society_id:s}})).data,updateCampaign:async(t,s,a)=>(await F.patch(`/commerce/donation-campaigns/${t}`,s,{params:{society_id:a}}
1)).data,deleteCampaign:async(t,s)=>{await F.delete(`/commerce/donation-campaigns/${t}`,{params:{society_id:s}})},getOrders:async(t,s)=>(await F.get("/commerce/orders",{params:{society_id:t,...s}})).data,getOrder:async(t,s)=>(await F.get(`/commerce/orders/${t}`,{params:{society_id:s}})).data,downloadOrderReceipt:async(t,s)=>(await F.get(`/commerce/orders/${t}/receipt`,{params:{society_id:s},responseType:"blob"})).data,downloadEventRegistrationsCsv:async(t,s,a,n)=>{const r=await F.get(`/commerce/events/${t}/registrations/export`,{params:{society_id:s,...a?{fields:a}:{},...n?{include_children:!0}:{}},responseType:"blob"});return{blob:r.data,filename:Em(r.headers["content-disposition"])}},getPromoCodes:async t=>(await F.get("/commerce/promo-codes",{params:{society_id:t}})).data,createPromoCode:async(t,s)=>(await F.post("/commerce/promo-codes",t,{params:{society_id:s}})).data,updatePromoCode:async(t,s,a)=>(await F.patch(`/commerce/promo-codes/${t}`,s,{params:{society_id:a}})).data,deletePromoCode:async(t,s)=>{await F.delete(`/commerce/promo-codes/${t}`,{params:{society_id:s}})},getEventDashboard:async(t,s)=>(await F.get(`/commerce/events/${t}/dashboard`,{params:{society_id:s}})).data,getMeetingsSummary:async t=>(await F.get("/commerce/events/metrics-summary",{params:{society_id:t}})).data,getRegistrationExportColumns:async(t,s,a)=>(await F.get(`/commerce/events/${t}/registrations/export-columns`,{params:{society_id:s,include_children:a}})).data.columns,downloadEventDashboardReport:async(t,s,a)=>{const n=await F.get(`/commerce/events/${t}/dashboard/export`,{params:{society_id:s,report:a},responseType:"blob"});return{blob:n.data,filename:Em(n.headers["content-disposition"])}}};function Lg(){const{selectedSocietyId:t}=V();return re({queryKey:["admin","events",t],queryFn:()=>Wt.getEvents(t),enabled:!!t})}function Pi(t){const{selectedSocietyId:s}=V();return re({queryKey:["admin","events",t,s],queryFn:()=>Wt.getEvent(t,s),enabled:!!s&&!!t})}function sk(){const{selectedSocietyId:t}=V(),s=J();return W({mutationFn:a=>Wt.createEvent(a,t),onSuccess:()=>s.invalidateQueries({queryKey:["admin","events"]})})}function ak(){const{selectedSocietyId:t}=V(),s=J();return W({mutationFn:a=>Wt.createEventWithChildren(a,t),onSuccess:()=>{s.invalidateQueries({queryKey:["admin","events"]})}})}function nk(){const{selectedSocietyId:t}=V(),s=J();return W({mutationFn:({eventId:a,data:n})=>Wt.updateEvent(a,n,t),onSuccess:()=>s.invalidateQueries({queryKey:["admin","events"]})})}function rk(){const{selectedSocietyId:t}=V(),s=J();return W({mutationFn:({eventId:a,pricingSource:n})=>Wt.switchEventPricingSource(a,n,t),meta:{suppressErrorToast:!0},onSettled:()=>s.invalidateQueries({queryKey:["admin","events"]})})}function ik(){const{selectedSocietyId:t}=V(),s=J();return W({mutationFn:({eventId:a,confirm_slug:n})=>Wt.deleteEvent(a,t,n),onSuccess:()=>s.invalidateQueries({queryKey:["admin","events"]})})}function lk(t){const{selectedSocietyId:s}=V();return re({queryKey:["admin","event-registrations",t,s],queryFn:()=>Wt.getEventRegistrations(t,s),enabled:!!s&&!!t})}function $g(){const{selectedSocietyId:t}=V(),s=J();return W({mutationFn:({eventId:a,registrationId:n})=>Wt.retryPush(a,n,t),onSuccess:()=>{s.invalidateQueries({queryKey:["admin","event-registrations"]}),s.invalidateQueries({queryKey:["admin","event-app-unpushed"]})}})}function ok(){const{selectedSocietyId:t}=V(),s=J();return W({mutationFn:a=>Wt.pushEventMetadata(a,t),onSuccess:()=>{s.invalidateQueries({queryKey:["admin","events"]})}})}function ck(){const{selectedSocietyId:t}=V(),s=J();return W({mutationFn:({eventId:a,file:n})=>Wt.uploadEventHero(a,n,t),onSuccess:()=>{s.invalidateQueries({queryKey:["admin","events"]})}})}function dk(){const{selectedSocietyId:t}=V(),s=J();return W({mutationFn:a=>Wt.deleteEventHero(a,t),onSuccess:()=>{s.invalidateQueries({queryKey:["admin","events"]})}})}function mk(){const{selectedSocietyId:t}=V();return re({queryKey:["admin","event-app-unpushed",t],queryFn:()=>Wt.getUnpushedRegistrations(t),enabled:!!t})}function uk(t){const{selectedSocietyId:s}=V();return re({queryKey:["admin","event-dashboard",t,s],queryFn:()=>Wt.getEventDashboard(t,s),enabled:!!s&&!!t})}function hk(){const{selectedSocietyId:t}=V();return re({queryKey:["admin","meetings-summary",t],queryFn:()=>Wt.getMeetingsSummary(t),enabled:!!t})}function pk(){const{selectedSocietyId:t}=V(),s=J();return W({mutationFn:({eventId:a,registrationId:n})=>Wt.retryPush(a,n,t),onSuccess:()=>{s.invalidateQueries({queryKey:["admin","event-registrations"]}),s.invalidateQueries({queryKey:["admin","event-app-unpushed"]}),s.invalidateQueries({queryKey:["admin","event-dashboard"]})}})}function xk(){const{selectedSocietyId:t}=V();return re({queryKey:["admin","products",t],queryFn:()=>Wt.getProducts(t),enabled:!!t})}function gk(){const{selectedSocietyId:t}=V(),s=J();return W({mutationFn:a=>Wt.createProduct(a,t),onSuccess:()=>s.invalidateQueries({queryKey:["admin","products"]})})}function fk(){const{selectedSocietyId:t}=V(),s=J();return W({mutationFn:({productId:a,data:n})=>Wt.updateProduct(a,n,t),onSuccess:()=>s.invalidateQueries({queryKey:["admin","products"]})})}function yk(){const{selectedSocietyId:t}=V(),s=J();return W({mutationFn:a=>Wt.deleteProduct(a,t),onSuccess:()=>s.invalidateQueries({queryKey:["admin","products"]})})}function bk(){const{selectedSocietyId:t}=V();return re({queryKey:["admin","campaigns",t],queryFn:()=>Wt.getCampaigns(t),enabled:!!t})}function jk(){const{selectedSocietyId:t}=V(),s=J();return W({mutationFn:a=>Wt.createCampaign(a,t),onSuccess:()=>s.invalidateQueries({queryKey:["admin","campaigns"]})})}function vk(){const{selectedSocietyId:t}=V(),s=J();return W({mutationFn:({campaignId:a,data:n})=>Wt.updateCampaign(a,n,t),onSuccess:()=>s.invalidateQueries({queryKey:["admin","campaigns"]})})}function wk(){const{selectedSocietyId:t}=V(),s=J();return W({mutationFn:a=>Wt.deleteCampaign(a,t),onSuccess:()=>s.invalidateQueries({queryKey:["admin","campaigns"]})})}function Nk(t){const{selectedSocietyId:s}=V();return re({queryKey:["admin","orders",s,t],queryFn:()=>Wt.getOrders(s,t),enabled:!!s,placeholderData:sa})}function kk(){const{selectedSocietyId:t}=V();return re({queryKey:["admin","promo-codes",t],queryFn:()=>Wt.getPromoCodes(t),enabled:!!t})}function _k(){const{selectedSocietyId:t}=V(),s=J();return W({mutationFn:a=>Wt.createPromoCode(a,t),onSuccess:()=>s.invalidateQueries({queryKey:["admin","promo-codes"]})})}function Sk(){const{selectedSocietyId:t}=V(),s=J();return W({mutationFn:({id:a,data:n})=>Wt.updatePromoCode(a,n,t),onSuccess:()=>s.invalidateQueries({queryKey:["admin","promo-codes"]})})}function Ck(){const{selectedSocietyId:t}=V(),s=J();return W({mutationFn:a=>Wt.deletePromoCode(a,t),onSuccess:()=>s.invalidateQueries({queryKey:["admin","promo-codes"]})})}const lo="flex h-7 w-7 shrink-0 items-center justify-center rounded-lg",qg=`${lo}
1 bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300`,Pk=`${lo} bg-emerald-100 text-emerald-600 dark:bg-emerald-900/30 dark:text-emerald-400`,Ak=`${lo} bg-amber-100 text-amber-600 dark:bg-amber-900/30 dark:text-amber-400`,Ig=t=>t.toLocaleString("en-US",{style:"currency",currency:"USD"});function Tm(t){if(!t)return null;const s=Ps(t);return Number.isNaN(s.getTime())?null:Be(s,"MMM d, yyyy")}function Ek(t){const s=Tm(t.start_date),a=Tm(t.end_date);return[s&&a&&s!==a?`${s} â ${a}`:s||a||"Date TBD",t.venue].filter(Boolean).join(" · ")}function Tk({inProgress:t}){return e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx("span",{className:me("h-1.5 w-1.5 rounded-full",t?"bg-emerald-500":"bg-muted-foreground/50"),"aria-hidden":"true"}),e.jsx("span",{className:"text-xs font-medium text-foreground/85",children:t?"In progress":"Upcoming"})]})}function Fk({parentName:t}){return e.jsx("span",{className:"inline-flex items-center rounded-full bg-muted px-2 py-0.5 text-[11px] font-medium text-muted-foreground",children:t?`Part of ${t}`:"Child event"})}function Rk({registrations:t,capacity:s}){if(s==null||s<=0)return e.jsxs("span",{className:"text-xs tabular-nums text-muted-foreground",children:[t.toLocaleString()," registered"]});const a=t>s,n=Math.min(t/s*100,100);return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-1.5 w-20 overflow-hidden rounded-full bg-muted",children:e.jsx("div",{className:me("h-full rounded-full",a?"bg-amber-500":"bg-brand-navy dark:bg-primary"),style:{width:`${n}%`}})}),e.jsxs("span",{className:me("text-xs tabular-nums",a?"font-medium text-amber-600 dark:text-amber-400":"text-muted-foreground"),children:[t.toLocaleString(),"/",s.toLocaleString()]})]})}function Mk({meeting:t}){const s=kt(),a=`/events/${t.id}`,n=()=>{s(a)},r=l=>{(l.key==="Enter"||l.key===" ")&&l.target===l.currentTarget&&(l.preventDefault(),s(a))},i=l=>l.stopPropagation();return e.jsxs("div",{role:"link",tabIndex:0,onClick:n,onKeyDown:r,className:"flex cursor-pointer flex-col gap-2 border-b border-border py-3 last:border-b-0 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring sm:flex-row sm:items-center sm:justify-between sm:gap-4",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"truncate text-sm font-medium",children:t.name}),e.jsx(Tk,{inProgress:t.in_progress}),t.is_child&&e.jsx(Fk,{parentName:t.parent_name})]}),e.jsx("p",{className:"mt-0.5 truncate text-xs text-muted-foreground",children:Ek(t)})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-4 sm:gap-6",children:[e.jsx(Rk,{registrations:t.registrations,capacity:t.capacity}),e.jsx("span",{className:"w-20 shrink-0 text-right text-sm font-semibold tabular-nums tracking-tight",children:Ig(t.net_revenue)}),e.jsx(je,{to:a,onClick:i,className:"shrink-0 text-xs font-medium text-brand-navy hover:underline dark:text-sky-300",children:"Dashboard â"})]})]})}function Dk({totals:t}){const s=t.ytd_year,a=[{key:"meetings",label:"Upcoming meetings",value:t.upcoming_meetings.toLocaleString(),icon:Yt,iconClass:qg},{key:"registrations",label:"Registrations",value:t.upcoming_registrations.toLocaleString(),icon:Lt,iconClass:Pk},{key:"revenue",label:`event net revenue · ${s} bookings`,value:Ig(t.net_revenue_ytd),icon:Ua,iconClass:Ak}];return e.jsx("div",{className:"grid grid-cols-1 gap-4 border-b border-border pb-4 sm:grid-cols-3",children:a.map(n=>e.jsxs("div",{className:"flex min-w-0 items-center gap-2.5",children:[e.jsx("span",{className:n.iconClass,children:e.jsx(n.icon,{className:"h-4 w-4"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-lg font-semibold tabular-nums tracking-tight",children:n.value}),e.jsx("div",{className:"truncate text-xs text-muted-foreground",children:n.label})]})]},n.key))})}function Og(){return e.jsx(ne,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:qg,children:e.jsx(Yt,{className:"h-4 w-4"})}),"Meetings"]}),e.jsx(je,{to:"/events",className:"shrink-0 text-xs font-medium text-brand-navy hover:underline dark:text-sky-300",children:"View all events â"})]})})}function Lk(){return e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(Og,{}),e.jsxs($,{className:"space-y-4",children:[e.jsx("div",{className:"grid grid-cols-1 gap-4 border-b border-border pb-4 sm:grid-cols-3",children:[0,1,2].map(t=>e.jsx(Y,{className:"h-10 w-full"},t))}),e.jsx("div",{className:"space-y-3",children:[0,1,2].map(t=>e.jsx(Y,{className:"h-12 w-full"},t))})]})]})}function $k({onRetry:t}){return e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:me(lo,"bg-red-100 text-red-600 dark:bg-red-900/30 dark:text-red-400"),children:e.jsx(Bt,{className:"h-4 w-4"})}),"Meetings"]})}),e.jsx($,{children:e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Couldnât load meetings."}),e.jsxs(g,{variant:"outline",size:"sm",onClick:t,children:[e.jsx(St,{className:"mr-1.5 h-3.5 w-3.5"}),"Retry"]})]})})]})}function qk(){const{data:t,isLoading:s,isError:a,refetch:n}=hk();return s||!t&&!a?e.jsx(Lk,{}):a||!t?e.jsx($k,{onRetry:()=>{n()}}):e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(Og,{}),e.jsxs($,{className:"space-y-4",children:[e.jsx(Dk,{totals:t.totals}),t.meetings.length===0?e.jsx("p",{className:"py-2 text-sm text-muted-foreground",children:"No upcoming meetings"}):e.jsx("div",{children:t.meetings.map(r=>e.jsx(Mk,{meeting:r},r.id))})]})]})}class Ik extends o.Component{constructor(s){super(s),this.state={hasError:!1}}static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(s,a){console.error(`Widget "${this.props.widgetLabel}" crashed:`,s,a)}render(){return this.state.hasError?e.jsxs(L,{children:[e.jsx(ne,{children:e.jsx(ie,{className:"text-sm font-medium",children:this.props.widgetLabel})}),e.jsx($,{children:e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Bt,{className:"h-4 w-4"}),e.jsx("span",{children:"Unable to load this widget."})]})})]}):this.props.children}}const ss=o.forwardRef(({className:t,...s},a)=>e.jsx(np,{className:me("peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",t),...s,ref:a,children:e.jsx(hb,{className:me("pointer-events-none block h-4 w-4 roun
1ded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0")})}));ss.displayName=np.displayName;const Cl=[{id:"stats-cards",label:"Stats Cards",description:"Current roster, active, expiring soon, MTD revenue",category:"core",span:"full",calendarDefault:!0,anniversaryDefault:!0},{id:"membership-matrix",label:"Membership Matrix",description:"Member count by type and status",category:"core",span:"full",calendarDefault:!0,anniversaryDefault:!0},{id:"mtd-renewals",label:"MTD Renewals",description:"Renewals this month vs last month and last year",category:"core",span:"half",calendarDefault:!0,anniversaryDefault:!0},{id:"pending-actions",label:"Pending Actions",description:"Pending members, disputes, and committee applications",category:"core",span:"half",calendarDefault:!0,anniversaryDefault:!0},{id:"recent-activity",label:"Recent Activity",description:"Latest admin actions and member changes",category:"core",span:"full",calendarDefault:!0,anniversaryDefault:!0},{id:"auto-renew-adoption",label:"Auto-Renew Adoption",description:"Percentage of active members with auto-renew enabled",category:"renewal",span:"half",calendarDefault:!0,anniversaryDefault:!0},{id:"at-risk-members",label:"At-Risk Members",description:"Members expiring within 30 days without auto-renew",category:"renewal",span:"half",calendarDefault:!1,anniversaryDefault:!0},{id:"renewal-progress",label:"Renewal Progress",description:"Renewal cycle c
1ompletion rate with previous cycle comparison",category:"renewal",span:"half",calendarDefault:!0,anniversaryDefault:!1},{id:"expiring-members",label:"Expiring Members",description:"Members expiring in 7, 30, and 90 day windows",category:"renewal",span:"half",calendarDefault:!1,anniversaryDefault:!0},{id:"lapsed-recovery",label:"Lapsed Recovery",description:"Recovery metrics for lapsed members over 90/180/365 days",category:"renewal",span:"half",calendarDefault:!0,anniversaryDefault:!1},{id:"failed-auto-renewals",label:"Failed Auto-Renewals",description:"Members whose automatic renewal payment failed",category:"renewal",span:"half",calendarDefault:!0,anniversaryDefault:!0},{id:"renewal-email-funnel",label:"Renewal Email Funnel",description:"Conversion rates for each renewal email step",category:"renewal",span:"full",calendarDefault:!1,anniversaryDefault:!1},{id:"revenue-pacing",label:"Revenue Pacing",description:"Current year vs previous year cumulative revenue",category:"financial",span:"full",calendarDefault:!0,anniversaryDefault:!1},{id:"ar-aging",label:"Accounts Receivable Aging",description:"Outstanding invoices by age bucket",category:"financial",span:"half",calendarDefault:!1,anniversaryDefault:!1},{id:"meetings-metrics",label:"Meetings",description:"Upcoming meetings with registrations and event revenue",category:"financial",span:"full",calendarDefault:!0,anniversaryDefault:!0,requiredFeature:"commerce_enabled"},{id:"member-growth-pacing",label:"Member Growth Pacing",description:"Monthly member growth trends",category:"engagement",span:"full",calendarDefault:!1,anniversaryDefault:!1},{id:"email-health",label:"Email Health",description:"Delivery rate, bounce rate, and suppression trends",category:"engagement",span:"half",calendarDefault:!1,anniversaryDefault:!1},{id:"cohort-retention",label:"Cohort Retention",description:"Retention curves by join-month cohort",category:"engagement",span:"full",calendarDefault:!1,anniversaryDefault:!1},{id:"membership-type-trends",label:"Membership Type Trends",description:"Active member counts by type over time",category:"engagement",span:"full",calendarDefault:!1,anniversaryDefault:!1},{id:"event-fill-rate",label:"Event Registration Fill Rate",description:"Registration progress for upcoming events",category:"engagement",span:"half",calendarDefault:!1,anniversaryDefault:!1,requiredFeature:"commerce_enabled"}],Ok={core:"Core",renewal:"Renewal",financial:"Financial",engagement:"Engagement"};function Ug(t){return Cl.filter(s=>t==="anniversary"?s.anniversaryDefault:s.calendarDefault).map(s=>s.id)}function Uk({open:t,onOpenChange:s,enabledWidgets:a}){return e.jsx(Fe,{open:t,onOpenChange:s,children:t&&e.jsx(zk,{enabledWidgets:a,onOpenChange:s})})}function zk({enabledWidgets:t,onOpenChange:s}){const{data:a}=Qs(),n=$v(),[r,i]=o.useState(()=>new Set(t)),l=(p,x)=>{i(f=>{const b=new Set(f);return x?b.add(p):b.delete(p),b})},m=()=>{const p=Ug(a?.dues_cycle_type||"calendar");i(new Set(p))},c=()=>{const p=Cl.filter(x=>r.has(x.id)).map(x=>x.id);n.mutate(p,{onSuccess:()=>s(!1)})},d=Cl.filter(p=>!(p.requiredFeature&&a?.settings?.[p.requiredFeature]===!1)),h=["core","renewal","financial","engagement"].map(p=>({key:p,label:Ok[p],widgets:d.filter(x=>x.category===p)})).filter(p=>p.widgets.length>0);return e.jsxs(Te,{className:"max-h-[80vh] max-w-lg overflow-y-auto",children:[e.jsx(Ae,{children:e.jsx(Ee,{children:"Configure Dashboard"})}),e.jsx("div",{className:"space-y-6 py-2",children:h.map(p=>e.jsxs("div",{children:[e.jsx("h3",{className:"mb-3 text-sm font-semibold uppercase tracking-wide text-muted-foreground",children:p.label}),e.jsx("div",{className:"space-y-3",children:p.widgets.map(x=>e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("label",{htmlFor:`widget-${x.id}`,className:"cursor-pointer text-sm font-medium",children:x.label}),e.jsx("p",{className:"text-xs text-muted-foreground",children:x.description})]}),e.jsx(ss,{id:`widget-${x.id}`,checked:r.has(x.id),onCheckedChange:f=>l(x.id,f)})]},x.id))})]},p.key))}),e.jsxs(Ge,{className:"flex-col gap-2 sm:flex-row",children:[e.jsx(g,{type:"button",variant:"ghost",size:"sm",onClick:m,className:"mr-auto",children:"Reset to Defaults"}),e.jsx(g,{type:"button",variant:"outline",onClick:()=>s(!1),children:"Cancel"}),e.jsx(g,{type:"button",onClick:c,disabled:n.isPending,children:n.isPending?"Saving...":"Save"})]})]})}
1function Fm(t){return`ams_passkey_prompt_dismissed_${t}`}function Ad({subjectId:t,variant:s,settingsPath:a,checkCredentials:n}){const r=io(),i=kt(),[l,m]=o.useState(!1);if(o.useEffect(()=>{r&&localStorage.getItem(Fm(t))!=="true"&&n().then(u=>{u.length===0&&m(!0)}).catch(()=>{})},[t,r,n]),!l)return null;const c=()=>{localStorage.setItem(Fm(t),"true"),m(!1)},d=s==="portal";return e.jsx(L,{className:d?"border-blue-200 bg-blue-50 dark:border-blue-800 dark:bg-blue-950/30":"border-primary/20 bg-primary/5",children:e.jsx($,{className:"p-4 sm:p-5",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:`shrink-0 rounded-full p-2 ${d?"bg-blue-100 dark:bg-blue-900":"bg-primary/10"}`,children:e.jsx(Hc,{className:`h-5 w-5 ${d?"text-blue-600":"text-primary"}`})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("h3",{className:`text-sm font-semibold ${d?"text-foreground":""}`,children:"Enable passkey login"}),e.jsx("p",{className:"mt-0.5 hidden text-sm sm:block text-muted-foreground",children:"Sign in faster with Face ID, fingerprint, or Windows Hello â no password needed."}),e.jsxs("div",{className:"mt-3 flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(g,{size:"sm",onClick:()=>i(a),className:`w-full sm:w-auto ${d?"bg-blue-600 text-white hover:bg-blue-700":""}`,children:"Set up passkey"}),e.jsx(g,{variant:"ghost",size:"sm",onClick:c,className:"w-full text-muted-foreground sm:w-auto",children:"Don't remind me"})]})]}),e.jsx("button",{type:"button","aria-label":"Close passkey reminder",onClick:()=>m(!1),className:"shrink-0 rounded-md p-1 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",children:e.jsx(ms,{className:"h-4 w-4","aria-hidden":"true"})})]})})})}const zg=o.createContext(null),To=200,Bk=5e3,Kk=2e4;function Bg({children:t,steps:s,storageKey:a,isSuperAdmin:n=!1,modules:r={},status:i,onEvent:l}){const[m,c]=o.useState(!1),[d,u]=o.useState(0),h=o.useRef(0),p=i!==void 0,x=p?i!==null:typeof window<"u"&&localStorage.getItem(a)==="true",f=o.useMemo(()=>{const C=window.innerWidth>=1024;return s.filter(P=>!(P.desktopOnly&&!C||P.superAdminOnly&&!n||P.module&&r[P.module]===!1))},[s,n,r]),b=o.useCallback(()=>{p||localStorage.setItem(a,"true")},[p,a]),N=o.useCallback(()=>{h.current=0,u(0),c(!0),l?.("started",0,f.length)},[l,f.length]),j=o.useCallback((C,P)=>{c(!1),u(0),b(),l?.(C,P,f.length)},[b,l,f.length]),w=o.useCallback(()=>j("completed",f.length-1),[j,f.length]),v=o.useCallback(()=>j("skipped",d),[j,d]),k=o.useCallback(()=>{u(C=>C+1>=f.length?(c(!1),b(),l?.("completed",C,f.length),0):(l?.("step",C+1,f.length),C+1))},[f.length,b,l]),S=o.useCallback(()=>{u(C=>Math.max(0,C-1))},[]),_=o.useCallback(()=>{p||localStorage.removeItem(a)},[p,a]);o.useEffect(()=>{if(!m||f.length===0)return;const C=f[d];if(!C)return;let P=0,A;const E=C.waitForSelector?Kk:Bk,Q=()=>{if(document.querySelector(C.selector)){h.current+=1;return}if(P+=To,P>=E){d+1>=f.length?(c(!1),h.current===0?l?.("aborted",-1,f.length):(b(),l?.("completed",d,f.length))):(l?.("step",d+1,f.length),u(U=>U+1));return}A=setTimeout(Q,To)};return A=setTimeout(Q,To),()=>clearTimeout(A)},[m,d,f,b,l]);const y=o.useMemo(()=>({active:m,currentStep:d,steps:f,start:N,next:k,back:S,complete:w,skip:v,end:v,completed:x,reset:_}),[m,d,f,N,k,S,w,v,x,_]);return e.jsx(zg.Provider,{value:y,children:t})}function oo(){const t=o.useContext(zg);if(!t)throw new Error("useTour must be used within a TourProvider");return t}function Kg({variant:t="admin"}){const{active:s,currentStep:a,steps:n,next:r,back:i,skip:l,complete:m}=oo(),[c,d]=o.useState(null),u=o.useRef(null),h=o.useRef(null),p=o.useRef(null),x=o.useRef(null),f=o.useRef(null),b=o.useCallback((A=!1)=>{if(!s||n.length===0)return;const E=n[a];if(!E)return;const Q=D=>{d(K=>!A&&K&&K.top===D.top&&K.left===D.left&&K.width===D.width&&K.height===D.height?K:D)},U=document.querySelector(E.selector);if(!U&&E.waitForSelector){const D=n[a+1];if(D?.waitForSelector&&document.querySelector(D.selector)){r();return}}if(h.current=U,U){const D=U.getBoundingClientRect();f.current!==a&&(D.top<0||D.bottom>window.innerHeight)?(f.current=a,U.scrollIntoView({behavior:"smooth",block:D.height>window.innerHeight*.8?"start":"center"}),requestAnimationFrame(()=>{Q(U.getBoundingClientRect())}
1)):Q(D)}else d(null)},[s,a,n,r]);o.useLayoutEffect(()=>{b()},[b]),o.useEffect(()=>{if(!s)return;const A=()=>b(!0),E=()=>b();return window.addEventListener("resize",A),window.addEventListener("scroll",E,!0),()=>{window.removeEventListener("resize",A),window.removeEventListener("scroll",E,!0)}},[s,b]),o.useEffect(()=>{if(!(!s||!h.current))return u.current=new ResizeObserver(()=>b()),u.current.observe(h.current),()=>u.current?.disconnect()},[s,a,b]),o.useEffect(()=>{if(!s)return;const A=E=>{E.key==="Escape"&&l();const Q=E.target,U=!!Q?.closest('input, textarea, select, [contenteditable="true"]'),D=!!Q?.closest("[data-tour-ui]");if(U&&!D)return;const K=p.current?.contains(document.activeElement);E.key==="Enter"&&!K&&r(),E.key==="ArrowRight"&&r(),E.key==="ArrowLeft"&&i()};return window.addEventListener("keydown",A),()=>window.removeEventListener("keydown",A)},[s,r,i,l]),o.useEffect(()=>{if(!s)return;const A=setInterval(b,200);return()=>clearInterval(A)},[s,b]),o.useEffect(()=>{if(!s)return;const A=n[a];if(!A?.advanceOnTargetClick)return;const E=document.querySelector(A.selector);if(!E)return;const Q=()=>r();return E.addEventListener("click",Q),()=>E.removeEventListener("click",Q)},[s,a,n,r,c]);const N=o.useRef(null);o.useEffect(()=>{if(!s){N.current=null,f.current=null;return}if(!c||N.current===a)return;N.current=a,(x.current??p.current?.querySelector("button"))?.focus()},[s,a,c]),o.useEffect(()=>{if(!s)return;const A=E=>{if(E.key!=="Tab"||!p.current)return;const Q=p.current.querySelectorAll("button");if(Q.length===0)return;const U=Q[0],D=Q[Q.length-1];if(!p.current.contains(document.activeElement)){E.preventDefault(),U.focus();return}E.shiftKey&&document.activeElement===U?(E.preventDefault(),D.focus()):!E.shiftKey&&document.activeElement===D&&(E.preventDefault(),U.focus())};return window.addEventListener("keydown",A),()=>window.removeEventListener("keydown",A)},[s]);const j=o.useRef(!1);if(o.useEffect(()=>{s?j.current=!0:j.current&&(j.current=!1,document.activeElement?.blur(),document.body.focus())},[s]),!s||n.length===0)return null;const w=n[a];if(!w)return null;const v=t==="portal";if(!c)return w.waitForSelector?e.jsx("div",{ref:p,"data-tour-ui":"",className:`fixed bottom-4 left-1/2 z-[9999] w-[calc(100%-2rem)] max-w-sm -translate-x-1/2 rounded-lg p-4 shadow-xl ${v?"border border-slate-200 bg-white text-slate-900":"border border-border bg-card text-card-foreground"}`,style:{pointerEvents:"auto"},role:"dialog","aria-label":w.title,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(He,{className:`mt-0.5 h-4 w-4 shrink-0 animate-spin ${v?"text-blue-600":"text-primary"}`,"aria-hidden":"true"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("h3",{className:"text-sm font-semibold",children:w.title}),e.jsx("p",{className:`mt-1 text-sm ${v?"text-slate-600":"text-muted-foreground"}`,children:w.description}),e.jsx("p",{className:`mt-2 text-xs ${v?"text-slate-400":"text-muted-foreground"}`,children:"The tour continues automatically when you reach this step."}),e.jsxs("div",{className:"mt-3 flex items-center gap-1.5 sm:gap-2",children:[a>0&&e.jsxs("button",{onClick:i,className:`flex min-h-[36px] items-center gap-1 rounded px-2 py-1.5 text-xs transition-colors ${v?"bg-white text-slate-600 hover:bg-slate-100":"text-foreground hover:bg-muted"}`,children:[e.jsx(Gs,{className:"h-3 w-3"}),"Back"]}),e.jsx("button",{onClick:l,className:`min-h-[36px] rounded px-2 py-1.5 text-xs transition-colors ${v?"bg-white text-slate-500 hover:bg-slate-100 hover:text-slate-700":"text-muted-foreground hover:bg-muted hover:text-foreground"}`,children:"Exit tour"})]})]})]})}):null;const k=window.innerWidth<640,S=k?4:8,_={position:"fixed",top:c.top-S,left:c.left-S,width:c.width+S*2,height:c.height+S*2,borderRadius:8,zIndex:9998,pointerEvents:"none",boxShadow:"0 0 0 9999px rgba(0, 0, 0, 0.5)"},y=k?Math.min(280,window.innerWidth-24):320,C=Qk(c,w.placement||"bottom",S,y),P=!!(w.advanceOnTargetClick||w.waitForSelector);return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:`fixed inset-0 z-[9997] ${P?"pointer-events-none":""}`,"aria-hidden":"true"}),e.jsx("div",{style:_}),e.jsxs("div",{ref:p,"data-tour-ui":"",className:`fixed z-[9999] rounded-lg p-3 shadow-xl sm:p-4 ${v?"border border-slate-200 bg-white text-slate-900":"border border-border bg-card text-card-foreground"}
1`,style:{top:C.top,left:C.left,width:y,pointerEvents:"auto"},role:"dialog","aria-label":w.title,children:[e.jsx("button",{onClick:l,className:`absolute right-1 top-1 flex min-h-[44px] min-w-[44px] items-center justify-center rounded-md p-2 transition-colors ${v?"text-slate-400 hover:bg-slate-100 hover:text-slate-600":"text-muted-foreground hover:bg-muted hover:text-foreground"}`,"aria-label":"Close tour",children:e.jsx(ms,{className:"h-4 w-4"})}),e.jsx("h3",{className:"pr-8 text-sm font-semibold",children:w.title}),e.jsx("p",{className:`mt-1 text-sm ${v?"text-slate-600":"text-muted-foreground"}`,children:w.description}),w.advanceOnTargetClick&&e.jsxs("div",{className:`mt-3 flex min-h-[36px] items-center gap-1.5 rounded-md px-3 py-1.5 text-xs font-medium ${v?"bg-blue-50 text-blue-700":"bg-muted text-muted-foreground"}`,children:[e.jsx(Ab,{className:"h-3.5 w-3.5 shrink-0"}),"Click the highlighted area to continue"]}),e.jsxs("div",{className:"mt-3 flex items-center justify-between sm:mt-4",children:[e.jsxs("span",{className:`shrink-0 whitespace-nowrap text-xs ${v?"text-slate-400":"text-muted-foreground"}`,children:[a+1," / ",n.length]}),e.jsxs("div",{className:"flex items-center gap-1.5 sm:gap-2",children:[e.jsx("button",{onClick:l,className:`min-h-[36px] rounded px-2 py-1.5 text-xs transition-colors ${v?"bg-white text-slate-500 hover:bg-slate-100 hover:text-slate-700":"text-muted-foreground hover:bg-muted hover:text-foreground"}`,children:"Skip"}),a>0&&e.jsxs("button",{onClick:i,className:`flex min-h-[36px] items-center gap-1 rounded px-2 py-1.5 text-xs transition-colors ${v?"bg-white text-slate-600 hover:bg-slate-100":"text-foreground hover:bg-muted"}`,children:[e.jsx(Gs,{className:"h-3 w-3"}),"Back"]}),w.advanceOnTargetClick?null:e.jsxs("button",{ref:x,onClick:a+1>=n.length?m:r,className:`flex min-h-[36px] items-center gap-1 rounded px-3 py-1.5 text-xs font-medium transition-colors ${v?"bg-blue-600 text-white hover:bg-blue-700":"bg-primary text-primary-foreground hover:bg-primary/90"}`,children:[a+1>=n.length?"Finish":"Next",a+1<n.length&&e.jsx(ts,{className:"h-3 w-3"})]})]})]})]})]})}function Qk(t,s,a,n){const l=window.innerWidth,m=window.innerHeight;let c=0,d=0;switch(s){case"bottom":c=t.bottom+a+12,d=t.left+t.width/2-n/2,c+200>m&&(c=t.top-a-12-200);break;case"top":c=t.top-a-12-200,d=t.left+t.width/2-n/2,c<0&&(c=t.bottom+a+12);break;case"right":c=t.top+t.height/2-200/2,d=t.right+a+12,d+n>l&&(d=t.left-a-12-n);break;case"left":c=t.top+t.height/2-200/2,d=t.left-a-12-n,d<0&&(d=t.right+a+12);break}return d=Math.max(8,Math.min(d,l-n-8)),c=Math.max(8,Math.min(c,m-200-8)),{top:c,left:d}}function Qg({variant:t="admin",suppressed:s=!1}){const{completed:a,start:n,skip:r,active:i}=oo(),[l,m]=o.useState(!1);if(o.useEffect(()=>{if(!a&&!i&&!s){const h=setTimeout(()=>m(!0),500);return()=>clearTimeout(h)}},[a,i,s]),a||i||s)return null;const c=t==="portal",d=()=>{m(!1),setTimeout(()=>n(),200)},u=()=>{m(!1),r()};return e.jsx(Fe,{open:l,onOpenChange:h=>{h||u()},children:e.jsxs(Te,{className:`sm:max-w-md ${c?"bg-white text-slate-900":""}`,children:[e.jsx(Ae,{children:e.jsxs(Ee,{className:"flex items-center gap-2 text-lg",children:[e.jsx(jr,{className:`h-5 w-5 ${c?"text-blue-600":"text-primary"}`}),"Welcome! Want a quick tour?"]})}),e.jsx("p",{className:`text-sm ${c?"text-slate-600":"text-muted-foreground"}`,children:c?"We'll show you around your member portal â it only takes about 30 seconds.":"We'll walk you through the key features of your admin dashboard in about 30 seconds."}),e.jsxs("div",{className:"mt-2 flex justify-end gap-3",children:[e.jsx(g,{onClick:u,className:"bg-slate-200 text-slate-900 hover:bg-slate-300 dark:bg-slate-700 dark:text-slate-100 dark:hover:bg-slate-600",children:"Skip"}),e.jsx(g,{onClick:d,className:c?"bg-blue-600 text-white hover:bg-blue-700":"",children:"Start tour"})]})]})})}function nr({tourIds:t,children:s}){const[a,n]=ws(),r=a.get("tour"),[i,l]=o.useState(null);o.useEffect(()=>{if(r===null)return;const v=new URLSearchParams(a);v.delete("tour"),n(v,{replace:!0}),Tg(r)&&t.includes(r)&&l(k=>({id:r,nonce:(k?.nonce??0)+1}))},[r,a,n,t]);const m=i?.id??t[0],c=Pd[m],{user:d,isPlatformMode:u}=V(),{pathname:h}=ta(),p=u||h.startsWith("/platform"),{data:x}=Qs(),f=Ag(),b=Eg(m),N=f.data?f.data.tours[m]?.status??null:null,j=d?.role==="super_admin",w=o.useMemo(()=>({commerce:x?.settings?.commerce_enabled===!0,committees:x?.settings?.committees_enabled===!0}),[x?.settings]);return e.jsxs(Bg,{steps:c.steps,storageKey:`ams_admin_tour_done_${d?.id??"unknown"}`,isSuperAdmin:j,modules:w,status:N,onEvent:b,children:[!p&&e.jsx(W
1k,{launch:i}),s,!p&&e.jsx(Kg,{variant:"admin"})]})}function Wk({launch:t}){const{start:s}=oo(),a=o.useRef(s);return o.useEffect(()=>{a.current=s}),o.useEffect(()=>{if(!t)return;const n=setTimeout(()=>a.current(),300);return()=>clearTimeout(n)},[t]),null}const Vk=10080*60*1e3;function Gk(t,s,a){return!t||t.status!=="skipped"||s?!1:a-new Date(t.at).getTime()>Vk}function Yk(){const{data:t,isLoading:s}=eo();return e.jsx(NN,{data:t,isLoading:s})}function Hk(){const{data:t,isLoading:s}=eo();return e.jsx(LN,{data:t,isLoading:s})}const Jk={"stats-cards":Yk,"membership-matrix":ON,"auto-renew-adoption":KN,"at-risk-members":WN,"renewal-progress":TN,"expiring-members":RN,"lapsed-recovery":DN,"revenue-pacing":SN,"member-growth-pacing":Cg,"recent-activity":Hk,"mtd-renewals":VN,"failed-auto-renewals":GN,"ar-aging":YN,"renewal-email-funnel":ZN,"email-health":JN,"pending-actions":HN,"cohort-retention":XN,"membership-type-trends":ek,"event-fill-rate":tk,"meetings-metrics":qk};function Zk(){const{data:t}=Qs(),{user:s,isPlatformMode:a,selectedSocietyId:n}=V(),r=o.useCallback(()=>Xa.listCredentials(),[]),[i,l]=o.useState(!1),[m,c]=o.useState(!1),d=async()=>{l(!0);try{const f=await Ns.executiveSummaryPdf(n||void 0),b=URL.createObjectURL(f),N=document.createElement("a");N.href=b,N.download=`executive-summary-${new Date().toISOString().split("T")[0]}.pdf`,N.click(),URL.revokeObjectURL(b)}catch{}finally{l(!1)}},u=t?.settings?.dashboard_widgets??Ug(t?.dues_cycle_type||"calendar"),h=Cl.filter(f=>u.includes(f.id)).filter(f=>!(f.requiredFeature&&t?.settings?.[f.requiredFeature]===!1)),p=[];let x=[];for(const f of h)f.span==="full"?(x.length>0&&(p.push({widgets:[...x],isFull:!1}),x=[]),p.push({widgets:[f],isFull:!0})):(x.push(f),x.length===2&&(p.push({widgets:[...x],isFull:!1}),x=[]));return x.length>0&&p.push({widgets:[...x],isFull:!1}),e.jsxs(nr,{tourIds:["dashboard"],children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:"Dashboard"}),e.jsx("p",{className:"text-sm text-muted-foreground sm:text-base",children:"Overview of your society's membership"})]}),e.jsx(Xk,{isPlatformMode:a})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(g,{variant:"outline",size:"sm",onClick:()=>c(!0),children:[e.jsx(cn,{className:"mr-1 h-4 w-4"}),"Configure"]}),e.jsxs(g,{variant:"outline",size:"sm",onClick:d,disabled:i,children:[i?e.jsx(He,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(cs,{className:"mr-1.5 h-4 w-4"}),"Executive Summary"]})]})]}),s&&e.jsx(Ad,{subjectId:s.id,variant:"admin",settingsPath:"/account",checkCredentials:r}),e.jsx(UN,{}),e.jsx(BN,{}),e.jsx(Rg,{}),p.map((f,b)=>e.jsx("div",{className:f.isFull?"":"grid grid-cols-1 gap-6 lg:grid-cols-2",children:f.widgets.map(N=>{const j=Jk[N.id];return j?e.jsx(Ik,{widgetLabel:N.label,children:e.jsx("div",{"data-tour":N.id,children:e.jsx(j,{})})},N.id):null})},b))]}),e.jsx(Uk,{open:m,onOpenChange:c,enabledWidgets:u})]})}function Xk({isPlatformMode:t}){const{user:s}=V(),a=Ag(),n=Eg("dashboard"),r=Cd(),[i,l]=o.useState(!1),m=o.useRef(!1);o.useEffect(()=>{if(!a.isSuccess||!s||m.current)return;m.current=!0;const p=`ams_admin_tour_done_${s.id}`;localStorage.getItem(p)==="true"&&!a.data.tours.dashboard&&(l(!0),n("completed",-1,0),setTimeout(()=>l(!1),0)),localStorage.removeItem(p)},[a.isSuccess,a.data,s,n]);const c=a.data?.tours.dashboard,d=window.innerWidth<1024,u=Gk(c??null,a.data?.tour_reinvite_shown??!1,Date.now()),h=o.useRef(!1);return o.useEffect(()=>{u&&!h.current&&(h.current=!0,r.mutate({tour_reinvite_shown:!0}))},[u,r]),e.jsxs(e.Fragment,{children:[!t&&e.jsx(Qg,{variant:"admin",suppressed:d||i||!a.isSuccess}),u&&e.jsx(e_,{})]})}function e_(){const{start:t}=oo(),[s,a]=o.useState(!1);return s?null:e.jsxs("div",{className:"flex items-center gap-2 rounded-full border border-border bg-card px-3 py-1.5 text-xs text-muted-foreground",children:[e.jsx(jr,{className:"h-3.5 w-3.5"}),"New here? Take a 30-second tour",e.jsx("button",{onClick:t,className:"font-medium text-primary hover:underline",children:"Start"}),e.jsx("button",{onClick:()=>a(!0),"aria-label":"Dismiss",className:"hover:text-foreground",children:e.jsx(ms,{className:"h-3 w-3"})})]})}const qe=bb,Rm=vb,Ie=jb,Le=o.forwardRef(({className:t,children:s,...a},n)=>e.jsxs(rp,{ref:n,className:me("flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm r
1ing-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",t),...a,children:[s,e.jsx(pb,{asChild:!0,children:e.jsx(ps,{className:"h-4 w-4 opacity-50"})})]}));Le.displayName=rp.displayName;const Wg=o.forwardRef(({className:t,...s},a)=>e.jsx(ip,{ref:a,className:me("flex cursor-default items-center justify-center py-1",t),...s,children:e.jsx(Gn,{className:"h-4 w-4"})}));Wg.displayName=ip.displayName;const Vg=o.forwardRef(({className:t,...s},a)=>e.jsx(lp,{ref:a,className:me("flex cursor-default items-center justify-center py-1",t),...s,children:e.jsx(ps,{className:"h-4 w-4"})}));Vg.displayName=lp.displayName;const $e=o.forwardRef(({className:t,children:s,position:a="popper",...n},r)=>e.jsx(xb,{children:e.jsxs(op,{ref:r,className:me("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",a==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",t),position:a,...n,children:[e.jsx(Wg,{}),e.jsx(gb,{className:me("p-1",a==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:s}),e.jsx(Vg,{})]})}));$e.displayName=op.displayName;const _c=o.forwardRef(({className:t,...s},a)=>e.jsx(cp,{ref:a,className:me("py-1.5 pl-8 pr-2 text-sm font-semibold",t),...s}));_c.displayName=cp.displayName;const q=o.forwardRef(({className:t,children:s,...a},n)=>e.jsxs(dp,{ref:n,className:me("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t),...a,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(fb,{children:e.jsx(Xt,{className:"h-4 w-4"})})}),e.jsx(yb,{children:s})]}));q.displayName=dp.displayName;const t_=o.forwardRef(({className:t,...s},a)=>e.jsx(mp,{ref:a,className:me("-mx-1 my-1 h-px bg-muted",t),...s}));t_.displayName=mp.displayName;const Pt=o.forwardRef(({className:t,...s},a)=>e.jsx("div",{className:"relative w-full overflow-auto",children:e.jsx("table",{ref:a,className:me("w-full caption-bottom text-sm",t),...s})}));Pt.displayName="Table";const At=o.forwardRef(({className:t,...s},a)=>e.jsx("thead",{ref:a,className:me("[&_tr]:border-b",t),...s}));At.displayName="TableHeader";const Et=o.forwardRef(({className:t,...s},a)=>e.jsx("tbody",{ref:a,className:me("[&_tr:last-child]:border-0",t),...s}));Et.displayName="TableBody";const s_=o.forwardRef(({className:t,...s},a)=>e.jsx("tfoot",{ref:a,className:me("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",t),...s}));s_.displayName="TableFooter";const Ue=o.forwardRef(({className:t,...s},a)=>e.jsx("tr",{ref:a,className:me("border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted",t),...s}));Ue.displayName="TableRow";const H=o.forwardRef(({className:t,...s},a)=>e.jsx("th",{ref:a,className:me("h-12 px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0",t),...s}));H.displayName="TableHead";const G=o.forwardRef(({className:t,...s},a)=>e.jsx("td",{ref:a,className:me("p-4 align-middle [&:has([role=checkbox])]:pr-0",t),...s}));G.displayName="TableCell";const a_=o.forwardRef(({className:t,...s},a)=>e.jsx("caption",{ref:a,className:me("mt-4 text-sm text-muted-foreground",t),...s}));a_.displayName="TableCaption";const n_={active:"bg-emerald-500",pending:"bg-amber-500",grace:"bg-orange-500",lapsed:"bg-red-500",expired:"bg-muted-foreground/60",cancelled:"bg-muted-foreground
1/60",rejected:"bg-red-500",suspended:"bg-amber-500",archived:"bg-muted-foreground/40"},r_={active:"Member has a current, valid membership",pending:"Awaiting payment or approval",grace:"Membership expired â within the grace period to renew",lapsed:"Grace period ended without renewal",expired:"Membership has expired",cancelled:"Membership was cancelled",rejected:"Application was rejected by admin",suspended:"Membership temporarily suspended by admin",archived:"Member record archived"};function Gg({status:t}){return e.jsxs(fs,{children:[e.jsx(ys,{asChild:!0,children:e.jsxs("div",{className:"inline-flex cursor-default items-center gap-2",children:[e.jsx("span",{className:me("h-1.5 w-1.5 rounded-full",n_[t]||"bg-muted-foreground"),"aria-hidden":"true"}),e.jsx("span",{className:"text-xs font-medium capitalize text-foreground/85",children:t})]})}),e.jsx(hs,{children:r_[t]||t})]})}function i_(t){return t==null?"â":Array.isArray(t)?t.join(", ")||"â":typeof t=="boolean"?t?"Yes":"No":String(t)}function l_(t,s){const a=t?.[0]||"",n=s?.[0]||"";return`${a}${n}`.toUpperCase()||"?"}const co=[{key:"email",label:"Email",sortKey:"email",render:t=>t.email,className:"hidden sm:table-cell"},{key:"secondaryEmail",label:"Secondary Email",sortKey:"secondaryEmail",render:t=>t.secondary_email||"â",className:"hidden sm:table-cell"},{key:"organization",label:"Organization",sortKey:"organization",render:t=>t.organization||"â",className:"hidden sm:table-cell"},{key:"phone",label:"Phone",sortKey:"phone",render:t=>t.phone||"â",className:"hidden sm:table-cell"},{key:"city",label:"City",sortKey:"city",render:t=>t.city||"â",className:"hidden sm:table-cell"},{key:"state",label:"State",sortKey:"state",render:t=>t.state||"â",className:"hidden sm:table-cell"}
1,{key:"county",label:"County",sortKey:"county",render:t=>t.county||"â",className:"hidden sm:table-cell"},{key:"membershipType",label:"Type",sortKey:"membershipType",render:t=>t.membership_type_name||t.membership_type?.name||"â"},{key:"status",label:"Status",sortKey:"status",render:t=>e.jsx(Gg,{status:t.status})},{key:"joinDate",label:"Joined",sortKey:"joinDate",render:t=>t.join_date?Be(Ps(t.join_date),"MMM d, yyyy"):"â",className:"hidden sm:table-cell"},{key:"expires",label:"Expires",sortKey:"expires",render:t=>t.membership_end_date?Be(Ps(t.membership_end_date),"MMM d, yyyy"):"â",className:"hidden sm:table-cell"},{key:"autoRenew",label:"Auto-Renew",sortKey:"autoRenew",render:t=>t.auto_renew?"Yes":"No",className:"hidden sm:table-cell"},{key:"addressLine1",label:"Address",sortKey:"addressLine1",render:t=>t.address_line1||"â",className:"hidden sm:table-cell"},{key:"addressLine2",label:"Address 2",sortKey:"addressLine2",render:t=>t.address_line2||"â",className:"hidden sm:table-cell"},{key:"postalCode",label:"Postal Code",sortKey:"postalCode",render:t=>t.postal_code||"â",className:"hidden sm:table-cell"}
1,{key:"country",label:"Country",sortKey:"country",render:t=>t.country||"â",className:"hidden sm:table-cell"},{key:"membershipStart",label:"Start Date",sortKey:"membershipStart",render:t=>t.membership_start_date?Be(Ps(t.membership_start_date),"MMM d, yyyy"):"â",className:"hidden sm:table-cell"},{key:"showInDirectory",label:"Directory",sortKey:"showInDirectory",render:t=>t.show_in_directory?"Yes":"No",className:"hidden sm:table-cell"},{key:"tags",label:"Tags",sortKey:"",render:t=>t.tags?.length?e.jsx("div",{className:"flex flex-wrap gap-1",children:t.tags.map(s=>e.jsx(Ts,{variant:"secondary",className:"text-xs",children:s},s))}):"â",className:"hidden sm:table-cell"}],o_=["email","membershipType","status","expires"];function Mm({columnKey:t,sortKey:s,sortDir:a}){return s!==t?e.jsx(Eb,{className:"ml-1.5 h-3 w-3 text-muted-foreground/40"}):a==="desc"?e.jsx(fc,{className:"ml-1.5 h-3 w-3 text-foreground"}):e.jsx(yl,{className:"ml-1.5 h-3 w-3 text-foreground"})}function c_({members:t,onDelete:s,onApprove:a,onReject:n,selectedIds:r,onSelectOne:i,onSelectAll:l,allSelected:m,someSelected:c,visibleColumns:d,sortKey:u,sortDir:h,onSort:p,allColumnDefs:x}){const f=o.useRef(null);o.useEffect(()=>{f.current&&(f.current.indeterminate=!m&&!!c)},[m,c]);const b=kt(),N=!!r&&!!i&&!!l,w=(x||co).filter(v=>d.includes(v.key));return e.jsxs(Pt,{children:[e.jsx(At,{className:"bg-muted/30",children:e.jsxs(Ue,{className:"hover:bg-transparent",children:[N&&e.jsx(H,{className:"h-10 w-[40px]",children:e.jsx("input",{ref:f,type:"checkbox",checked:!!m,onChange:l,className:"h-4 w-4 rounded border-input",onClick:v=>v.stopPropagation()})}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:e.jsxs("button",{type:"button",className:"inline-flex items-center hover:text-foreground",onClick:()=>p?.("name"),children:["Name",e.jsx(Mm,{columnKey:"name",sortKey:u,sortDir:h})]})}),w.map(v=>e.jsx(H,{className:me("h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",v.className),children:v.sortKey?e.jsxs("button",{type:"button",className:"inline-flex items-center hover:text-foreground",onClick:()=>p?.(v.sortKey),children:[v.label,e.jsx(Mm,{columnKey:v.sortKey,sortKey:u,sortDir:h})]}):e.jsx("span",{children:v.label})},v.key)),e.jsx(H,{className:"h-10 w-[50px] sm:w-[180px]"})]})}),e.jsx(Et,{children:t.map(v=>e.jsxs(Ue,{className:"cursor-pointer hover:bg-brand-navy/[0.04] dark:hover:bg-brand-navy/10",onClick:()=>b(`/members/${v.id}`),children:[N&&e.jsx(G,{onClick:k=>k.stopPropagation(),children:e.jsx("input",{type:"checkbox",checked:r.has(v.id),onChange:()=>i(v.id),className:"h-4 w-4 rounded border-input"})}),e.jsx(G,{children:e.jsxs(je,{to:`/members/${v.id}`,className:"group flex items-center gap-3",onClick:k=>k.stopPropagation(),children:[e.jsx(ao,{className:"h-8 w-8 shrink-0 ring-1 ring-border/60",children:e.jsx(no,{className:"bg-brand-navy/10 text-[11px] font-semibold text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:l_(v.first_name,v.last_name)})}),e.jsxs("span",{className:"font-medium text-foreground transition-colors group-hover:text-brand-navy dark:group-hover:text-brand-navy/85",children:[v.first_name," ",v.last_name]})]})}),w.map(k=>e.jsx(G,{className:k.className,children:k.render(v)},k.key)),e.jsx(G,{onClick:k=>k.stopPropagation(),children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[v.status==="pending"&&e.jsxs("span",{className:"hidden sm:contents",children:[(v.membership_type_price??0)>0?e.jsx("span",{className:"px-2.5 text-xs font-medium text-amber-600 dark:text-amber-400",title:"This is a paid membership type â the member must complete payment to be activated.",children:"Awaiting payment"}):e.jsxs(g,{variant:"ghost",size:"sm",className:"h-8 bg-emerald-50 px-2.5 text-emerald-700 hover:bg-emerald-100 hover:text-emerald-800 dark:bg-emerald-950/30 dark:text-emerald-400 dark:hover:bg-emerald-950/50 dark:hover:text-emerald-300",onClick:()=>a(v),children:[e.jsx(Xt,{className:"mr-1 h-3.5 w-3.5"}),"Approve"]}),e.jsxs(g,{variant:"ghost",size:"sm",className:"h-8 bg-red-50 px-2.5 text-red-700 hover:bg-red-100 hover:text-red-800 dark:bg-red-950/30 dark:text-red-400 dark:hover:bg-red-950/50 dark:hover:text-red-300",onClick:()=>n(v),children:[e.jsx(ms,{className:"mr-1 h-3.5 w-3.5"}),"Reject"]})]}),e.jsxs(Ws,{children:[e.jsx(Vs,{asChild:!0,children:e.jsxs(g,{variant:"ghost",size:"icon",className:"h-8 w-8 min-h-[44px] min-w-[44px]",children:[e.jsx(Pn,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Open menu"})]})}),e.jsxs($s,{align:"end",children:[e.jsx(wt,{asChild:!0,children:e.jsxs(je,{to:`/members/${v.id}`,children:[e.jsx(ca,{className:"mr-2 h-4 w-4"}),"View"]}
1)}),e.jsx(wt,{asChild:!0,children:e.jsxs(je,{to:`/members/${v.id}/edit`,children:[e.jsx(Hs,{className:"mr-2 h-4 w-4"}),"Edit"]})}),e.jsxs(wt,{className:"text-destructive",onClick:()=>s(v),children:[e.jsx(Ft,{className:"mr-2 h-4 w-4"}),"Delete"]})]})]})]})})]},v.id))})]})}const mo={getTags:async t=>(await F.get(`/members/${t}/tags`)).data,addTags:async(t,s)=>(await F.post(`/members/${t}/tags`,{tags:s})).data,removeTags:async(t,s)=>(await F.delete(`/members/${t}/tags`,{data:{tags:s}})).data,getSuggestions:async t=>(await F.get("/members/tags/suggestions",{params:t?{society_id:t}:{}})).data,bulkTags:async(t,s,a,n)=>(await F.post("/members/bulk/tags",{member_ids:t,tags:s,action:a},{params:n?{society_id:n}:{}})).data};function Ai(){const{selectedSocietyId:t}=V();return re({queryKey:["societyTags",t],queryFn:()=>mo.getSuggestions(t||void 0),enabled:!!t})}function d_(t){const s=J();return W({mutationFn:a=>mo.addTags(t,a),onSuccess:()=>{s.invalidateQueries({queryKey:["members"]}),s.invalidateQueries({queryKey:["member",t]}),s.invalidateQueries({queryKey:["societyTags"]})}})}function m_(t){const s=J();return W({mutationFn:a=>mo.removeTags(t,a),onSuccess:()=>{s.invalidateQueries({queryKey:["members"]}),s.invalidateQueries({queryKey:["member",t]}),s.invalidateQueries({queryKey:["societyTags"]})}})}function u_(){const t=J(),{selectedSocietyId:s}=V();return W({mutationFn:({memberIds:a,tags:n,action:r})=>mo.bulkTags(a,n,r,s||void 0),onSuccess:()=>{t.invalidateQueries({queryKey:["members"]}),t.invalidateQueries({queryKey:["societyTags"]})}})}const Dm=[{value:"organization",label:"Organization"},{value:"city",label:"City"},{value:"state",label:"State"},{value:"county",label:"County"},{value:"phone",label:"Phone"},{value:"postal_code",label:"Postal Code"},{value:"tag",label:"Tag"}];function h_({search:t,onSearchChange:s,filterField:a,onFilterFieldChange:n,filterValue:r,onFilterValueChange:i,status:l,onStatusChange:m,membershipTypeId:c,onMembershipTypeChange:d,visibleColumns:u,onColumnsChange:h,allColumnDefs:p}){const{data:x}=oa(!1,!0),{data:f}=Ai(),b=p||co,N=w=>{u.includes(w)?h(u.filter(v=>v!==w)):h([...u,w])},j=Dm.find(w=>w.value===a)?.label;return e.jsxs("div",{className:"flex flex-col gap-4 sm:flex-row sm:items-center",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(ya,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(O,{id:"member-search",name:"member-search",placeholder:"Search membersâ¦",value:t,onChange:w=>s(w.target.value),className:"pl-9",autoComplete:"off","aria-label":"Search members"})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsxs(qe,{value:a||"none",onValueChange:w=>n(w==="none"?"":w),children:[e.jsxs(Le,{className:"w-full sm:w-[130px]",children:[e.jsx(Tb,{className:"mr-2 h-4 w-4 shrink-0 text-muted-foreground"}),e.jsx(Ie,{placeholder:"Filter byâ¦"})]}),e.jsxs($e,{children:[e.jsx(q,{value:"none",children:"Filter byâ¦"}),Dm.map(w=>e.jsx(q,{value:w.value,children:w.label},w.value))]})]}),a&&a!=="tag"&&e.jsxs("div",{className:"relative w-full sm:w-[160px]",children:[e.jsx(O,{id:"field-filter-value",name:"field-filter-value",placeholder:`Filter by ${j?.toLowerCase()}â¦`,value:r,onChange:w=>i(w.target.value),autoComplete:"off","aria-label":`Filter by ${j}`}),r&&e.jsx("button",{type:"button",onClick:()=>i(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground",children:e.jsx(ms,{className:"h-3.5 w-3.5"})})]}),a==="tag"&&e.jsxs(qe,{value:r||"none",onValueChange:w=>i(w==="none"?"":w),children:[e.jsx(Le,{className:"w-full sm:w-[160px]",children:e.jsx(Ie,{placeholder:"Select tagâ¦"})}),e.jsxs($e,{children:[e.jsx(q,{value:"none",children:"Select tagâ¦"}),(f||[]).map(w=>e.jsxs(q,{value:w.tag,children:[w.tag," (",w.count,")"]},w.tag))]})]})]}),e.jsxs(qe,{value:l,onValueChange:m,children:[e.jsx(Le,{className:"w-full sm:w-[150px]",children:e.jsx(Ie,{placeholder:"All statuses"})}),e.jsxs($e,{children:[e.jsx(q,{value:"all",children:"All statuses"}),e.jsx(q,{value:"active",children:"Active"}),e.jsx(q,{value:"pending",children:"Pending"}),e.jsx(q,{value:"grace",children:"Grace"}),e.jsx(q,{value:"lapsed",children:"Lapsed"}),e.jsx(q,{value:"expired",children:"Expired"}),e.jsx(q,{value:"cancelled",children:"Cancelled"}),e.jsx(q,{value:"rejected",children:"Rejected"}),e.jsx(q,{value:"suspended",children:"Suspended"}),e.jsx(q,{value:"archived",children:"Archived"})]})]}),e.jsxs(qe,{value:c,onValueChange:d,children:[e.jsx(Le,{className:"w-full sm:w-[200px]",children:e.jsx(Ie,{placeholder:"All types"})}),e.jsxs($e,{children:[e.jsx(q,{value:"all",children:"All types"}),x?.map(w=>e.jsx(q,{value:w.id,children:w.name},w.id))]})]}),e.jsxs(Ws,{children:[e.jsx(Vs,{asChild:!0,children:e.jsxs(g,{variant:"outline",size:"sm",className:"h-9 min-h-[44px]",children:[e.jsx(vp,{className:"mr-2 h-4 w-4"}),"Columns"]})}),e.jsxs($s,{align:"end",className:"w-[180px]",children:[e.jsx(so,{children:"Toggle columns"}),e.jsx(Aa,{}),b.map(w=>e.jsx(dg,{checked:u.includes(w.key),onCheckedChange:()=>N(w.key),onSelect:v=>v.preventDefault(),children:w.label},w.key))]})]})]})}function uo(t){return t.replace(/_/g," ").replace(/\b\w/g,s=>s.toUpperCase())}const Ed={getBadges:async t=>(await F.get(`/members/${t}/badges`)).data,awardBadge:async(t,s,a)=>(await F.post(`/members/${t}/badges`,{badge_type_id:s,note:a||null})).data,removeBadge:async(t,s)=>(await F.delete(`/members/${t}/badges`,{data:{badge_type_id:s}})).data};function p_(t){return re({queryKey:["memberBadges",t],queryFn:()=>Ed.getBadges(t),enabled:!!t})}function x_(t){const s=J();return W({mutationFn:({badge_type_id:a,note:n})=>Ed.awardBadge(t,a,n),onSuccess:()=>{s.invalidateQueries({queryKey:["memberBadges",t]})}})}function g_(t){const s=J();return W({mutationFn:a=>Ed.removeBadge(t,a),onSuccess:()=>{s.invalidateQueries({queryKey:["memberBadges",t]})}})}const rr={list:async(t,s=!1)=>{const a={society_id:t};s&&(a.include_inactive=!0);const{data:n}=await F.get("/badge-types",{params:a});return n},create:async(t,s)=>{const{data:a}=await F.post("/badge-types",t,{params:{society_id:s}});return a},update:async(t,s)=>{const{data:a}=await F.patch(`/badge-types/${t}`,s);return a},delete:async(t,s=!1)=>{await F.delete(`/badge-types/${t}`,{params:{force:s}})},uploadIcon:async(t,s)=>{const a=new FormData;a.append("file",s);const{data:n}=await F.post(`/badge-types/${t}/icon`,a,{headers:{"Content-Type":"multipart/form-data"}});return n},deleteIcon:async t=>{const{data:s}=await F.delete(`/badge-types/${t}/icon`);return s},reorder:async(t,s)=>{const{data:a}=await F.put("/badge-types/reorder",t,{params:{society_id:s}});return a}};function Yg(t,s=!1){return re({queryKey:["badgeTypes",t,s],queryFn:()=>rr.list(t,s),enabled:!!t})}function f_(t){const s=J();return W({mutationFn:a=>rr.create(a,t),onSuccess:()=>{s.invalidateQueries({queryKey:["badgeTypes",t]})}})}function y_(t){const s=J();return W({mutationFn:({id:a,...n})=>rr.update(a,n),onSuccess:()=>{s.invalidateQueries({queryKey:["badgeTypes",t]})}})}function b_(t){const s=J();return W({mutationFn:({id:a,force:n})=>rr.delete(a,n),onSuccess:()=>{s.invalidateQueries({queryKey:["badgeTypes",t]})}})}function j_(t){const s=J();return W({mutationFn:({id:a,file:n})=>rr.uploadIcon(a,n),onSuccess:()=>{s.invalidateQueries({queryKey:["badgeTypes",t]})}})}function v_(t){const s=J();return W({mutationFn:a=>rr.deleteIcon(a),onSuccess:()=>{s.invalidateQueries({queryKey:["badgeTypes",t]})}})}function w_(t){const s=J();return W({mutationFn:a=>rr.reorder(a,t),onSuccess:()=>{s.invalidateQueries({queryKey:["badgeTypes",t]})}})}const Js={getCommittees:async t=>(await F.get("/committees",{params:{society_id:t}})).data,getCommittee:async(t,s)=>(await F.get(`/committees/${t}`,{params:{society_id:s}})).data,createCommittee:async(t,s)=>(await F.post("/committees",t,{params:{society_id:s}})).data,updateCommittee:async(t,s,a)=>(await F.patch(`/committees/${t}`,s,{params:{society_id:a}})).data,deleteCommittee:async(t,s)=>{await F.delete(`/committees/${t}`,{params:{society_id:s}})},addMember:async(t,s,a)=>(await F.post(`/committees/${t}/members`,s,{params:{society_id:a}})).data,updateMember:async(t,s,a,n)=>(await F.patch(`/committees/${t}/members/${s}`,a,{params:{society_id:n}})).data,removeMember:async(t,s,a)=>{await F.delete(`/committees/${t}/members/${s}`,{params:{society_id:a}})},getMemberCommittees:async(t,s)=>(await F.get(`/committees/member/${t}`,{params:s?{society_id:s}:{}})).data,getOpenings:async t=>(await F.get("/committees/openings",{params:{society_id:t}})).data,createOpening:async(t,s,a)=>(await F.post(`/committees/${t}/openings`,s,{params:{society_id:a}})).data,updateOpening:async(t,s,a)=>(await F.patch(`/committees/openings/${t}`,s,{params:{society_id:a}})).data,deleteOpening:async(t,s)=>{await F.delete(`/committees/openings/${t}`,{params:{society_id:s}})},getApplications:async(t,s)=>(await F.get(`/committees/openings/${t}/applications`,{params:{society_id:s}})).data,reviewApplication:async(t,s,a,n)=>(await F.patch(`/committees/openings/${t}/applications/${s}`,a,{params:{society_id:n}})).data};function N_(){const{selectedSocietyId:t}=V();return re({queryKey:["admin","committees",t],queryFn:()=>Js.getCommittees(t),enabled:!!t})}function k_(t){const{selectedSocietyId:s}=V();return re({queryKey:["admin","committees",t,s],queryFn:()=>Js.getCommittee(t,s),enabled:!!s&&!!t})}function __(){const{selectedSocietyId:t}=V(),s=J();return W({mutationFn:a=>Js.createCommittee(a,t),onSuccess:()=>s.invalidateQueries({queryKey:["admin","committees"]})})}function S_(){const{selectedSocietyId:t}=V(),s=J();return W({mutationFn:({id:a,data:n})=>Js.updateCommittee(a,n,t),onSuccess:()=>s.invalidateQueries({queryKey:["admin","committees"]})})}function C_(){const{selectedSocietyId:t}=V(),s=J();return W({mutationFn:a=>Js.deleteCommittee(a,t),onSuccess:()=>s.invalidateQueries({queryKey:["admin","committees"]})})}function P_(){const{selectedSocietyId:t}=V(),s=J();return W({mutationFn:({committeeId:a,data:n})=>Js.addMember(a,n,t),onSuccess:()=>s.invalidateQueries({queryKey:["admin","committees"]})})}
1function A_(){const{selectedSocietyId:t}=V(),s=J();return W({mutationFn:({committeeId:a,cmId:n,data:r})=>Js.updateMember(a,n,r,t),onSuccess:()=>s.invalidateQueries({queryKey:["admin","committees"]})})}function E_(){const{selectedSocietyId:t}=V(),s=J();return W({mutationFn:({committeeId:a,cmId:n})=>Js.removeMember(a,n,t),onSuccess:()=>s.invalidateQueries({queryKey:["admin","committees"]})})}function T_(t){const{selectedSocietyId:s}=V();return re({queryKey:["member-committees",t],queryFn:()=>Js.getMemberCommittees(t,s||void 0),enabled:!!t})}function F_(){const{selectedSocietyId:t}=V();return re({queryKey:["admin","committee-openings",t],queryFn:()=>Js.getOpenings(t),enabled:!!t})}function R_(){const{selectedSocietyId:t}=V(),s=J();return W({mutationFn:({committeeId:a,data:n})=>Js.createOpening(a,n,t),onSuccess:()=>s.invalidateQueries({queryKey:["admin","committee-openings"]})})}function M_(){const{selectedSocietyId:t}=V(),s=J();return W({mutationFn:({openingId:a,data:n})=>Js.updateOpening(a,n,t),onSuccess:()=>s.invalidateQueries({queryKey:["admin","committee-openings"]})})}function D_(){const{selectedSocietyId:t}=V(),s=J();return W({mutationFn:a=>Js.deleteOpening(a,t),onSuccess:()=>s.invalidateQueries({queryKey:["admin","committee-openings"]})})}function L_(t){const{selectedSocietyId:s}=V();return re({queryKey:["admin","committee-applications",t,s],queryFn:()=>Js.getApplications(t,s),enabled:!!s&&!!t})}function $_(){const{selectedSocietyId:t}=V(),s=J();return W({mutationFn:({openingId:a,appId:n,data:r})=>Js.reviewApplication(a,n,r,t),onSuccess:()=>{s.invalidateQueries({queryKey:["admin","committee-applications"]}),s.invalidateQueries({queryKey:["admin","committee-openings"]}),s.invalidateQueries({queryKey:["admin","committees"]})}})}const q_={active:"bg-emerald-500",pending:"bg-amber-500",grace:"bg-orange-500",lapsed:"bg-red-500",expired:"bg-red-500",cancelled:"bg-muted-foreground/60",suspended:"bg-red-500",archived:"bg-muted-foreground/60"},I_={active:"Member has a current, valid membership",pending:"Awaiting payment or approval",grace:"Membership expired â within the grace period to renew",lapsed:"Grace period ended without renewal",expired:"Membership has expired",cancelled:"Membership was cancelled",suspended:"Membership temporarily suspended by admin",archived:"Member record archived"};function O_({member:t,onSwitchToHistory:s}){const{data:a}=Ex(t.id),{data:n}=vv(t.id),{data:r}=Ai(),{data:i}=er(),l={};for(const U of i||[])l[U.field_key]=U.label;const m=d_(t.id),c=m_(t.id),{data:d}=p_(t.id),{data:u}=Yg(t.society_id),h=x_(t.id),p=g_(t.id),{data:x}=T_(t.id),[f,b]=o.useState(""),[N,j]=o.useState(""),[w,v]=o.useState(""),[k,S]=o.useState(!1),_=o.useRef(null),y=t.tags||[],C=(r||[]).filter(U=>!y.includes(U.tag)).filter(U=>!w||U.tag.includes(w.toLowerCase())),P=U=>{const D=U.trim().toLowerCase();!D||y.includes(D)||(m.mutate([D]),v(""),S(!1))},A=U=>{U.key==="Enter"&&(U.preventDefault(),P(w)),U.key==="Escape"&&S(!1)},E=U=>{c.mutate([U])},Q=[t.address_line1,t.address_line2,t.city,t.state,t.county,t.postal_code,t.country].filter(Boolean).join(", ");return e.jsxs("div",{className:"grid gap-6 md:grid-cols-2",children:[e.jsxs(L,{children:[e.jsx(ne,{children:e.jsxs(ie,{className:"flex items-center gap-2.5",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx($t,{className:"h-4 w-4"})}),"Contact information"]})}),e.jsxs($,{className:"space-y-4",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[e.jsx($t,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),e.jsx("a",{href:`mailto:${t.email}`,className:"truncate text-primary hover:underline",children:t.email})]}),t.secondary_email&&e.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[e.jsx($t,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),e.jsx("a",{href:`mailto:${t.secondary_email}`,className:"truncate text-primary hover:underline",children:t.secondary_email}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"(secondary)"})]}),t.organization&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ga,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:t.organization})]}),t.phone&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Jc,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:t.phone})]}),Q&&e.jsxs("div",{className:"flex min-w-0 items-start gap-3",children:[e.jsx(Fa,{className:"mt-0.5 h-4 w-4 shrink-0 text-muted-foreground"}),e.jsx("span",{className:"break-words",children:Q})]})]})]}),e.jsxs(L,{children:[e.jsx(ne,{children:e.jsxs(ie,{className:"flex items-center gap-2.5",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy
1/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(xa,{className:"h-4 w-4"})}),"Tags"]})}),e.jsxs($,{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[y.map(U=>e.jsxs(Ts,{variant:"secondary",className:"gap-1 pr-1",children:[U,e.jsx("button",{type:"button",onClick:()=>E(U),className:"ml-0.5 rounded-full p-0.5 hover:bg-black/10",disabled:c.isPending,children:e.jsx(ms,{className:"h-3 w-3"})})]},U)),y.length===0&&!w&&e.jsx("span",{className:"text-sm text-muted-foreground",children:"No tags"})]}),e.jsxs("div",{className:"relative",children:[e.jsx(O,{ref:_,placeholder:"Add tagâ¦",value:w,onChange:U=>{v(U.target.value),S(!0)},onFocus:()=>S(!0),onBlur:()=>{setTimeout(()=>S(!1),150)},onKeyDown:A,className:"h-8 text-sm",disabled:m.isPending}),m.isPending&&e.jsx(He,{className:"absolute right-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 animate-spin text-muted-foreground"}),k&&C.length>0&&e.jsx("div",{className:"absolute z-10 mt-1 max-h-[160px] w-full overflow-y-auto rounded-md border bg-popover shadow-md",children:C.map(U=>e.jsxs("button",{type:"button",className:"flex w-full items-center justify-between px-3 py-1.5 text-sm hover:bg-accent",onMouseDown:D=>D.preventDefault(),onClick:()=>P(U.tag),children:[e.jsx("span",{children:U.tag}),e.jsx("span",{className:"text-xs text-muted-foreground",children:U.count})]},U.tag))})]})]})]}),e.jsxs(L,{children:[e.jsx(ne,{children:e.jsxs(ie,{className:"flex items-center gap-2.5",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(qn,{className:"h-4 w-4"})}),"Badges"]})}),e.jsxs($,{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[d&&d.map(U=>e.jsxs(fs,{children:[e.jsx(ys,{asChild:!0,children:e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full px-2.5 py-0.5 text-xs font-medium text-white",style:{backgroundColor:U.badge_type_color},children:[U.badge_type_icon_url?e.jsx("img",{src:`${ds}${U.badge_type_icon_url}`,alt:"",className:"h-3 w-3 rounded-full object-cover"}):e.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-white/30"}),U.badge_type_name,U.auto_detected&&e.jsx("span",{className:"opacity-60",children:"(auto)"}),!U.auto_detected&&e.jsx("button",{type:"button",onClick:()=>p.mutate(U.badge_type_id),className:"ml-0.5 rounded-full p-0.5 hover:bg-black/10",disabled:p.isPending,children:e.jsx(ms,{className:"h-3 w-3"})})]})}),e.jsxs(hs,{children:[U.note||U.badge_type_name,U.auto_detected&&" â detected from committee role"]})]},U.badge_type_id)),(!d||d.length===0)&&e.jsx("span",{className:"text-sm text-muted-foreground",children:"No badges"})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(qe,{value:f,onValueChange:b,children:[e.jsx(Le,{className:"h-8 flex-1 text-sm",children:e.jsx(Ie,{placeholder:"Award badgeâ¦"})}),e.jsx($e,{children:(u||[]).filter(U=>!d?.some(D=>D.badge_type_id===U.id)).map(U=>e.jsx(q,{value:U.id,children:U.name},U.id))})]}),e.jsx(O,{placeholder:"Note (optional)",value:N,onChange:U=>j(U.target.value),className:"h-8 flex-1 text-sm"}),e.jsx(g,{size:"sm",className:"h-8",disabled:!f||h.isPending,onClick:()=>{f&&h.mutate({badge_type_id:f,note:N||void 0},{onSuccess:()=>{b(""),j("")}})},children:h.isPending?e.jsx(He,{className:"h-3.5 w-3.5 animate-spin"}):"Award"})]})]})]}),x&&x.length>0&&e.jsxs(L,{children:[e.jsx(ne,{children:e.jsxs(ie,{className:"flex items-center gap-2.5",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(Lt,{className:"h-4 w-4"})}),"Committees (",x.length,")"]})}),e.jsx($,{className:"space-y-2",children:x.map(U=>{const K={chair:"bg-blue-100 text-blue-800",vice_chair:"bg-indigo-100 text-indigo-800",secretary:"bg-purple-100 text-purple-800",treasurer:"bg-green-100 text-green-800",member:"bg-gray-100 text-gray-800"}[U.role]||"bg-gray-100 text-gray-800";return e.jsxs("div",{className:"flex items-center justify-between rounded-md border p-3",children:[e.jsx("span",{className:"font-medium",children:U.committee_name}),e.jsx("span",{className:`inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium ${K}`,children:U.role.replace("_"," ")})]},U.committee_id)})})]}),e.jsxs(L,{children:[e.jsx(ne,{children:e.jsxs(ie,{className:"flex items-center gap-2.5",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy
1/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(Zc,{className:"h-4 w-4"})}),"Membership"]})}),e.jsxs($,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Status"}),e.jsxs(fs,{children:[e.jsx(ys,{asChild:!0,children:e.jsxs("span",{className:"inline-flex cursor-default items-center gap-1.5 whitespace-nowrap capitalize",children:[e.jsx("span",{className:`h-1.5 w-1.5 shrink-0 rounded-full ${q_[t.status]||"bg-muted-foreground/60"}`}),e.jsx("span",{className:"text-xs font-medium",children:t.status})]})}),e.jsx(hs,{children:I_[t.status]||t.status})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Type"}),e.jsx("span",{className:"font-medium",children:t.membership_type_name||t.membership_type?.name||"â"})]}),t.join_date&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Yt,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{children:["Joined ",Be(Ps(t.join_date),"MMM d, yyyy")]})]}),t.membership_end_date&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Qt,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{children:[t.membership_end_date<kd()?"Expired":"Expires"," ",Be(Ps(t.membership_end_date),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(St,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{children:["Auto-renew:"," ",t.auto_renew?e.jsx("span",{className:"font-medium text-green-600 dark:text-green-400",children:"On"}):e.jsx("span",{className:"font-medium text-muted-foreground",children:"Off"})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ea,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:t.last_login_at?e.jsxs(e.Fragment,{children:["Last active ",Be(Ct(t.last_login_at),"MMM d, yyyy h:mm a")]}):e.jsx("span",{className:"text-muted-foreground",children:"Never logged in"})})]})]})]}),a&&a.payment_count>0&&e.jsxs(L,{children:[e.jsx(ne,{children:e.jsxs(ie,{className:"flex items-center gap-2.5",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(Ua,{className:"h-4 w-4"})}),"Payment summary"]})}),e.jsxs($,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Total paid"}),e.jsxs("span",{className:"font-medium",children:["$",a.total_paid.toFixed(2)]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Payments"}),e.jsx("span",{className:"font-medium",children:a.payment_count})]}),a.last_payment_date&&e.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[e.jsx(Ua,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),e.jsxs("span",{className:"truncate",children:["Last: $",a.last_payment_amount?.toFixed(2)," on"," ",Be(Ps(a.last_payment_date),"MMM d, yyyy")]})]}),s&&e.jsx("button",{onClick:s,className:"text-sm text-primary hover:underline",children:"View full history"})]})]}),n&&n.length>0&&e.jsxs(L,{children:[e.jsx(ne,{children:e.jsxs(ie,{className:"flex items-center gap-2.5",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(ml,{className:"h-4 w-4"})}),"Events (",n.length,")"]})}),e.jsx($,{className:"space-y-3",children:n.map(U=>e.jsxs(je,{to:`/events?event=${U.event_id}`,className:"flex min-w-0 items-start justify-between gap-2 rounded-md border p-3 transition-colors hover:bg-muted",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate font-medium",children:U.event_name}),e.jsxs("div",{className:"mt-1 flex flex-wrap gap-x-3 gap-y-1 text-xs text-muted-foreground",children:[U.event_start_date&&e.jsx("span",{children:Be(Ps(U.event_start_date),"MMM d, yyyy")}),U.event_location&&e.jsx("span",{className:"truncate",children:U.event_location})]})]}),e.jsxs("div",{className:"shrink-0 text-right",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5 whitespace-nowrap capitalize",children:[e.jsx("span",{className:`h-1.5 w-1.5 shrink-0 rounded-full ${U.status==="confirmed"?"bg-emerald-500":"bg-muted-foreground
1/60"}`}),e.jsx("span",{className:"text-xs font-medium",children:U.status})]}),U.price_paid>0&&e.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:["$",U.price_paid.toFixed(2)]})]})]},U.id))})]}),t.admin_notes&&e.jsxs(L,{className:"md:col-span-2",children:[e.jsx(ne,{children:e.jsxs(ie,{className:"flex items-center gap-2.5",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(Fb,{className:"h-4 w-4"})}),"Notes"]})}),e.jsx($,{children:e.jsx("p",{className:"whitespace-pre-wrap",children:t.admin_notes})})]}),t.custom_fields&&Object.keys(t.custom_fields).length>0&&e.jsxs(L,{className:"md:col-span-2",children:[e.jsx(ne,{children:e.jsxs(ie,{className:"flex items-center gap-2.5",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(Rb,{className:"h-4 w-4"})}),"Custom fields"]})}),e.jsx($,{children:e.jsx("dl",{className:"grid gap-4 sm:grid-cols-2",children:Object.entries(t.custom_fields).map(([U,D])=>e.jsxs("div",{children:[e.jsx("dt",{className:"text-sm text-muted-foreground",children:l[U]||uo(U)}),e.jsx("dd",{className:"font-medium",children:String(D)})]},U))})})]})]})}function Hg({member:t,open:s,onOpenChange:a,onConfirm:n,isDeleting:r}){return e.jsx(Fe,{open:s,onOpenChange:a,children:e.jsxs(Te,{children:[e.jsxs(Ae,{children:[e.jsx(Ee,{children:"Delete Member"}),e.jsxs(tt,{children:["Are you sure you want to delete"," ",e.jsxs("strong",{children:[t?.first_name," ",t?.last_name]}),"? This action cannot be undone."]})]}),e.jsxs(Ge,{children:[e.jsx(g,{variant:"outline",onClick:()=>a(!1),disabled:r,children:"Cancel"}),e.jsx(g,{variant:"destructive",onClick:n,disabled:r,children:r?"Deleting...":"Delete"})]})]})})}function U_({rows:t=10}){return e.jsxs(Pt,{children:[e.jsx(At,{children:e.jsxs(Ue,{children:[e.jsx(H,{children:"Name"}),e.jsx(H,{children:"Email"}),e.jsx(H,{children:"Membership Type"}),e.jsx(H,{children:"Status"}),e.jsx(H,{children:"Expires"}),e.jsx(H,{className:"w-[50px]"})]})}),e.jsx(Et,{children:[...Array(t)].map((s,a)=>e.jsxs(Ue,{children:[e.jsx(G,{children:e.jsx(Y,{className:"h-4 w-32"})}),e.jsx(G,{children:e.jsx(Y,{className:"h-4 w-48"})}),e.jsx(G,{children:e.jsx(Y,{className:"h-4 w-24"})}),e.jsx(G,{children:e.jsx(Y,{className:"h-5 w-16 rounded-full"})}),e.jsx(G,{children:e.jsx(Y,{className:"h-4 w-24"})}),e.jsx(G,{children:e.jsx(Y,{className:"h-8 w-8"})})]},a))})]})}function z_({title:t="No members found",description:s="Get started by adding your first member.",showAddButton:a=!0}){return e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx("div",{className:"rounded-full bg-muted p-4",children:e.jsx(Lt,{className:"h-8 w-8 text-muted-foreground"})}),e.jsx("h3",{className:"mt-4 text-lg font-semibold",children:t}),e.jsx("p",{className:"mt-2 max-w-sm text-sm text-muted-foreground",children:s}),a&&e.jsx(g,{asChild:!0,className:"mt-6",children:e.jsxs(je,{to:"/members/new",children:[e.jsx(Rt,{className:"mr-2 h-4 w-4"}),"Add Member"]})})]})}const ot=o.forwardRef(({className:t,...s},a)=>e.jsx(up,{ref:a,className:me("peer h-4 w-4 shrink-0 rounded-sm border border-primary ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground",t),...s,children:e.jsx(wb,{className:me("flex items-center justify-center text-current"),children:e.jsx(Xt,{className:"h-4 w-4"})})}));ot.displayName=up.displayName;const B_=[{value:"pending",label:"Pending"},{value:"active",label:"Active"},{value:"grace",label:"Grace"},{value:"lapsed",label:"Lapsed"},{value:"expired",label:"Expired"},{value:"cancelled",label:"Cancelled"},{value:"suspended",label:"Suspended"},{value:"archived",label:"Archived"}];function K_({member:t}){const[s,a]=o.useState(!1),[n,r]=o.useState(t.status),[i,l]=o.useState(""),[m,c]=o.useState(""),[d,u]=o.useState(null),h=gv(),p=async()=>{u(null);try{await h.mutateAsync({id:t.id,data:{new_status:n,reason:i,extend_membership_days:m?parseInt(m,10):null}}),u({type:"success",message:`Status changed to ${n}`}),a(!1),l(""),c("")}catch{u({type:"error",message:"Could not override status. Please try again."})}};return e.jsxs(L,{children:[e.jsxs(ne,{children:[e.jsxs(ie,{className:"flex items-center gap-2.5",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy
1/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(Kc,{className:"h-4 w-4"})}),"Manual status override"]}),e.jsx(Ci,{children:"Use only when automatic status rules don't apply"})]}),e.jsxs($,{className:"space-y-4",children:[d&&e.jsx("p",{className:`text-sm ${d.type==="success"?"text-green-600":"text-destructive"}`,children:d.message}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(ot,{id:"confirm-override",checked:s,onCheckedChange:x=>{a(!!x),u(null)}}),e.jsx(T,{htmlFor:"confirm-override",className:"cursor-pointer text-sm",children:"I understand this overrides automatic status management"})]}),s&&e.jsxs("div",{className:"space-y-4 border-t pt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{children:"New status"}),e.jsxs(qe,{value:n,onValueChange:x=>r(x),children:[e.jsx(Le,{children:e.jsx(Ie,{})}),e.jsx($e,{children:B_.map(x=>e.jsx(q,{value:x.value,children:x.label},x.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{children:"Reason (required)"}),e.jsx(It,{placeholder:"Board approved extension, administrative correction, etc.",value:i,onChange:x=>l(x.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{children:"Extend membership by days (optional)"}),e.jsx(O,{type:"number",min:"0",placeholder:"e.g. 30",value:m,onChange:x=>c(x.target.value)})]}),e.jsx(g,{onClick:p,disabled:!i.trim()||h.isPending,children:h.isPending?"Overriding...":"Override Status"})]})]})]})}const Q_={create:{icon:fa,color:"text-blue-600 dark:text-blue-400",bgColor:"bg-blue-100 dark:bg-blue-900/30"},update:{icon:Db,color:"text-gray-600 dark:text-gray-400",bgColor:"bg-gray-100 dark:bg-gray-800"},delete:{icon:Ft,color:"text-red-600 dark:text-red-400",bgColor:"bg-red-100 dark:bg-red-900/30"},status_override:{icon:Kc,color:"text-red-600 dark:text-red-400",bgColor:"bg-red-100 dark:bg-red-900/30"},status_auto_change:{icon:St,color:"text-amber-600 dark:text-amber-400",bgColor:"bg-amber-100 dark:bg-amber-900/30"},payment_completed:{icon:Qt,color:"text-green-600 dark:text-green-400",bgColor:"bg-green-100 dark:bg-green-900/30"},payment_failed:{icon:Qt,color:"text-red-600 dark:text-red-400",bgColor:"bg-red-100 dark:bg-red-900/30"},payment:{icon:Qt,color:"text-green-600 dark:text-green-400",bgColor:"bg-green-100 dark:bg-green-900/30"},refund_issued:{icon:fi,color:"text-amber-600 dark:text-amber-400",bgColor:"bg-amber-100 dark:bg-amber-900/30"},subscription_created:{icon:Zc,color:"text-green-600 dark:text-green-400",bgColor:"bg-green-100 dark:bg-green-900/30"},subscription_cancelled:{icon:wp,color:"text-red-600 dark:text-red-400",bgColor:"bg-red-100 dark:bg-red-900/30"},subscription_renewed:{icon:St,color:"text-green-600 dark:text-green-400",bgColor:"bg-green-100 dark:bg-green-900/30"},email_sent:{icon:$t,color:"text-blue-600 dark:text-blue-400",bgColor:"bg-blue-100 dark:bg-blue-900/30"},login:{icon:Xc,color:"text-gray-600 dark:text-gray-400",bgColor:"bg-gray-100 dark:bg-gray-800"},logout:{icon:oi,color:"text-gray-600 dark:text-gray-400",bgColor:"bg-gray-100 dark:bg-gray-800"},password_change:{icon:An,color:"text-amber-600 dark:text-amber-400",bgColor:"bg-amber-100 dark:bg-amber-900/30"},profile_self_update:{icon:Mb,color:"text-blue-600 dark:text-blue-400",bgColor:"bg-blue-100 dark:bg-blue-900/30"},member_approved:{icon:Kl,color:"text-green-600 dark:text-green-400",bgColor:"bg-green-100 dark:bg-green-900/30"},member_rejected:{icon:bp,color:"text-red-600 dark:text-red-400",bgColor:"bg-red-100 dark:bg-red-900/30"},member_impersonated:{icon:ca,color:"text-purple-600 dark:text-purple-400",bgColor:"bg-purple-100 dark:bg-purple-900/30"},invoice_created:{icon:cs,color:"text-blue-600 dark:text-blue-400",bgColor:"bg-blue-100 dark:bg-blue-900/30"},invoice_sent:{icon:Pr,color:"text-blue-600 dark:text-blue-400",bgColor:"bg-blue-100 dark:bg-blue-900/30"},invoice_paid:{icon:cs,color:"text-green-600 dark:text-green-400",bgColor:"bg-green-100 dark:bg-green-900/30"},invoice_voided:{icon:Ca,color:"text-red-600 dark:text-red-400",bgColor:"bg-red-100 dark:bg-red-900/30"}
1,invoice_batch_created:{icon:gi,color:"text-blue-600 dark:text-blue-400",bgColor:"bg-blue-100 dark:bg-blue-900/30"},payment_method_updated:{icon:Qt,color:"text-blue-600 dark:text-blue-400",bgColor:"bg-blue-100 dark:bg-blue-900/30"}},W_={create:{label:"Created",dot:"bg-emerald-500"},update:{label:"Updated",dot:"bg-amber-500"},delete:{label:"Deleted",dot:"bg-red-500"},status_override:{label:"Status override",dot:"bg-red-500"},status_auto_change:{label:"Auto status change",dot:"bg-amber-500"},payment_completed:{label:"Payment",dot:"bg-orange-500"},payment_failed:{label:"Payment failed",dot:"bg-red-500"},payment:{label:"Payment",dot:"bg-orange-500"},refund_issued:{label:"Refund",dot:"bg-amber-500"},subscription_created:{label:"Subscription started",dot:"bg-emerald-500"},subscription_cancelled:{label:"Subscription cancelled",dot:"bg-red-500"},subscription_renewed:{label:"Subscription renewed",dot:"bg-emerald-500"},email_sent:{label:"Email sent",dot:"bg-muted-foreground/60"},login:{label:"Login",dot:"bg-muted-foreground/60"},logout:{label:"Logout",dot:"bg-muted-foreground/60"},password_change:{label:"Password changed",dot:"bg-muted-foreground/60"},profile_self_update:{label:"Profile updated",dot:"bg-muted-foreground/60"},member_approved:{label:"Approved",dot:"bg-emerald-500"},member_rejected:{label:"Rejected",dot:"bg-red-500"},member_impersonated:{label:"Viewed as member",dot:"bg-muted-foreground/60"},invoice_created:{label:"Invoice created",dot:"bg-orange-500"},invoice_sent:{label:"Invoice sent",dot:"bg-orange-500"},invoice_paid:{label:"Invoice paid",dot:"bg-emerald-500"},invoice_voided:{label:"Invoice voided",dot:"bg-red-500"},invoice_batch_created:{label:"Batch invoiced",dot:"bg-orange-500"},payment_method_updated:{label:"Card updated",dot:"bg-muted-foreground/60"},export:{label:"Export",dot:"bg-muted-foreground/60"},import:{label:"Import",dot:"bg-muted-foreground/60"}},V_={all:[],profile:["create","update","delete","profile_self_update"],status:["status_override","status_auto_change"],payments:["payment","payment_completed","payment_failed","refund_issued","subscription_created","subscription_cancelled","subscription_renewed"],emails:["email_sent"],logins:["login"]},G_={first_name:"First Name",last_name:"Last Name",email:"Email",phone:"Phone",address_line1:"Address",address_line2:"Address Line 2",city:"City",state:"State",postal_code:"Postal Code",country:"Country",membership_type_id:"Membership Type",membership_start_date:"Membership Start",membership_end_date:"Membership End",join_date:"Join Date",status:"Status",is_active:"Active",auto_renew:"Auto Renew",show_in_directory:"Show in Directory",custom_fields:"Custom Fields",grace_period_days:"Grace Period (Days)",dues_cycle_start_month:"Dues Cycle Start Month",dues_cycle_start_day:"Dues Cycle Start Day",fellowship_end_date:"Fellowship End Date",residency_end_date:"Residency End Date",hashed_password:"Password"};function Lm(t){return G_[t]||t.replace(/_/g," ").replace(/\b\w/g,s=>s.toUpperCase())}function Y_(t){const s=Ct(t);return nd(s)?"Today":mj(s)?"Yesterday":uj(s)?"This Week":hj(s)?"This Month":"Earlier"}function H_(t,s){if(!t)return"";const a=Object.keys(t);if(s==="payment_completed"||s==="payment"){const r=t.amount;if(r!=null)return`Payment $${Number(r).toFixed(2)}`}if(s==="payment_failed"){const r=t.amount;if(r!=null)return`Failed payment $${Number(r).toFixed(2)}`}if(s==="refund_issued"){const r=t.amount;if(r!=null)return`Refund $${Number(r).toFixed(2)}`}const n=a.filter(r=>{const i=t[r];return i&&typeof i=="object"&&"old"in i&&"new"in i});return n.length>0?`Changed ${n.length} field${n.length>1?"s":""}`:a.length>0?`${a.length} detail${a.length>1?"s":""}`:""}const J_=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Z_({memberId:t}){const[s,a]=o.useState(1),[n,r]=o.useState("all"),[i,l]=o.useState(new Set),{data:m,isLoading:c}=bv(t,s),{data:d}=oa(!0),u=o.useMemo(()=>{const w={};if(d)for(const v of d)w[v.id]=v.name;return w},[d]),h=(w,v)=>{const k=String(v??"â");return w==="membership_type_id"&&J_.test(k)?u[k]||k:w==="hashed_password"?"â¢â¢â¢â¢â¢â¢â¢â¢":k}
1,p=m?.items??[],x=m?.total??0,f=s*20<x,b=o.useMemo(()=>{if(n==="all")return p;const w=V_[n]||[];return p.filter(v=>w.includes(v.action))},[p,n]),N=o.useMemo(()=>{const w=[];let v=null;for(const k of b){const S=Y_(k.created_at);S!==v&&(v=S,w.push({label:S,logs:[]})),w[w.length-1].logs.push(k)}return w},[b]),j=w=>{l(v=>{const k=new Set(v);return k.has(w)?k.delete(w):k.add(w),k})};return c&&s===1?e.jsx("div",{className:"space-y-4",children:Array.from({length:5}).map((w,v)=>e.jsx(Y,{className:"h-16 w-full"},v))}):b.length===0&&!c?e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"flex justify-end",children:e.jsxs(qe,{value:n,onValueChange:r,children:[e.jsx(Le,{className:"w-48",children:e.jsx(Ie,{placeholder:"Filter"})}),e.jsxs($e,{children:[e.jsx(q,{value:"all",children:"All Activity"}),e.jsx(q,{value:"profile",children:"Profile Updates"}),e.jsx(q,{value:"status",children:"Status Changes"}),e.jsx(q,{value:"payments",children:"Payments"}),e.jsx(q,{value:"emails",children:"Emails"}),e.jsx(q,{value:"logins",children:"Logins"})]})]})}),e.jsx("div",{className:"rounded-md border bg-gray-50 py-12 text-center",children:e.jsx("p",{className:"text-muted-foreground",children:"No audit history for this member."})})]}):e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"flex justify-end",children:e.jsxs(qe,{value:n,onValueChange:r,children:[e.jsx(Le,{className:"w-48",children:e.jsx(Ie,{placeholder:"Filter"})}),e.jsxs($e,{children:[e.jsx(q,{value:"all",children:"All Activity"}),e.jsx(q,{value:"profile",children:"Profile Updates"}),e.jsx(q,{value:"status",children:"Status Changes"}),e.jsx(q,{value:"payments",children:"Payments"}),e.jsx(q,{value:"emails",children:"Emails"}),e.jsx(q,{value:"logins",children:"Logins"})]})]})}),e.jsx("div",{className:"space-y-0",children:N.map(w=>e.jsxs("div",{children:[e.jsx("div",{className:"mb-2 py-2",children:e.jsx("span",{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:w.label})}),w.logs.map((v,k)=>{const S=W_[v.action]||{label:v.action,dot:"bg-muted-foreground/60"},_=Q_[v.action],y=_?.icon,C=v.changes,P=C&&Object.keys(C).length>0,A=i.has(v.id),E=H_(C,v.action),Q=k===w.logs.length-1;return e.jsxs("div",{className:"relative flex gap-4 pb-6",children:[!Q&&e.jsx("div",{className:"absolute bottom-0 left-[15px] top-9 w-px bg-border"}),e.jsx("div",{className:`relative mt-1 flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-full ${_?_.bgColor:"bg-gray-100"}`,children:y?e.jsx(y,{className:`h-4 w-4 ${_.color}`}):e.jsx("div",{className:"h-3 w-3 rounded-full border-2 border-primary bg-background"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5 whitespace-nowrap",children:[e.jsx("span",{className:`h-1.5 w-1.5 shrink-0 rounded-full ${S.dot}`}),e.jsx("span",{className:"text-xs font-medium",children:S.label})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Be(Ct(v.created_at),"MMM d, yyyy h:mm a")})]}),e.jsx("p",{className:"mt-1 text-sm",children:v.description}),P&&e.jsxs("div",{className:"mt-1",children:[e.jsxs("button",{onClick:()=>j(v.id),className:"flex items-center gap-1 text-xs text-muted-foreground transition-colors hover:text-foreground",children:[A?e.jsx(ps,{className:"h-3 w-3"}):e.jsx(ts,{className:"h-3 w-3"}),e.jsx("span",{children:E||"View details"})]}),A&&e.jsx("div",{className:"mt-2 space-y-1 rounded-md bg-muted/50 p-2 text-xs",children:Object.entries(C).map(([U,D])=>{if(U==="reason")return e.jsxs("div",{className:"text-muted-foreground",children:[e.jsx("span",{className:"font-medium",children:"Reason:"})," ",String(D)]},U);if(U==="extended_days")return e.jsxs("div",{className:"text-muted-foreground",children:[e.jsx("span",{className:"font-medium",children:"Extended by:"})," ",String(D)," days"]},U);const K=D;return K&&typeof K=="object"&&"old"in K&&"new"in K?e.jsxs("div",{className:"text-muted-foreground",children:[e.jsxs("span",{className:"font-medium",children:[Lm(U),":"]})," ",e.jsx("span",{className:"line-through",children:h(U,K.old)})," ",e.jsx("span",{className:"text-foreground",children:h(U,K.new)})]},U):e.jsxs("div",{className:"text-muted-foreground",children:[e.jsxs("span",{className:"font-medium",children:[Lm(U),":"]})," ",h(U,D)]},U)})})]})]})]},v.id)})]},w.label))}),f&&e.jsx("div",{className:"flex justify-center pt-2",children:e.jsx(g,{variant:"outline",size:"sm",onClick:()=>a(w=>
1w+1),disabled:c,children:c?"Loading...":"Load More"})})]})}function X_({member:t,open:s,onOpenChange:a,onConfirm:n,isRejecting:r}){const[i,l]=o.useState(""),m=d=>{d||l(""),a(d)},c=()=>{n(i.trim()||void 0),l("")};return e.jsx(Fe,{open:s,onOpenChange:m,children:e.jsxs(Te,{children:[e.jsxs(Ae,{children:[e.jsx(Ee,{children:"Reject Application"}),e.jsxs(tt,{children:["Are you sure you want to reject"," ",e.jsxs("strong",{children:[t?.first_name," ",t?.last_name]}),"'s application?"]})]}),e.jsx(It,{placeholder:"Reason for rejection (optional)",value:i,onChange:d=>l(d.target.value),rows:3}),e.jsxs(Ge,{children:[e.jsx(g,{variant:"outline",onClick:()=>m(!1),disabled:r,children:"Cancel"}),e.jsx(g,{variant:"destructive",onClick:c,disabled:r,children:r?"Rejecting...":"Reject"})]})]})})}function eS({memberId:t}){const{data:s,isLoading:a}=jv(t);if(a||!s||s.total_attempts===0)return null;const n=()=>{let l=null,m="";return s.resolved?(l="bg-emerald-500",m="Resolved"):s.total_attempts>=s.max_attempts?(l="bg-red-500",m="Exhausted"):s.in_dunning&&(l="bg-amber-500",m="Active"),l?e.jsxs("span",{className:"inline-flex items-center gap-1.5 whitespace-nowrap",children:[e.jsx("span",{className:`h-1.5 w-1.5 shrink-0 rounded-full ${l}`}),e.jsx("span",{className:"text-xs font-medium",children:m})]}):null},r=l=>l==="retry_succeeded"?e.jsx(Kt,{className:"h-4 w-4 text-green-600"}):l==="retry_failed"?e.jsx(Ca,{className:"h-4 w-4 text-red-600"}):e.jsx(ea,{className:"h-4 w-4 text-muted-foreground"}),i=l=>Ps(l).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"});return e.jsxs(L,{className:"border-amber-300 dark:border-amber-700",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(ie,{className:"flex items-center gap-2.5",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(fi,{className:"h-4 w-4"})}),"Payment retry status"]}),n()]})}),e.jsxs($,{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-3 gap-4 text-sm",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"Retry Attempts"}),e.jsxs("p",{className:"font-medium",children:[s.total_attempts," / ",s.max_attempts]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"Last Attempt"}),e.jsx("p",{className:"font-medium",children:s.last_attempt_date?i(s.last_attempt_date):"â"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"Next Retry"}),e.jsx("p",{className:"font-medium",children:s.next_retry_date?i(s.next_retry_date):"â"})]})]}),s.attempts.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium",children:"Attempt History"}),e.jsx("div",{className:"space-y-1",children:s.attempts.map(l=>e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-muted/50 px-2 py-1.5 text-sm",children:[r(l.result),e.jsxs("span",{className:"font-medium",children:["#",l.attempt_number]}),e.jsx("span",{className:"text-muted-foreground",children:i(l.attempted_at)}),l.error_message&&e.jsx("span",{className:"ml-auto max-w-[200px] truncate text-muted-foreground",title:l.error_message,children:l.error_message})]},l.attempt_number))})]})]})]})}function tS({memberId:t}){const[s,a]=o.useState(1),[n,r]=o.useState(""),{data:i,isLoading:l}=wv(t,s),m=Nv(),c=kv(),{user:d}=V(),u=async p=>{p.preventDefault(),n.trim()&&(await m.mutateAsync({memberId:t,content:n.trim()}),r(""),a(1))},h=async p=>{await c.mutateAsync({memberId:t,noteId:p})};return e.jsxs("div",{className:"space-y-4",children:[e.jsx(L,{children:e.jsx($,{className:"pt-4",children:e.jsxs("form",{onSubmit:u,className:"space-y-3",children:[e.jsx(It,{placeholder:"Add a noteâ¦",value:n,onChange:p=>r(p.target.value),rows:3,maxLength:2e3}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-xs text-muted-foreground",children:[n.length,"/2000"]}),e.jsxs(g,{type:"submit",size:"sm",disabled:!n.trim()||m.isPending,children:[e.jsx(fl,{className:"mr-1.5 h-4 w-4"}),m.isPending?"Adding...":"Add Note"]})]})]})})}),l?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(p=>e.jsx(Y,{className:"h-24"},p))}):i&&i.items.length>0?e.jsxs("div",{className:"space-y-3",children:[i.items.map(p=>e.jsx(L,{children:e.jsx($,{className:"pt-4",children:e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx("span",{className:"font-medium",children:p.user_name||p.user_email||"Unknown"}),e.jsx("span",{className:"text-muted-foreground",children:Be(Ct(p.created_at),"MMM d, yyyy h:mm a")})]}),e.jsx("p",{className:"mt-2 whitespace-pre-wrap text-sm",children:p.content})]}),(p.user_id===d?.id||d?.role==="super_admin")&&e.jsx(g,{variant:"ghost",size:"icon",className:"h-8 w-8 shrink-0 text-muted-foreground hover:text-destructive",onClick:()=>h(p.id),disabled:c.isPending,children:e.jsx(Ft,{className:"h-4 w-4"})})]})})},p.id)),i.pages>1&&e.jsxs("div",{className:"flex items-center justify-center gap-2 pt-2",children:[e.jsx(g,{variant:"outline",size:"sm",disabled:s<=1,onClick:()=>a(p=>p-1),children:"Previous"}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:["Page ",s," of ",i.pages]}),e.jsx(g,{variant:"outline",size:"sm",disabled:s>=i.pages,onClick:()=>a(p=>p+1),children:"Next"})]})]}):e.jsx("p",{className:"py-8 text-center text-sm text-muted-foreground",children:"No notes yet. Add one above."})]})}const sS=[{value:"active",label:"Active"},{value:"pending",label:"Pending"},{value:"grace",label:"Grace"},{value:"lapsed",label:"Lapsed"},{value:"suspended",label:"Suspended"},{value:"cancelled",label:"Cancelled"}];function aS({open:t,onOpenChange:s,selectedIds:a,onSuccess:n}){const[r,i]=o.useState(""),[l,m]=o.useState(""),c=Tx(),[d,u]=o.useState(null),h=async()=>
1{if(r)try{const x=await c.mutateAsync({member_ids:a,action:"change_status",params:{new_status:r,reason:l||"Bulk status change"}});u(x),x.failure_count===0&&(n(),p())}catch{}},p=()=>{i(""),m(""),u(null),s(!1)};return e.jsx(Fe,{open:t,onOpenChange:p,children:e.jsxs(Te,{children:[e.jsxs(Ae,{children:[e.jsx(Ee,{children:"Change Status"}),e.jsxs(tt,{children:["Change the status of ",a.length," selected member",a.length!==1?"s":"","."]})]}),d&&d.failure_count>0&&e.jsxs("div",{className:"rounded-md bg-amber-50 p-3 text-sm text-amber-800 dark:bg-amber-950/20 dark:text-amber-200",children:[d.success_count," succeeded, ",d.failure_count," failed."]}),e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{children:"New status"}),e.jsxs(qe,{value:r,onValueChange:i,children:[e.jsx(Le,{children:e.jsx(Ie,{placeholder:"Select status"})}),e.jsx($e,{children:sS.map(x=>e.jsx(q,{value:x.value,children:x.label},x.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{children:"Reason"}),e.jsx(It,{placeholder:"Reason for status change",value:l,onChange:x=>m(x.target.value),rows:3})]})]}),e.jsxs(Ge,{children:[e.jsx(g,{variant:"outline",onClick:p,children:"Cancel"}),e.jsx(g,{onClick:h,disabled:!r||c.isPending,children:c.isPending?"Applying...":"Apply"})]})]})})}function nS({open:t,onOpenChange:s,selectedIds:a,onSuccess:n}){const[r,i]=o.useState(""),l=Tx(),{data:m}=oa(),[c,d]=o.useState(null),u=async()=>{if(r)try{const p=await l.mutateAsync({member_ids:a,action:"change_membership_type",params:{type_id:r}});d(p),p.failure_count===0&&(n(),h())}catch{}},h=()=>{i(""),d(null),s(!1)};return e.jsx(Fe,{open:t,onOpenChange:h,children:e.jsxs(Te,{children:[e.jsxs(Ae,{children:[e.jsx(Ee,{children:"Change Membership Type"}),e.jsxs(tt,{children:["Change the membership type of ",a.length," selected member",a.length!==1?"s":"","."]})]}),c&&c.failure_count>0&&e.jsxs("div",{className:"rounded-md bg-amber-50 p-3 text-sm text-amber-800 dark:bg-amber-950/20 dark:text-amber-200",children:[c.success_count," succeeded, ",c.failure_count," failed."]}),e.jsx("div",{className:"space-y-4 py-2",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{children:"Membership type"}),e.jsxs(qe,{value:r,onValueChange:i,children:[e.jsx(Le,{children:e.jsx(Ie,{placeholder:"Select membership type"})}),e.jsx($e,{children:(m||[]).map(p=>e.jsx(q,{value:p.id,children:p.name},p.id))})]})]})}),e.jsxs(Ge,{children:[e.jsx(g,{variant:"outline",onClick:h,children:"Cancel"}),e.jsx(g,{onClick:u,disabled:!r||l.isPending,children:l.isPending?"Applying...":"Apply"})]})]})})}function rS({open:t,onOpenChange:s,selectedIds:a,onSuccess:n}){const r=_v(),[i,l]=o.useState(null),m=async()=>{try{const d=await r.mutateAsync(a);l(d),d.failure_count===0&&setTimeout(()=>{n(),c()},1500)}catch{}},c=()=>{l(null),s(!1)};return e.jsx(Fe,{open:t,onOpenChange:c,children:e.jsxs(Te,{children:[e.jsxs(Ae,{children:[e.jsxs(Ee,{className:"flex items-center gap-2",children:[e.jsx($t,{className:"h-5 w-5"}),"Send Portal Access Emails"]}
1),e.jsxs(tt,{children:["Send a portal access email with a secure login link to ",a.length," selected member",a.length!==1?"s":"","."]})]}),!i&&e.jsxs("div",{className:"space-y-3 py-2",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Each member will receive an email with a one-click login link that expires in 24 hours. After signing in, members without a password will be prompted to create one."}),e.jsxs("div",{className:"flex items-start gap-2 rounded-md bg-amber-50 p-3 text-sm text-amber-800 dark:bg-amber-950/30 dark:text-amber-200",children:[e.jsx(Bt,{className:"mt-0.5 h-4 w-4 shrink-0"}),e.jsx("span",{children:"This will send real emails. Make sure the selected members are correct."})]})]}),i&&i.failure_count===0&&e.jsxs("div",{className:"flex items-center gap-3 rounded-md bg-emerald-50 p-4 text-emerald-800 dark:bg-emerald-950/30 dark:text-emerald-200",children:[e.jsx(Kt,{className:"h-5 w-5 shrink-0"}),e.jsxs("span",{className:"text-sm font-medium",children:["Successfully sent ",i.success_count," email",i.success_count!==1?"s":"","."]})]}),i&&i.failure_count>0&&e.jsxs("div",{className:"rounded-md bg-amber-50 p-3 text-sm text-amber-800 dark:bg-amber-950/30 dark:text-amber-200",children:[i.success_count," sent successfully, ",i.failure_count," failed."]}),e.jsxs(Ge,{children:[e.jsx(g,{variant:"outline",onClick:c,children:i?"Close":"Cancel"}),!i&&e.jsx(g,{onClick:m,disabled:r.isPending,children:r.isPending?"Sending...":`Send ${a.length} Email${a.length!==1?"s":""}`})]})]})})}function iS({open:t,onOpenChange:s,selectedIds:a,onSuccess:n}){const r=Sv(),[i,l]=o.useState(null),m=async()=>{try{const d=await r.mutateAsync(a);l(d),d.failure_count===0&&setTimeout(()=>{n(),c()},1500)}catch{}},c=()=>{l(null),s(!1)};return e.jsx(Fe,{open:t,onOpenChange:c,children:e.jsxs(Te,{children:[e.jsxs(Ae,{children:[e.jsxs(Ee,{className:"flex items-center gap-2",children:[e.jsx(ed,{className:"h-5 w-5"}),"Send Faculty Hub Invitation"]}),e.jsxs(tt,{children:["Send the Faculty Hub invitation with a secure login link to ",a.length," ","selected member",a.length!==1?"s":"","."]})]}),!i&&e.jsxs("div",{className:"space-y-3 py-2",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Each member will receive an email with a one-click login link that expires in 24 hours. After signing in, members without a password will be prompted to create one."}),e.jsxs("div",{className:"flex items-start gap-2 rounded-md bg-amber-50 p-3 text-sm text-amber-800 dark:bg-amber-950/30 dark:text-amber-200",children:[e.jsx(Bt,{className:"mt-0.5 h-4 w-4 shrink-0"}),e.jsx("span",{children:"This will send real emails. Make sure the selected members are correct."})]})]}),i&&i.failure_count===0&&e.jsxs("div",{className:"flex items-center gap-3 rounded-md bg-emerald-50 p-4 text-emerald-800 dark:bg-emerald-950/30 dark:text-emerald-200",children:[e.jsx(Kt,{className:"h-5 w-5 shrink-0"}),e.jsxs("span",{className:"text-sm font-medium",children:["Successfully sent ",i.success_count," email",i.success_count!==1?"s":"","."]})]}),i&&i.failure_count>0&&e.jsxs("div",{className:"rounded-md bg-amber-50 p-3 text-sm text-amber-800 dark:bg-amber-950/30 dark:text-amber-200",children:[i.success_count," sent successfully, ",i.failure_count," failed."]}),e.jsxs(Ge,{children:[e.jsx(g,{variant:"outline",onClick:c,children:i?"Close":"Cancel"}),!i&&e.jsx(g,{onClick:m,disabled:r.isPending,children:r.isPending?"Sending...":`Send ${a.length} Email${a.length!==1?"s":""}`})]})]})})}function lS(){const t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*";let s="";for(let a=0;a<12;a++)s+=t.charAt(Math.floor(Math.random()*t.length));return s}function oS({member:t,open:s,onOpenChange:a,onConfirm:n,isResetting:r}){const[i,l]=o.useState(""),[m,c]=o.useState(""),[d,u]=o.useState(!1),[h,p]=o.useState(""),[x,f]=o.useState(!1),b=()=>{const v=lS();l(v),c(v),u(!0),p("")},N=async()=>{await navigator.clipboard.writeText(i),f(!0),setTimeout(()=>f(!1),2e3)},j=async()=>{if(p(""),i.length<8){p("Password must be at least 8 characters");return}if(i!==m){p("Passwords do not match");return}await n(i),l(""),c(""),u(!1)},w=v=>{v||(l(""),c(""),u(!1),p("")),a(v)};return e.jsx(Fe,{open:s,onOpenChange:w,children:e.jsxs(Te,{className:"sm:max-w-md",children:[e.jsxs(Ae,{children:[e.jsx(Ee,{children:"Reset Password"}),e.jsxs(tt,{children:["Set a new password for"," ",e.jsxs("strong",{children:[t?.first_name," ",t?.last_name]}),". Make sure to share it with them securely."]})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[h&&e.jsx("div",{className:"rounded-md bg-destructive/10 p-3 text-sm text-destructive",children:h}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"new-password",children:"New password"}),e.jsxs("div",{className:"relative",children:[e.jsx(O,{id:"new-password",type:d?"text":"password",value:i,onChange:v=>l(v.target.value),placeholder:"Enter new password",className:"pr-20"}),e.jsxs("div",{className:"absolute right-2 top-1/2 flex -translate-y-1/2 items-center gap-1",children:[i&&e.jsx(g,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:N,children:x?e.jsx(Xt,{className:"h-4 w-4 text-green-600"}):e.jsx(za,{className:"h-4 w-4"})}),e.jsx(g,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>u(!d),children:d?e.jsx(Er,{className:"h-4 w-4"}):e.jsx(ca,{className:"h-4 w-4"})})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"confirm-password",children:"Confirm password"}),e.jsx(O,{id:"confirm-password",type:d?"text":"password",value:m,onChange:v=>c(v.target.value),placeholder:"Confirm new password"})]}),e.jsx(g,{type:"button",variant:"outline",size:"sm",onClick:b,className:"w-full",children:"Generate Random Password"})]}),e.jsxs(Ge,{children:[e.jsx(g,{variant:"outline",onClick:()=>w(!1),disabled:r,children:"Cancel"}),e.jsx(g,{onClick:j,disabled:r||!i,children:r?"Resetting...":"Reset Password"})]})]})})}const cS={email:"email",secondaryEmail:"secondary_email",organization:"organization",phone:"phone",city:"city",state:"state",county:"county",membershipType:"membership_type",status:"status",joinDate:"join_date",expires:"membership_end_date",autoRenew:"auto_renew",addressLine1:"address_line1",addressLine2:"address_line2",postalCode:"postal_code",country:"country",membershipStart:"membership_start_date",showInDirectory:"show_in_directory",tags:"tags"};function dS({open:t,onOpenChange:s,allColumnDefs:a,visibleColumns:n,totalCount:r,filters:i}){const{selectedSocietyId:l}
1=V(),m=J(),[c,d]=o.useState("csv"),[u,h]=o.useState(new Set),[p,x]=o.useState(!0),[f,b]=o.useState(!1),[N,j]=o.useState(""),[w,v]=o.useState(!1),[k,S]=o.useState(""),{data:_=[]}=re({queryKey:["export-templates",l],queryFn:()=>$a.listTemplates(l),enabled:!!l&&t}),y=W({mutationFn:z=>$a.createTemplate(z,l),onSuccess:z=>{m.invalidateQueries({queryKey:["export-templates",l]}),v(!1),S(""),j(z.id)}}),C=W({mutationFn:z=>$a.deleteTemplate(z,l),onSuccess:()=>{m.invalidateQueries({queryKey:["export-templates",l]}),j("")}});o.useEffect(()=>{t&&(h(new Set(n)),x(!0),j(""),v(!1),S(""))},[t,n]);const P=z=>{if(j(z),z==="none"){j("");return}const ae=_.find(ue=>ue.id===z);ae&&(d(ae.config.format),h(new Set(ae.config.selected_columns)),x(ae.config.include_custom_fields))},A=()=>{k.trim()&&y.mutate({name:k.trim(),config:{format:c,selected_columns:Array.from(u),include_custom_fields:p}})},E=co,Q=a.filter(z=>z.key.startsWith("custom_")),U=Q.length>0,D=z=>{h(ae=>{const ue=new Set(ae);return ue.has(z)?ue.delete(z):ue.add(z),ue})},K=!!(i.search||i.filterValue||i.filterTag||i.status||i.membershipTypeId||i.expiringWithinDays!=null),xe=async()=>{if(l){b(!0);try{const z=["first_name","last_name"];for(const ue of u){const _e=cS[ue];_e&&!z.includes(_e)&&z.push(_e)}const ae=p&&U;await $a.exportMembers({format:c,status:i.status?[i.status]:void 0,membership_type_id:i.membershipTypeId,expiring_within_days:i.expiringWithinDays,include_custom_fields:ae,fields:z,query:i.search,filter_field:i.filterField,filter_value:i.filterValue,filter_tag:i.filterTag,sort_by:i.sortBy,sort_dir:i.sortDir},l),s(!1)}catch(z){console.error("Export failed:",z)}finally{b(!1)}}};return e.jsx(Fe,{open:t,onOpenChange:s,children:e.jsxs(Te,{className:"sm:max-w-[480px]",children:[e.jsxs(Ae,{children:[e.jsx(Ee,{children:"Export Members"}),e.jsx(tt,{children:K?`Exporting ${r} member${r!==1?"s":""} matching current filters`:`Exporting all ${r} member${r!==1?"s":""}`})]}),e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{className:"text-sm font-medium",children:"Template"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(qe,{value:N||"none",onValueChange:P,children:[e.jsx(Le,{className:"flex-1",children:e.jsx(Ie,{placeholder:"No template"})}),e.jsxs($e,{children:[e.jsx(q,{value:"none",children:"No template"}),_.map(z=>e.jsx(q,{value:z.id,children:z.name},z.id))]})]}),N&&e.jsx(g,{type:"button",variant:"ghost",size:"icon",onClick:()=>C.mutate(N),disabled:C.isPending,title:"Delete template",children:e.jsx(Ft,{className:"h-4 w-4 text-destructive"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{className:"text-sm font-medium",children:"Format"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(g,{type:"button",size:"sm",variant:c==="csv"?"default":"outline",onClick:()=>d("csv"),children:"CSV"}),e.jsx(g,{type:"button",size:"sm",variant:c==="xlsx"?"default":"outline",onClick:()=>d("xlsx"),children:"Excel (XLSX)"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(T,{className:"text-sm font-medium",children:"Columns"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("button",{type:"button",className:"text-xs text-muted-foreground hover:text-foreground",onClick:()=>h(new Set(E.map(z=>z.key))),children:"Select all"}),e.jsx("button",{type:"button",className:"text-xs text-muted-foreground hover:text-foreground",onClick:()=>h(new Set),children:"Clear"})]})]}),e.jsxs("div",{className:"max-h-[200px] space-y-1 overflow-y-auto rounded-md border p-2",children:[e.jsxs("label",{className:"flex cursor-default items-center gap-2 text-sm text-muted-foreground",children:[e.jsx("input",{type:"checkbox",checked:!0,disabled:!0,className:"h-3.5 w-3.5 rounded border-gray-300"}),"Name (always included)"]}),E.map(z=>e.jsxs("label",{className:"flex cursor-pointer items-center gap-2 rounded px-1 text-sm hover:bg-accent",children:[e.jsx("input",{type:"checkbox",checked:u.has(z.key),onChange:()=>D(z.key),className:"h-3.5 w-3.5 rounded border-gray-300"}),z.label]},z.key))]})]}),U&&e.jsxs("label",{className:"flex cursor-pointer items-center gap-2 text-sm",children:[e.jsx("input",{type:"checkbox",checked:p,onChange:()=>x(!p),className:"h-3.5 w-3.5 rounded border-gray-300"}),"Include custom fields (",Q.length,")"]})]}),e.jsxs(Ge,{className:"flex-col gap-2 sm:flex-row",children:[e.jsx("div",{className:"flex-1",children:w?e.jsxs("div",{className:"flex gap-2",children:[e.jsx(O,{placeholder:"Template name",value:k,onChange:z=>S(z.target.value),onKeyDown:z=>z.key==="Enter"&&A(),className:"h-9",autoFocus:!0}),e.jsx(g,{type:"button",size:"sm",onClick:A,disabled:!k.trim()||y.isPending,children:y.isPending?e.jsx(He,{className:"h-4 w-4 animate-spin"}):"Save"}),e.jsx(g,{type:"button",size:"sm",variant:"ghost",onClick:()=>{v(!1),S("")},children:"Cancel"})]}):e.jsxs(g,{type:"button",variant:"outline",size:"sm",onClick:()=>v(!0),children:[e.jsx(Np,{className:"mr-1.5 h-3.5 w-3.5"}),"Save as Template"]})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(g,{variant:"outline",onClick:()=>s(!1),children:"Cancel"}),e.jsx(g,{onClick:xe,disabled:f,children:f?e.jsxs(e.Fragment,{children:[e.jsx(He,{className:"mr-2 h-4 w-4 animate-spin"}),"Exporting..."]}):e.jsxs(e.Fragment,{children:[e.jsx(vs,{className:"mr-2 h-4 w-4"}),"Export ",c.toUpperCase()]})})]})]})]})})}function mS({open:t,onOpenChange:s,selectedIds:a,onSuccess:n}
1){const[r,i]=o.useState("add"),[l,m]=o.useState([]),[c,d]=o.useState(""),[u,h]=o.useState(!1),{data:p}=Ai(),x=u_(),f=(p||[]).filter(k=>!l.includes(k.tag)).filter(k=>!c||k.tag.includes(c.toLowerCase())),b=k=>{const S=k.trim().toLowerCase();!S||l.includes(S)||(m([...l,S]),d(""),h(!1))},N=k=>{m(l.filter(S=>S!==k))},j=k=>{k.key==="Enter"&&(k.preventDefault(),b(c)),k.key==="Escape"&&h(!1)},w=async()=>{l.length!==0&&(await x.mutateAsync({memberIds:a,tags:l,action:r}),m([]),d(""),s(!1),n())},v=k=>{k||(m([]),d(""),i("add")),s(k)};return e.jsx(Fe,{open:t,onOpenChange:v,children:e.jsxs(Te,{className:"sm:max-w-[420px]",children:[e.jsxs(Ae,{children:[e.jsx(Ee,{children:"Manage Tags"}),e.jsxs(tt,{children:[r==="add"?"Add":"Remove"," tags for ",a.length," selected member",a.length!==1?"s":""]})]}),e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(g,{type:"button",size:"sm",variant:r==="add"?"default":"outline",onClick:()=>i("add"),children:"Add Tags"}),e.jsx(g,{type:"button",size:"sm",variant:r==="remove"?"default":"outline",onClick:()=>i("remove"),children:"Remove Tags"})]}),e.jsxs("div",{className:"space-y-2",children:[l.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5",children:l.map(k=>e.jsxs(Ts,{variant:"secondary",className:"gap-1 pr-1",children:[k,e.jsx("button",{type:"button",onClick:()=>N(k),className:"ml-0.5 rounded-full p-0.5 hover:bg-black/10",children:e.jsx(ms,{className:"h-3 w-3"})})]},k))}),e.jsxs("div",{className:"relative",children:[e.jsx(O,{placeholder:"Type tag and press Enterâ¦",value:c,onChange:k=>{d(k.target.value),h(!0)},onFocus:()=>h(!0),onBlur:()=>setTimeout(()=>h(!1),150),onKeyDown:j,className:"text-sm"}),u&&f.length>0&&e.jsx("div",{className:"absolute z-10 mt-1 max-h-[160px] w-full overflow-y-auto rounded-md border bg-popover shadow-md",children:f.map(k=>e.jsxs("button",{type:"button",className:"flex w-full items-center justify-between px-3 py-1.5 text-sm hover:bg-accent",onMouseDown:S=>S.preventDefault(),onClick:()=>b(k.tag),children:[e.jsx("span",{children:k.tag}),e.jsx("span",{className:"text-xs text-muted-foreground",children:k.count})]},k.tag))})]})]})]}),e.jsxs(Ge,{children:[e.jsx(g,{variant:"outline",onClick:()=>v(!1),children:"Cancel"}),e.jsx(g,{onClick:w,disabled:l.length===0||x.isPending,children:x.isPending?e.jsxs(e.Fragment,{children:[e.jsx(He,{className:"mr-2 h-4 w-4 animate-spin"}),"Applying..."]}):`${r==="add"?"Add":"Remove"} ${l.length} tag${l.length!==1?"s":""}`})]})]})})}function uS(t,s){const a=new Set(t.map(n=>n.invoice_id));return[...t,...s.filter(n=>!a.has(n.invoice_id))]}function Fo({items:t,message:s,tone:a,footer:n}){return e.jsxs("div",{className:a==="warning"?"space-y-2 rounded-md bg-amber-50 p-3 text-sm text-amber-900 dark:bg-amber-950/30 dark:text-amber-200":"space-y-2 rounded-md bg-red-50 p-3 text-sm text-red-800 dark:bg-red-950/30 dark:text-red-200",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Bt,{className:"mt-0.5 h-4 w-4 shrink-0"}),e.jsx("span",{children:s})]}),e.jsx("ul",{className:"max-h-48 space-y-1 overflow-y-auto pl-6","aria-label":"Invoices not included",children:t.map(r=>e.jsxs("li",{children:[e.jsx("span",{className:"font-medium",children:r.member_name})," · ",r.invoice_number," ·"," ",r.reason_label]},r.invoice_id))}),n&&e.jsx("p",{className:"pl-6 text-xs",children:n})]})}function hS({open:t,onOpenChange:s,selectedIds:a,onSuccess:n}){const{selectedSocietyId:r}=V(),[i,l]=o.useState("loading"),[m,c]=o.useState(null),[d,u]=o.useState(null),[h,p]=o.useState([]),[x,f]=o.useState(0),b=o.useRef(null),[N,j]=o.useState(!1);o.useEffect(()=>()=>{b.current&&clearTimeout(b.current)},[]);const[w,v]=o.useState(!1),[k,S]=o.useState(!1);o.useEffect(()=>{t&&a.length>0&&(l("loading"),c(null),u(null),v(!1),S(!1),Bs.bulkPrintPreview(a,r||void 0).then(C=>{c(C),l("preview")}).catch(C=>{u(C?.response?.data?.detail||"Failed to load preview"),l("error")}))},[t,a,r]);const _=async(C=[])=>{l("downloading");try{const P=await Bs.bulkPrintDownload(a,r||void 0,C.map(Q=>Q.invoice_id)),A=window.URL.createObjectURL(P),E=document.createElement("a");E.href=A,E.download=`invoices_print_${new Date().toISOString().split("T")[0]}.pdf`,document.body.appendChild(E),E.click(),window.URL.revokeObjectURL(A),document.body.removeChild(E),l("done"),C.length===0&&(b.current=setTimeout(()=>{b.current=null,n(),y()},1500))}catch(P){let A="Failed to generate PDF",E=[],Q=0,U;try{const K=P?.response;if(U=K?.status,K?.data instanceof Blob){const xe=await K.data.text(),z=JSON.parse(xe);typeof z.detail=="string"&&(A=z.detail),Array.isArray(z.skipped)&&(E=z.skipped),typeof z.included_count=="number"&&(Q=z.included_count)}else{const xe=P?.response?.data?.detail;xe&&(A=xe)}}catch{}const D=U===void 0||U>
1=500;D&&(A="The download didnât complete. The server may still finish and mark these invoices as printed, so check the Invoices page before printing again."),j(D),u(A),p(uS(C,E)),f(Q),l(U===409&&E.length>0?"skipped":"error")}},y=()=>{if(i==="downloading")return;const C=b.current!==null;b.current&&(clearTimeout(b.current),b.current=null),(C||i==="done"&&h.length>0)&&n(),l("loading"),c(null),u(null),p([]),j(!1),s(!1)};return e.jsx(Fe,{open:t,onOpenChange:y,children:e.jsxs(Te,{className:"max-w-lg",children:[e.jsxs(Ae,{children:[e.jsxs(Ee,{className:"flex items-center gap-2",children:[e.jsx(ni,{className:"h-5 w-5"}),"Print Invoices"]}),e.jsxs(tt,{children:["Download a combined PDF of unpaid invoices for ",a.length," selected member",a.length!==1?"s":"","."]})]}),i==="loading"&&e.jsxs("div",{className:"flex items-center justify-center py-8",children:[e.jsx(He,{className:"h-6 w-6 animate-spin text-muted-foreground"}),e.jsx("span",{className:"ml-2 text-sm text-muted-foreground",children:"Loading previewâ¦"})]}),i==="preview"&&m&&e.jsxs("div",{className:"space-y-3 py-2",children:[m.ready.length>0&&e.jsx("div",{className:"rounded-md bg-emerald-50 p-3 text-sm text-emerald-800 dark:bg-emerald-950/30 dark:text-emerald-200",children:e.jsxs("div",{className:"flex items-center gap-2 font-medium",children:[e.jsx(Kt,{className:"h-4 w-4 shrink-0"}),m.ready.length," member",m.ready.length!==1?"s":""," ready to print"]})}),m.missing_address.length>0&&e.jsxs("div",{className:"rounded-md bg-amber-50 p-3 text-sm text-amber-800 dark:bg-amber-950/30 dark:text-amber-200",children:[e.jsxs("button",{type:"button",className:"flex w-full items-center justify-between",onClick:()=>v(!w),children:[e.jsxs("div",{className:"flex items-center gap-2 font-medium",children:[e.jsx(Bt,{className:"h-4 w-4 shrink-0"}),m.missing_address.length," member",m.missing_address.length!==1?"s":""," missing mailing address"]}),w?e.jsx(Gn,{className:"h-4 w-4 shrink-0"}):e.jsx(ps,{className:"h-4 w-4 shrink-0"})]}),w&&e.jsx("ul",{className:"mt-2 space-y-1 pl-6",children:m.missing_address.map(C=>e.jsxs("li",{className:"text-xs",children:[C.member_name," (",C.invoice_number,")"]},C.member_id))})]}),m.no_invoice.length>0&&e.jsxs("div",{className:"rounded-md bg-muted p-3 text-sm text-muted-foreground",children:[e.jsxs("button",{type:"button",className:"flex w-full items-center justify-between",onClick:()=>S(!k),children:[e.jsxs("div",{className:"flex items-center gap-2 font-medium",children:[m.no_invoice.length," member",m.no_invoice.length!==1?"s":""," ","have no unpaid invoice"]}),k?e.jsx(Gn,{className:"h-4 w-4 shrink-0"}):e.jsx(ps,{className:"h-4 w-4 shrink-0"})]}),k&&e.jsx("ul",{className:"mt-2 space-y-1 pl-6",children:m.no_invoice.map(C=>e.jsx("li",{className:"text-xs",children:C.member_name},C.member_id))})]})]}),i==="downloading"&&e.jsxs("div",{className:"flex items-center justify-center py-8",children:[e.jsx(He,{className:"h-6 w-6 animate-spin text-muted-foreground"}),e.jsx("span",{className:"ml-2 text-sm text-muted-foreground",children:"Generating combined PDFâ¦"})]}),i==="done"&&e.jsxs("div",{className:"flex items-center gap-3 rounded-md bg-emerald-50 p-4 text-emerald-800 dark:bg-emerald-950/30 dark:text-emerald-200",children:[e.jsx(Kt,{className:"h-5 w-5 shrink-0"}),e.jsx("span",{className:"text-sm font-medium",children:"PDF downloaded successfully. Invoices marked as printed."})]}),i==="done"&&h.length>0&&e.jsx(Fo,{items:h,tone:"warning",message:"Not in the PDF or marked as printed. Print or email these separately:"}),i==="skipped"&&e.jsx(Fo,{items:h,tone:"warning",message:d??"",footer:"These members won't be in the PDF or marked as printed. Print or email them separately."}),i==="error"&&h.length>0&&e.jsx(Fo,{items:h,tone:"error",message:d??""}),i==="error"&&h.length===0&&e.jsxs("div",{className:"flex items-start gap-2 rounded-md bg-red-50 p-3 text-sm text-red-800 dark:bg-red-950/30 dark:text-red-200",children:[e.jsx(Bt,{className:"mt-0.5 h-4 w-4 shrink-0"}),e.jsx("span",{children:d})]}),e.jsxs(Ge,{children:[e.jsx(g,{variant:"outline",onClick:y,disabled:i==="downloading",children:i==="done"?"Close"
1:"Cancel"}),i==="preview"&&m&&e.jsxs(g,{onClick:()=>{_()},disabled:m.ready.length===0,children:[e.jsx(ni,{className:"mr-1.5 h-4 w-4"}),"Download PDF (",m.ready.length,")"]}),i==="skipped"&&e.jsxs(g,{onClick:()=>{_(h)},children:[e.jsx(ni,{className:"mr-1.5 h-4 w-4"}),"Download the other ",x]}),i==="error"&&!N&&e.jsx(g,{variant:"outline",onClick:()=>{l("loading"),u(null),p([]),Bs.bulkPrintPreview(a,r||void 0).then(C=>{c(C),l("preview")}).catch(C=>{u(C?.response?.data?.detail||"Failed to load preview"),l("error")})},children:"Retry"})]})]})})}const Jg={preview:async t=>(await F.post("/members/comp-dues/preview",{tag:t.tag,include_cancelled:t.includeCancelled},{params:t.societyId?{society_id:t.societyId}:{}})).data,execute:async t=>(await F.post("/members/comp-dues",{tag:t.tag,include_cancelled:t.includeCancelled,reason:t.reason,send_notification:t.sendNotification},{params:t.societyId?{society_id:t.societyId}:{}})).data};function pS(){const{selectedSocietyId:t}=V();return W({mutationFn:s=>Jg.preview({...s,societyId:t||void 0})})}function xS(){const{selectedSocietyId:t}=V(),s=J();return W({mutationFn:a=>Jg.execute({...a,societyId:t||void 0}),onSuccess:()=>{s.invalidateQueries({queryKey:["members"]}),s.invalidateQueries({queryKey:["member"]})}})}const gS=5,fS={comp:"Comp",reinstate_comp:"Reinstate + comp",skip:"Skip"},yS={already_covered:"already covered",status_ineligible:"status ineligible",free_membership_type:"free membership type"};function bS({open:t,onOpenChange:s,onSuccess:a}){const[n,r]=o.useState(""),[i,l]=o.useState(""),[m,c]=o.useState(!1),[d,u]=o.useState(!0),[h,p]=o.useState(null),[x,f]=o.useState(null),{data:b}=Ai(),N=pS(),j=xS(),w=h?h.comped_count+h.reinstated_count:0,v=i.trim().length>=gS,k=async()=>{if(!N.isPending&&n)try{const A=await N.mutateAsync({tag:n,includeCancelled:m});p(A)}catch{}},S=async()=>{if(!j.isPending&&!(!h||w===0||!v))try{const A=await j.mutateAsync({tag:n,includeCancelled:m,reason:i.trim(),sendNotification:d});f(A),a?.()}catch{}},_=()=>{r(""),l(""),c(!1),u(!0),p(null),f(null),s(!1)},y=A=>{if(A)s(A);else{if(j.isPending)return;_()}},C=!!x?.rows.some(A=>A.notice==="failed"),P=!!x?.rows.some(A=>A.notice==="no_template");return e.jsx(Fe,{open:t,onOpenChange:y,children:e.jsxs(Te,{className:"sm:max-w-[640px]",children:[e.jsxs(Ae,{children:[e.jsx(Ee,{children:"Comp dues"}),e.jsx(tt,{children:"Comp the upcoming dues cycle for every member carrying a tag, society-wide."})]}),x?e.jsxs("div",{className:"space-y-3 py-2",children:[e.jsxs("div",{className:"rounded-md bg-emerald-50 p-3 text-sm text-emerald-800 dark:bg-emerald-950/30 dark:text-emerald-200",children:["Comped ",x.comped_count+x.reinstated_count," member",x.comped_count+x.reinstated_count!==1?"s":"",x.reinstated_count>0?` (${x.reinstated_count} reinstated)`:""," for the ",x.cycle_start," â ",x.cycle_end," cycle. ",x.skipped_count," skipped."]}),C&&e.jsx("div",{className:"rounded-md bg-amber-50 p-3 text-sm text-amber-800 dark:bg-amber-950/30 dark:text-amber-200",children:"Some notice emails failed â check email logs."}),P&&e.jsx("p",{className:"text-sm text-muted-foreground",children:'No "Dues comp notice" email template is configured, so no notice emails were sent.'})]}):e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{children:"Tag"}),e.jsxs(qe,{value:n,onValueChange:A=>{r(A),p(null)},children:[e.jsx(Le,{children:e.jsx(Ie,{placeholder:"Select tag"})}),e.jsx($e,{children:(b||[]).map(A=>e.jsxs(q,{value:A.tag,children:[A.tag," (",A.count,")"]},A.tag))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{children:"Reason"}),e.jsx(O,{placeholder:"e.g. 2026 faculty free-dues policy",value:i,onChange:A=>l(A.target.value)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Recorded on each payment and in the audit log (min 5 characters)."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ot,{id:"comp-dues-include-cancelled",checked:m,onCheckedChange:A=>{c(A===!0),p(null)}}),e.jsx(T,{htmlFor:"comp-dues-include-cancelled",className:"font-normal",children:"Include cancelled members"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ot,{id:"comp-dues-send-notice",checked:d,onCheckedChange:A=>u(A===!0)}),e.jsx(T,{htmlFor:"comp-dues-send-notice",className:"font-normal",children:'Send comp notice email (uses the "Dues comp notice" template)'})]}),h&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"max-h-[280px] overflow-y-auto rounded-md border",children:e.jsxs(Pt,{children:[e.jsx(At,{children:e.jsxs(Ue,{children:[e.jsx(H,{children:"Member"}),e.jsx(H,{children:"Type"}),e.jsx(H,{children:"Status"}),e.jsx(H,{children:"Action"}),e.jsx(H,{children:"New end date"})]})}),e.jsx(Et,{children:h.rows.map(A=>e.jsxs(Ue,{children:[e.jsxs(G,{children:[A.last_name,", ",A.first_name]}),e.jsx(G,{children:A.membership_type_name??"â"}),e.jsx(G,{children:A.status}),e.jsxs(G,{children:[fS[A.action]??A.action,A.skip_reason?` (${yS[A.skip_reason]??A.skip_reason})`:""]}),e.jsx(G,{children:A.new_end_date??"â"})]},A.member_id))})]})}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[h.comped_count+h.reinstated_count," will be comped (",h.reinstated_count," reinstated), ",h.skipped_count," skipped â cycle"," ",h.cycle_start," â ",h.cycle_end]})]})]}),e.jsx(Ge,{children:x?e.jsx(g,{onClick:_,children:"Done"}):e.jsxs(e.Fragment,{children:[e.jsx(g,{variant:"outline",onClick:_,children:"Cancel"}),h?e.jsx(g,{onClick:S,disabled:!v||w===0||j.isPending,children:j.isPending?e.jsxs(e.Fragment,{children:[e.jsx(He,{className:"mr-2 h-4 w-4 animate-spin"}),"Comping..."]}):`Comp ${w} member${w!==1?"s":""}`}):e.jsx(g,{onClick:k,disabled:!n||N.isPending,children:N.isPending?e.jsxs(e.Fragment,{children:[e.jsx(He,{className:"mr-2 h-4 w-4 animate-spin"}),"Previewing..."]}):"Preview"})]})})]})})}function ho({selectedMember:t,onSelectMember:s,onClearMember:a,label:n="Member",placeholder:r="Search by name or emailâ¦",inputId:i="member-search",touch:l=!1}
1){const[m,c]=o.useState(!1),[d,u]=o.useState(0),[h,p]=o.useState(""),[x,f]=o.useState([]),[b,N]=o.useState(!1),[j,w]=o.useState(!1),v=o.useRef(void 0),k=o.useRef(null),{selectedSocietyId:S}=V();o.useEffect(()=>{let y=!0;if(c(!1),!h||h.length<2){f([]),w(!1),N(!1);return}return clearTimeout(v.current),v.current=setTimeout(async()=>{N(!0);try{const C=await Gt.list({query:h,size:10,society_id:S||void 0});if(!y)return;f(C.items),w(!0)}catch{if(!y)return;c(!0),f([])}finally{y&&N(!1)}},300),()=>{y=!1,clearTimeout(v.current)}},[h,S,d]),o.useEffect(()=>{const y=C=>{k.current&&!k.current.contains(C.target)&&w(!1)};return document.addEventListener("mousedown",y),()=>document.removeEventListener("mousedown",y)},[]);const _=y=>{s(y),p(""),f([]),w(!1)};return e.jsxs("div",{className:"space-y-2",ref:k,children:[e.jsx(T,{htmlFor:i,children:n}),t?e.jsxs("div",{className:"flex items-center justify-between rounded-md border bg-muted px-3 py-2 text-sm",children:[e.jsxs("div",{children:[e.jsxs("span",{className:"font-medium",children:[t.first_name," ",t.last_name]}),e.jsx("span",{className:"ml-2 text-muted-foreground",children:t.email})]}),e.jsx(g,{type:"button",variant:"ghost",size:"sm",className:me(l&&"min-h-[44px]"),onClick:a,children:"Change"})]}):e.jsxs("div",{className:"relative",children:[e.jsx(O,{className:me(l&&"min-h-[44px]"),autoFocus:l,id:i,name:i,placeholder:r,value:h,onChange:y=>p(y.target.value),onFocus:()=>{x.length>0&&w(!0)},autoComplete:"off"}),m&&e.jsxs("div",{role:"alert",className:"space-y-2 py-2 text-sm",children:[e.jsx("p",{children:"Could not search people. Try again."}),e.jsx(g,{type:"button",variant:"outline",className:"min-h-[44px]",onClick:()=>u(y=>y+1),children:"Retry search"})]}),b&&e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"Searchingâ¦"}),j&&x.length>0&&e.jsx("div",{className:me("mt-1 max-h-72 overflow-y-auto rounded-md border bg-card shadow-sm",!l&&"fixed z-[100]"),style:l?void 0:{width:k.current?.getBoundingClientRect().width},children:x.map(y=>e.jsxs("button",{type:"button",className:me("w-full border-b px-3 py-2 text-left text-sm last:border-b-0 hover:bg-muted",l&&"min-h-[44px] break-words"),onClick:()=>_(y),children:[e.jsxs("span",{className:"font-medium",children:[y.first_name," ",y.last_name]}),e.jsx("span",{className:"ml-2 text-muted-foreground",children:y.email})]},y.id))}),j&&h.length>=2&&!b&&x.length===0&&e.jsx("div",{className:me("mt-1 rounded-md border bg-card px-3 py-2 shadow-sm",!l&&"fixed z-[100]"),style:l?void 0:{width:k.current?.getBoundingClientRect().width},children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"No members found"})})]})]})}const En={destinations:(t,s)=>F.get("/email-sync-rules/destinations",{params:{platform:t,...s?{society_id:s}:{}}}).then(a=>a.data.destinations),list:t=>F.get("/email-sync-rules/",{params:t?{society_id:t}:void 0}).then(s=>s.data),create:(t,s)=>F.post("/email-sync-rules/",t,{params:s?{society_id:s}:void 0}).then(a=>a.data),update:(t,s,a)=>F.patch(`/email-sync-rules/${t}`,s,{params:a?{society_id:a}:void 0}).then(n=>n.data),delete:(t,s)=>F.delete(`/email-sync-rules/${t}`,{params:s?{society_id:s}:void 0}),syncNow:(t,s)=>F.post(`/email-sync-rules/${t}/sync`,null,{params:s?{society_id:s}:void 0}).then(a=>a.data),preview:(t,s)=>F.post("/email-sync-rules/preview",{filters:t},{params:s?{society_id:s}:void 0}).then(a=>a.data),push:(t,s)=>F.post("/email-sync-rules/push",t,{params:s?{society_id:s}:void 0}).then(a=>a.data)};function jS(){const{selectedSocietyId:t}=V();return re({queryKey:["email-sync-rules",t],queryFn:()=>En.list(t??void 0)})}function Zg(t){const{selectedSocietyId:s}=V();return re({queryKey:["email-sync-rules-destinations",t,s],queryFn:()=>En.destinations(t,s??void 0),enabled:!!t})}function vS(){const t=J(),{selectedSocietyId:s}=V();return W({mutationFn:a=>
1En.create(a,s??void 0),onSuccess:()=>{t.invalidateQueries({queryKey:["email-sync-rules"]})}})}function wS(){const t=J(),{selectedSocietyId:s}=V();return W({mutationFn:({ruleId:a,data:n})=>En.update(a,n,s??void 0),onSuccess:()=>{t.invalidateQueries({queryKey:["email-sync-rules"]})}})}function NS(){const t=J(),{selectedSocietyId:s}=V();return W({mutationFn:a=>En.delete(a,s??void 0),onSuccess:()=>{t.invalidateQueries({queryKey:["email-sync-rules"]})}})}function kS(){const t=J(),{selectedSocietyId:s}=V();return W({mutationFn:a=>En.syncNow(a,s??void 0),onSuccess:()=>{t.invalidateQueries({queryKey:["email-sync-rules"]})}})}function _S(t,s){const{selectedSocietyId:a}=V();return re({queryKey:["email-sync-rules-preview",t,a],queryFn:()=>En.preview(t,a??void 0),enabled:s})}function SS(){const{selectedSocietyId:t}=V();return W({mutationFn:s=>En.push(s,t??void 0)})}function CS({open:t,onClose:s,filters:a,memberCount:n,mailchimpConnected:r,mailerliteConnected:i}){const l=r&&i,m=r?"mailchimp":i?"mailerlite":null,[c,d]=o.useState(m),[u,h]=o.useState(""),[p,x]=o.useState(!1),[f,b]=o.useState(""),[N,j]=o.useState(null),[w,v]=o.useState(null),{data:k,isLoading:S}=Zg(c),_=SS();o.useEffect(()=>{t&&(d(m),h(""),x(!1),b(""),j(null),v(null))},[t,m]),o.useEffect(()=>{h(""),x(!1),b("")},[c]);const y=async()=>{if(c){v(null);try{const E=await _.mutateAsync({platform:c,destination_id:p?void 0:u||void 0,destination_name:p?void 0:k?.find(Q=>Q.id===u)?.name,create_new_group:p||void 0,new_group_name:p?f:void 0,filters:a});j(E)}catch(E){const Q=E instanceof Error?E.message:E?.response?.data?.detail||"Push failed. Please try again.";v(Q)}}},C=c&&(p?f.trim().length>0:u.length>0)&&!_.isPending,P=c==="mailchimp"?"Mailchimp":"MailerLite",A=c==="mailchimp"?"group/tag":"group";return N?e.jsx(Fe,{open:t,onOpenChange:()=>s(),children:e.jsxs(Te,{className:"sm:max-w-[420px]",children:[e.jsxs(Ae,{children:[e.jsxs(Ee,{className:"flex items-center gap-2",children:[e.jsx(Kt,{className:"h-5 w-5 text-green-600"}),"Push Complete"]}),e.jsxs(tt,{children:["Successfully pushed ",N.members_pushed.toLocaleString()," member",N.members_pushed!==1?"s":""," to"," ",e.jsx("span",{className:"font-medium",children:N.destination_name})," on ",P,"."]})]}),e.jsx(Ge,{children:e.jsx(g,{onClick:s,children:"Done"})})]})}):e.jsx(Fe,{open:t,onOpenChange:()=>s(),children:e.jsxs(Te,{className:"sm:max-w-[420px]",children:[e.jsxs(Ae,{children:[e.jsx(Ee,{children:"Push to Email Platform"}),e.jsxs(tt,{children:["Push ",n.toLocaleString()," member",n!==1?"s":""," matching current filters to your email platform."]})]}),e.jsxs("div",{className:"space-y-4 py-2",children:[l?e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{className:"text-sm font-medium",children:"Platform"}),e.jsxs(qe,{value:c||"",onValueChange:E=>d(E),children:[e.jsx(Le,{children:e.jsx(Ie,{placeholder:"Select platform"})}),e.jsxs($e,{children:[e.jsx(q,{value:"mailchimp",children:"Mailchimp"}),e.jsx(q,{value:"mailerlite",children:"MailerLite"})]})]})]}):e.jsxs("div",{className:"text-sm text-muted-foreground",children:["Pushing to ",e.jsx("span",{className:"font-medium",children:P})]}),c&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(T,{className:"text-sm font-medium",children:["Destination ",A]}),p?e.jsxs("div",{className:"space-y-2",children:[e.jsx(O,{placeholder:`New ${A} name`,value:f,onChange:E=>b(E.target.value),autoFocus:!0}),e.jsx(g,{type:"button",variant:"ghost",size:"sm",onClick:()=>{x(!1),b("")},children:"Cancel"})]}):e.jsx("div",{className:"space-y-2",children:S?e.jsxs("div",{className:"flex items-center gap-2 py-2 text-sm text-muted-foreground",children:[e.jsx(He,{className:"h-4 w-4 animate-spin"}),"Loading ",A,"s..."]}):e.jsxs(e.Fragment,{children:[e.jsxs(qe,{value:u,onValueChange:h,children:[e.jsx(Le,{children:e.jsx(Ie,{placeholder:`Select ${A}`})}),e.jsx($e,{children:(k||[]).map(E=>e.jsx(q,{value:E.id,children:E.name},E.id))})]}),e.jsxs(g,{type:"button",variant:"outline",size:"sm",onClick:()=>x(!0),className:"w-full",children:[e.jsx(Rt,{className:"mr-1.5 h-3.5 w-3.5"}),"Create new ",A]})]})})]}),w&&e.jsx("div",{className:"rounded-md border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700 dark:border-red-800 dark:bg-red-950/20 dark:text-red-400",children:w})]}),e.jsxs(Ge,{children:[e.jsx(g,{variant:"outline",onClick:s,disabled:_.isPending,children:"Cancel"}),e.jsx(g,{onClick:y,disabled:!C,children:_.isPending?e.jsxs(e.Fragment,{children:[e.jsx(He,{className:"mr-2 h-4 w-4 animate-spin"}),"Pushing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(en,{className:"mr-2 h-4 w-4"}
1),"Push ",n.toLocaleString()," Member",n!==1?"s":""]})})]})]})})}const Xg="ams_member_columns",ef="ams_member_page_size",Fs=1e3,Vr=500;function PS(){try{const t=localStorage.getItem(ef);if(t){const s=Number(t);if([20,50,100].includes(s))return s}}catch{}return 20}function AS(){try{const t=localStorage.getItem(Xg);if(t){const s=JSON.parse(t);if(Array.isArray(s)&&s.every(a=>typeof a=="string"))return s}}catch{}return o_}function ES(){const[t,s]=ws(),[a,n]=o.useState(1),[r,i]=o.useState(""),[l,m]=o.useState(""),[c,d]=o.useState(""),[u,h]=o.useState(t.get("status")||"all"),[p,x]=o.useState(t.get("membership_type_id")||"all"),[f,b]=o.useState(()=>{const et=Number(t.get("expiring_within_days"));return Number.isInteger(et)&&et>=1&&et<=365?et:null}),[N,j]=o.useState(null),[w,v]=o.useState(null),[k,S]=o.useState(new Set),_=o.useMemo(()=>Array.from(k),[k]),[y,C]=o.useState(new Map),[P,A]=o.useState(!1),[E,Q]=o.useState(!1),[U,D]=o.useState(!1),[K,xe]=o.useState(!1),[z,ae]=o.useState(!1),[ue,_e]=o.useState(!1),[ee,se]=o.useState(!1),[le,oe]=o.useState(AS),[Pe,M]=o.useState(void 0),[I,R]=o.useState("asc"),[X,Se]=o.useState(!1),[ce,ke]=o.useState(!1),[ve,Ne]=o.useState(PS),{selectedSocietyId:Qe,user:Oe}=V(),Ce=Oe?.role==="super_admin"||Oe?.role==="society_admin",{data:ze}=tr(Qe||void 0),{data:Ze}=sr(Qe||void 0),Re=!!(ze?.mailchimp_connected||Ze?.mailerlite_connected);o.useEffect(()=>{S(new Set),C(new Map)},[Qe]),o.useEffect(()=>{(t.has("status")||t.has("membership_type_id")||t.has("expiring_within_days"))&&s({},{replace:!0})},[]),o.useEffect(()=>{localStorage.setItem(Xg,JSON.stringify(le))},[le]);const de=o.useMemo(()=>({page:a,size:ve,search:r||void 0,filterField:l&&l!=="tag"?l:void 0,filterValue:l&&l!=="tag"&&c||void 0,filterTag:l==="tag"&&c||void 0,status:u!=="all"?u:void 0,membershipTypeId:p!=="all"?p:void 0,expiringWithinDays:f??void 0,sortBy:Pe,sortDir:I}),[a,ve,r,l,c,u,p,f,Pe,I]),{data:ge,isLoading:mt}=fm(de);o.useEffect(()=>{ge?.items&&C(et=>{const bt=new Map(et);let qt=!1;for(const xs of ge.items)bt.get(xs.id)!==xs.tags&&(bt.set(xs.id,xs.tags??[]),qt=!0);return qt?bt:et})},[ge?.items]);const ye=Ax(),Ke=fv(),ut=yv(),{data:De}=er(),he=o.useMemo(()=>{const et=(De||[]).filter(bt=>bt.is_active).map(bt=>({key:`custom_${bt.field_key}`,label:bt.label,sortKey:"",render:qt=>i_(qt.custom_fields?.[bt.field_key]),className:"hidden sm:table-cell"}));return[...co,...et]},[De]),Xe=async()=>{if(!N)return;const et=N.id;await ye.mutateAsync(et),S(bt=>{if(!bt.has(et))return bt;const qt=new Set(bt);return qt.delete(et),qt}),j(null)},rt=async et=>{await Ke.mutateAsync(et.id)},yt=async et=>{w&&(await ut.mutateAsync({id:w.id,reason:et}),v(null))},dt=o.useCallback(et=>{Pe===et?R(bt=>bt==="asc"?"desc":"asc"):(M(et),R("asc")),n(1)},[Pe]),jt=r||c||u!=="all"||p!=="all"||f!==null,Ot=!mt&&(!ge?.items||ge.items.length===0),be=o.useCallback(et=>{S(bt=>{const qt=new Set(bt);return qt.has(et)?qt.delete(et):qt.add(et),qt})},[]),lt=o.useCallback(()=>{if(!ge?.items)return;const et=ge.items.map(bt=>bt.id);S(bt=>{const qt=et.every(ns=>bt.has(ns)),xs=new Set(bt);return qt?et.forEach(ns=>xs.delete(ns)):et.forEach(ns=>xs.add(ns)),xs})},[ge?.items]),ht=!!ge?.items?.length&&ge.items.every(et=>k.has(et.id)),zt=k.size>0&&!ht,Tt=k.size>0&&Array.from(k).every(et=>y.get(et)?.includes("faculty")),{data:Jt}=fm({page:1,size:1,status:"pending"}),is=Jt?.total??0,{data:Va}=oa(!1,!0),nt=Va?.find(et=>et.is_non_member),Vt=nt?.member_count??0;return e.jsx(nr,{tourIds:["add-members"],children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-baseline gap-3",children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:"Members"}),ge?.total!==void 0&&e.jsx("span",{className:"inline-flex items-center rounded-full bg-brand-navy/10 px-2.5 py-0.5 text-xs font-semibold text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:ge.total.toLocaleString()})]}),e.jsx("p",{className:"text-sm text-muted-foreground sm:text-base",children:"Manage your society's members"}),nt&&Vt>0&&e.jsxs("button",{type:"button",onClick:()=>{h("all"),i(""),m(""),d(""),x(nt.id),S(new Set),n(1)},className:"mt-1 text-xs text-muted-foreground underline-offset-2 hover:underline hover:text-foreground",children:["+ ",Vt," non-member account",Vt===1?"":"s"," (event-only)"]})]}),e.jsxs("div",{className:"flex w-full flex-wrap gap-2 sm:w-auto",children:[Re&&e.jsxs(g,{variant:"outline",className:"min-h-[44px]",onClick:()=>ke(!0),disabled:f!==null,title:f!==null?"Not available with the expiring filter â sync rules cannot represent a date window, so the push would include more members than shown.":void 0,children:[e.jsx(en,{className:"mr-2 h-4 w-4"}),"Push to email"]}),e.jsxs(g,{variant:"outline",className:"min-h-[44px]",onClick:()=>se(!0),children:[e.jsx(Lb,{className:"mr-2 h-4 w-4"}),"Comp dues"]}),e.jsxs(g,{variant:"outline",className:"min-h-[44px]",onClick:()=>Se(!0),children:[e.jsx(vs,{className:"mr-2 h-4 w-4"}),"Export"]}),Ce&&e.jsx(g,{asChild:!0,variant:"outline",className:"min-h-[44px]",children:e.jsxs(je,{to:"/members/duplicates",children:[e.jsx(za,{className:"mr-2 h-4 w-4"}),"Find duplicates"]})}),e.jsx(g,{asChild:!0,className:"flex-1 sm:flex-initial min-h-[44px]","data-tour":"members-add-btn",children:e.jsxs(je,{to:"/members/new",children:[e.jsx(Rt,{className:"mr-2 h-4 w-4"}),"Add member"]})})]})]}),is>0&&u!=="pending"&&e.jsxs("div",{className:"flex items-center justify-between rounded-lg border border-amber-200 bg-amber-50 px-4 py-3 dark:border-amber-700 dark:bg-amber-950/20",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Dt,{className:"h-4 w-4 text-amber-600 dar
1k:text-amber-400"}),e.jsxs("span",{className:"text-sm font-medium text-amber-800 dark:text-amber-200",children:[is," pending ",is===1?"application":"applications"," ","awaiting review"]})]}),e.jsx(g,{variant:"outline",size:"sm",className:"border-amber-300 text-amber-700 hover:bg-amber-100 dark:border-amber-600 dark:text-amber-400 dark:hover:bg-amber-950/30",onClick:()=>{h("pending"),n(1),S(new Set)},children:"Review"})]}),e.jsx(h_,{search:r,onSearchChange:et=>{i(et),n(1),S(new Set)},filterField:l,onFilterFieldChange:et=>{m(et),d(""),n(1),S(new Set)},filterValue:c,onFilterValueChange:et=>{d(et),n(1),S(new Set)},status:u,onStatusChange:et=>{h(et),et!=="all"&&et!=="active"&&b(null),n(1),S(new Set)},membershipTypeId:p,onMembershipTypeChange:et=>{x(et),n(1),S(new Set)},visibleColumns:le,onColumnsChange:oe,allColumnDefs:he}),f!==null&&e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full border border-amber-200 bg-amber-50 px-3 py-1 text-xs font-medium text-amber-800 dark:border-amber-700 dark:bg-amber-950/20 dark:text-amber-300",children:["Expiring within ",f," days (active members)",e.jsx("button",{type:"button","aria-label":`Clear expiring-within-${f}-days filter`,onClick:()=>{b(null),n(1),S(new Set)},className:"-mr-1 inline-flex h-6 w-6 items-center justify-center rounded-full hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-amber-500",children:e.jsx(ms,{className:"h-3 w-3"})})]})}),k.size>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between rounded-lg border bg-muted/50 px-4 py-3",children:[e.jsxs("span",{className:"text-sm font-medium",children:[k.size," member",k.size!==1?"s":""," selected"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(g,{size:"sm",variant:"outline",onClick:()=>A(!0),disabled:k.size>Fs,title:k.size>Fs?`Selection too large â limit is ${Fs}`:void 0,children:"Change Status"}),e.jsx(g,{size:"sm",variant:"outline",onClick:()=>Q(!0),disabled:k.size>Fs,title:k.size>Fs?`Selection too large â limit is ${Fs}`:void 0,children:"Change Type"}),e.jsxs(g,{size:"sm",variant:"outline",onClick:()=>ae(!0),disabled:k.size>Fs,title:k.size>Fs?`Selection too large â limit is ${Fs}`:void 0,children:[e.jsx(xa,{className:"mr-1.5 h-3.5 w-3.5"}),"Manage Tags"]}),e.jsxs(g,{size:"sm",variant:"outline",onClick:()=>D(!0),disabled:k.size>Fs,title:k.size>Fs?`Selection too large â limit is ${Fs}`:void 0,children:[e.jsx($t,{className:"mr-1.5 h-3.5 w-3.5"}),"Send Access Email"]}),Tt&&e.jsxs(g,{size:"sm",variant:"outline",onClick:()=>xe(!0),disabled:k.size>Fs,title:k.size>Fs?`Selection too large â limit is ${Fs}`:void 0,children:[e.jsx(ed,{className:"mr-1.5 h-3.5 w-3.5"}),"Send Faculty Welcome"]}),e.jsxs(g,{size:"sm",variant:"outline",onClick:()=>_e(!0),disabled:k.size>Vr,title:k.size>Vr?`Selection too large â print limit is ${Vr}`:void 0,children:[e.jsx(ni,{className:"mr-1.5 h-3.5 w-3.5"}),"Print Invoices"]}),e.jsx(g,{size:"sm",variant:"ghost",onClick:()=>S(new Set),children:e.jsx(ms,{className:"h-4 w-4"})})]})]}),(k.size>Fs||k.size>Vr)&&e.jsx("p",{className:"px-1 text-xs text-amber-700 dark:text-amber-400",children:k.size>Fs?`Selection exceeds the ${Fs}-member bulk-action limit. Deselect down or split into batches.`:`Print invoices is capped at ${Vr} per batch. Other bulk actions still work; deselect down or split to print.`})]}),ge&&ge.total>0&&e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("p",{className:"text-sm text-muted-foreground text-center sm:text-left",children:["Showing ",(a-1)*ve+1," to ",Math.min(a*ve,ge.total)," of"," ",ge.total," members"]}),e.jsxs("div",{className:"flex items-center justify-center gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm text-muted-foreground whitespace-nowrap",children:"Per page:"}),e.jsxs(qe,{value:String(ve),onValueChange:et=>{const bt=Number(et);Ne(bt),n(1),localStorage.setItem(ef,String(bt))},children:[e.jsx(Le,{className:"h-9 w-20",children:e.jsx(Ie,{})}),e.jsxs($e,{children:[e.jsx(q,{value:"20",children:"20"}),e.jsx(q,{value:"50",children:"50"}),e.jsx(q,{value:"100",children:"100"})]})]})]}),ge.pages>1&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(g,{variant:"outline",size:"sm",className:"min-h-[44px]",onClick:()=>n(a-1),disabled:a===1,children:[e.jsx(Gs,{className:"h-4 w-4"}),"Previous"]}),e.jsxs("span",{className:"text-sm whitespace-nowrap",children:["Page ",a," of ",ge.pages]}),e.jsxs(g,{variant:"outline",size:"sm",className:"min-h-[44px]",onClick:()=>n(a+1),disabled:a===ge.pages,children:["Next",e.jsx(ts,{className:"h-4 w-4"})]})]})]})]}),e.jsx(L,{children:e.jsx($,{className:"p-0",children:mt?e.jsx(U_,{}):Ot?e.jsx(z_,{title:jt?"No members match your filters":"No members yet",description:u==="archived"?"Members archived via the Delete action are removed from this list entirely â only members whose status was set to Archived (status override or import) appear here.":jt?"Try adjusting your search or filters":"Get started by adding your first member.",showAddButton:!jt}):e.jsx(c_,{members:ge?.items||[],onDelete:j,onApprove:rt,onReject:v,selectedIds:k,onSelectOne:be,onSelectAll:lt,allSelected:ht,someSelected:zt,visibleColumns:le,sortKey:Pe,sortDir:I,onSort:dt,allColumnDefs:he})})}),ge&&ge.pages>1&&e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("p",{className:"text-sm text-muted-foreground text-center sm:text-left",children:["Showing ",(a-1)*ve+1," to ",Math.min(a*ve,ge.total)," of"," ",ge.total," members"]}),e.jsxs("div",{className:"flex items-center justify-center gap-2",children:[e.jsxs(g,{variant:"outline",size:"sm",className:"min-h-[44px]",onClick:()=>n(a-1),disabled:a===1,children:[e.jsx(Gs,{className:"h-4 w-4"}),"Previous"]}),e.jsxs("span",{className:"text-sm whitespace-nowrap",children:["Page ",a," of ",ge.pages]}),e.jsxs(g,{variant:"outline",size:"sm",className:"min-h-[44px]",onClick:()=>n(a+1),disabled:a===ge.pages,children:["Next",e.jsx(ts,{className:"h-4 w-4"})]})]})]}),e.jsx(Hg,{member:N,open:!!N,onOpenChange:et=>!et&&j(null),onConfirm:Xe,isDeleting:ye.isPending}),e.jsx(X_,{member:w,open:!!w,onOpenChange:et=>!et&&v(null),onConfirm:yt,isRejecting:ut.isPending}),e.jsx(aS,{open:P,onOpenChange:A,selectedIds:Array.from(k),onSuccess:()=>S(new Set)}),e.jsx(nS,{open:E,onOpenChange:Q,selectedIds:Array.from(k),onSuccess:()=>S(new Set)}),e.jsx(rS,{open:U,onOpenChange:D,selectedIds:Array.from(k),onSuccess:()=>S(new Set)}),e.jsx(iS,{open:K,onOpenChange:xe,selectedIds:Array.from(k),onSuccess:()=>S(new Set)}),e.jsx(mS,{open:z,onOpenChange:ae,selectedIds:Array.from(k),onSuccess:()=>S(new Set)}),e.jsx(hS,{open:ue,onOpenChange:_e,selectedIds:_,onSuccess:()=>S(new Set)}),e.jsx(bS,{open:ee,onOpenChange:se}),e.jsx(dS,{open:X,onOpenChange:Se,allColumnDefs:he,visibleColumns:le,totalCount:ge?.total??0,filters:{search:r||void 0,filterField:l&&l!=="tag"?l:void 0,filterValue:l&&l!=="tag"&&c||void 0,filterTag:l==="tag"&&c||void 0,status:u!=="all"?u:void 0,membershipTypeId:p!=="all"?p:void 0,expiringWithinDays:f??void 0,sortBy:Pe,sortDir:I}}),Re&&f===null&&e.jsx(CS,{open:ce,onClose:()=>ke(!1),memberCount:ge?.total??0,mailchimpConnected:!!ze?.mailchimp_connected,mailerliteConnected:!!Ze?.mailerlite_connected,filters:{statuses:u!=="all"?[u]:void 0,membership_type_ids:p!=="all"?[p]:void 0,tags:l==="tag"&&c?[c]:void 0}})]})})}const Cn=o.forwardRef(({className:t,...s},a)=>e.jsx(hp,{className:me("grid gap-2",t),...s,ref:a}));Cn.displayName=hp.displayName;const la=o.forwardRef(({className:t,...s},a)=>
1e.jsx(pp,{ref:a,className:me("aspect-square h-4 w-4 rounded-full border border-primary text-primary ring-offset-background focus:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",t),...s,children:e.jsx(Nb,{className:"flex items-center justify-center",children:e.jsx(Bl,{className:"h-2.5 w-2.5 fill-current text-current"})})}));la.displayName=pp.displayName;const TS={exact_email:"Same email",exact_phone:"Same phone",similar_name:"Similar name"},$m={in_flight_paid_grant:"This member has an in-progress membership offer â try again after it completes.",in_flight_pending_offer_claim:"This member has an in-progress membership offer â try again after it completes.",member_missing_or_cross_tenant:"This member was changed by someone else â rescan and try again.",merged_member_has_stripe_subscription:"This member has active billing â resolve it before merging.",fk_rewrite_count_exceeded_cap:"Merge aborted by a safety check â contact support."};function FS(t){return t&&$m[t]?$m[t]:`Merge blocked: ${t??"unknown"} â rescan and try again.`}function zi(t){return[t.first_name,t.last_name].filter(Boolean).join(" ")||t.email}function RS({group:t,societyId:s,onResolved:a}){const n=t.members.find(x=>x.suggested_keep)??t.members[0],[r,i]=o.useState(n.id),[l,m]=o.useState(new Set),[c,d]=o.useState(!1),u=W({mutationFn:()=>Gt.mergeMembers(r,[...l],s),onSuccess:x=>{const f=x.results.filter(N=>N.status==="merged"),b=x.results.filter(N=>N.status==="blocked");f.length>0&&Ut.success(`Merged ${f.length} member${f.length===1?"":"s"}`),b.forEach(N=>Ut.error(FS(N.reason))),d(!1),a()},onError:()=>{Ut.error("Merge failed â rescan and try again."),d(!1)}}),h=W({mutationFn:()=>Gt.dismissDuplicates(t.members.map(x=>x.id),s),onSuccess:()=>{Ut.success("Marked as not duplicates"),a()},onError:()=>Ut.error("Could not save the dismissal â try again.")}),p=t.members.find(x=>x.id===r);return e.jsxs(L,{children:[e.jsxs(ne,{className:"flex flex-row flex-wrap items-center gap-2 space-y-0",children:[e.jsxs("span",{className:"text-sm font-semibold",children:[Math.round(t.score*100),"% match"]}),t.reasons.map(x=>e.jsx(Ts,{variant:"secondary",children:TS[x]??x},x))]}),e.jsx($,{children:e.jsx(Cn,{value:r,onValueChange:x=>{i(x),m(f=>{const b=new Set(f);return b.delete(x),b})},children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(Pt,{children:[e.jsx(At,{className:"bg-muted/30",children:e.jsx(Ue,{className:"hover:bg-transparent",children:["Keep","Merge","Name","Email","Phone","Status","Type","Joined","Payments","Registrations"].map(x=>e.jsx(H,{className:me("h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",(x==="Payments"||x==="Registrations")&&"text-right"),children:x},x))})}),e.jsx(Et,{children:t.members.map(x=>{const f=x.id===r;return e.jsxs(Ue,{className:"hover:bg-brand-navy/[0.04] dark:hover:bg-brand-navy/10",children:[e.jsx(G,{children:e.jsx(la,{value:x.id,"aria-label":`Keep ${zi(x)}`})}),e.jsx(G,{children:e.jsx(ot,{checked:l.has(x.id),disabled:f,"aria-label":`Merge ${zi(x)}`,onCheckedChange:b=>{m(N=>{const j=new Set(N);return b===!0?j.add(x.id):j.delete(x.id),j})}})}),e.jsx(G,{className:"font-medium",children:zi(x)}),e.jsx(G,{children:x.email}),e.jsx(G,{children:x.phone??"â"}),e.jsx(G,{children:e.jsx(Gg,{status:x.status})}),e.jsx(G,{children:x.membership_type_name??"â"}),e.jsx(G,{children:Ct(x.created_at).toLocaleDateString()}),e.jsx(G,{className:"text-right",children:x.payments_count}),e.jsx(G,{className:"text-right",children:x.registrations_count})]},x.id)})})]})})})}),e.jsxs(Sg,{className:"justify-end gap-2",children:[e.jsx(g,{variant:"ghost",disabled:h.isPending,onClick:()=>h.mutate(),children:"Not duplicates"}),e.jsx(g,{variant:"destructive",disabled:l.size===0,onClick:()=>d(!0),children:"Merge selected"})]}),e.jsx(Fe,{open:c,onOpenChange:d,children:e.jsxs(Te,{children:[e.jsxs(Ae,{children:[e.jsxs(Ee,{children:["Merge ",l.size," member",l.size===1?"":"s"," into"," ",p?zi(p):"the kept member","?"]}),e.jsx(tt,{children:"Their payments, invoices, registrations, committees and badges move onto the kept member. The merged records are archived and their portal logins stop working. This cannot be undone."})]}),e.jsxs(Ge,{children:[e.jsx(g,{variant:"outline",onClick:()=>d(!1),children:"Cancel"}),e.jsx(g,{variant:"destructive",disabled:u.isPending,onClick:()=>u.mutate(),children:u.isPending?"Mergingâ¦":"Merge members"})]})]})})]})}function MS(){const{selectedSocietyId:t}=V(),s=J(),a=t??void 0,n=re({queryKey:["member-duplicates",a],queryFn:()=>Gt.duplicateScan(a),staleTime:0}),r=()=>{s.invalidateQueries({queryKey:["members"]}),n.refetch()};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-brand-navy
1/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(za,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:"Duplicate members"}),n.data?e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Scanned ",n.data.scanned_members.toLocaleString()," members"]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Find and merge likely duplicate member records"})]})]}),e.jsxs(g,{variant:"outline",onClick:()=>{n.refetch()},disabled:n.isFetching,children:[e.jsx(St,{className:"mr-2 h-4 w-4"}),"Rescan"]})]}),n.data&&(n.data.skipped_blocks>0||n.data.skipped_groups>0||n.data.truncated)&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Some very large clusters were skipped to keep results reviewable â narrow them by cleaning up shared emails or phones first."}),n.isLoading&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(Y,{className:"h-40 w-full"}),e.jsx(Y,{className:"h-40 w-full"})]}),n.isError&&e.jsxs("div",{className:"rounded-lg border border-border p-8 text-center",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"The scan failed â check your connection and try again."}),e.jsx(g,{className:"mt-4",variant:"outline",onClick:()=>{n.refetch()},children:"Retry"})]}),n.data&&n.data.total_groups===0&&e.jsxs("div",{className:"rounded-lg border border-border p-10 text-center",children:[e.jsx(Lt,{className:"mx-auto h-8 w-8 text-muted-foreground"}),e.jsx("p",{className:"mt-3 font-medium",children:"No duplicates found"}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"Every member looks unique. Rescan any time â for example after an import."})]}),n.data?.groups.map(i=>e.jsx(RS,{group:i,societyId:a,onResolved:r},i.members.map(l=>l.id).join("-")))]})}const Ur=kb,ir=o.forwardRef(({className:t,...s},a)=>e.jsx(xp,{ref:a,className:me("inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground",t),...s}));ir.displayName=xp.displayName;const bs=o.forwardRef(({className:t,...s},a)=>e.jsx(gp,{ref:a,className:me("inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-sm",t),...s}));bs.displayName=gp.displayName;const js=o.forwardRef(({className:t,...s},a)=>e.jsx(fp,{ref:a,className:me("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",t),...s}));js.displayName=fp.displayName;const tf=t=>`ams_refund_key_${t}`;function DS(t){const s=tf(t);let a=sessionStorage.getItem(s);return a||(a=crypto.randomUUID().replace(/-/g,""),sessionStorage.setItem(s,a)),a}function LS(t){sessionStorage.removeItem(tf(t))}function sf({open:t,onOpenChange:s,payment:a,onSuccess:n}){const r=N0(),i=k0(),[l,m]=o.useState(""),[c,d]=o.useState(""),[u,h]=o.useState(""),[p,x]=o.useState(!1),f=()=>{const S=p||r.isPending||i.isPending;m(""),d(""),h(""),x(!1),r.reset(),i.reset(),a&&!S&&LS(a.id)};if(!a)return null;const b=Number(a.net_amount)-Number(a.refunded_amount),N=l?parseFloat(l):b,j=l!==""&&N<b,w=u==="REFUND"&&c.trim().length>0&&N>0&&N<=b,v=async S=>{if(S.preventDefault(),!w)return;const _=DS(a.id);if((await r.mutateAsync({payment_id:a.id,amount:j?N:void 0,reason:c.trim(),client_key:_}))?.status==="pending"){x(!0),n?.();return}f(),s(!1),n?.()},k=S=>S.toLocaleString("en-US",{style:"currency",currency:"USD"});return e.jsx(Fe,{open:t,onOpenChange:S=>{S||f(),s(S)},children:e.jsxs(Te,{className:"max-h-[90vh] w-[95vw] max-w-md overflow-y-auto",children:[e.jsxs(Ae,{children:[e.jsxs(Ee,{className:"flex items-center gap-2 text-destructive",children:[e.jsx(Bt,{className:"h-5 w-5"}),"Issue Refund"]}),e.jsx(tt,{children:"Refunds are irreversible. The funds will be returned to the customer's original payment method."})]}),e.jsxs("form",{onSubmit:v,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1 rounded-md border bg-muted/50 p-3 text-sm",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Member"}),e.jsx("span",{className:"font-medium",children:a.member_name||"â"})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Date"}),e.jsx("span",{children:Be(Ct(a.created_at),"MMM d, yyyy")})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Original amount"}),e.jsx("span",{className:"font-medium",children:k(Number(a.net_amount))})]}),Number(a.refunded_amount)>0&&e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Already refunded"}),e.jsx("span",{className:"font-medium text-amber-600",children:k(Number(a.refunded_amount))})]}),e.jsxs("div",{className:"mt-1 flex justify-between border-t pt-1",children:[e.jsx("span",{className:"text-muted-foreground",children:"Max refund
1able"}),e.jsx("span",{className:"font-semibold",children:k(b)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"refund-amount",children:"Refund amount ($)"}),e.jsx(O,{id:"refund-amount",type:"number",min:"0.01",max:b,step:"0.01",placeholder:b.toFixed(2),value:l,onChange:S=>m(S.target.value)}),j&&N>0&&e.jsxs("p",{className:"text-xs text-amber-600",children:["Partial refund â ",k(b-N)," will remain on this payment"]}),l!==""&&N>b&&e.jsxs("p",{className:"text-xs text-destructive",children:["Amount exceeds maximum refundable (",k(b),")"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"refund-reason",children:"Reason"}),e.jsx(It,{id:"refund-reason",placeholder:"Why is this refund being issued?",value:c,onChange:S=>d(S.target.value),maxLength:500,rows:3}),e.jsxs("p",{className:"text-right text-xs text-muted-foreground",children:[c.length,"/500"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(T,{htmlFor:"refund-confirm",children:["Type ",e.jsx("span",{className:"font-mono font-bold text-destructive",children:"REFUND"})," to confirm"]}),e.jsx(O,{id:"refund-confirm",placeholder:"REFUND",value:u,onChange:S=>h(S.target.value),className:"font-mono",autoComplete:"off"})]}),p&&e.jsxs("div",{className:"rounded-md border border-blue-200 bg-blue-50 p-3 dark:border-blue-900/50 dark:bg-blue-950/30",children:[e.jsx("p",{className:"text-sm font-medium text-blue-900 dark:text-blue-200",children:"Refund is processing"}),e.jsx("p",{className:"mt-1 text-xs text-blue-800 dark:text-blue-300",children:"Stripe accepted the refund but hasn't settled it yet. The payment will update and the member will be notified automatically once it completes. You can safely close this dialog."})]}),r.isError&&(()=>{const S=r.error,_=S?.response?.data?.detail,C=S?.response?.status===422&&typeof _=="string"&&_.toLowerCase().includes("promo code");return e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"whitespace-pre-line text-sm text-destructive",children:_??S?.message??"Failed to process refund. Please try again."}),C&&a.order_id&&e.jsxs("div",{className:"rounded-md border border-amber-200 bg-amber-50 p-3 dark:border-amber-900/50 dark:bg-amber-950/30",children:[e.jsx("p",{className:"text-sm font-medium text-amber-900 dark:text-amber-200",children:"Already issued the refund in Stripe?"}),e.jsx("p",{className:"mt-1 text-xs text-amber-800 dark:text-amber-300",children:"Click below to mark all payment rows on this order as REFUNDED in AMS. The system verifies with Stripe that the PaymentIntent is fully refunded before mutating any rows."}),i.isError&&e.jsx("p",{className:"mt-2 text-xs text-destructive",children:i.error?.response?.data?.detail||i.error?.message||"Failed to mark order refunded."}),e.jsx(g,{type:"button",variant:"outline",className:"mt-2 min-h-[36px] w-full sm:w-auto",disabled:i.isPending||c.trim().length===0,onClick:async()=>{await i.mutateAsync({orderId:a.order_id,reason:c.trim()}),f(),s(!1),n?.()},children:i.isPending?"Marking refundedâ¦":"Mark Order Refunded"}),c.trim().length===0&&e.jsx("p",{className:"mt-1 text-xs text-amber-800 dark:text-amber-300",children:"Enter a reason above first â it gets recorded in the audit log."})]})]})})(),e.jsxs(Ge,{className:"flex-col gap-2 sm:flex-row",children:[e.jsx(g,{type:"submit",variant:"destructive",className:"min-h-[44px] w-full sm:w-auto",disabled:!w||r.isPending||i.isPending,children:r.isPending?"Processing...":j?`Issue Partial Refund (${k(N)})`:`Issue Full Refund (${k(b)})`}),e.jsx(g,{type:"button",variant:"outline",className:"min-h-[44px] w-full sm:w-auto",onClick:()=>{f(),s(!1)},disabled:r.isPending||i.isPending,children:"Cancel"})]})]})]})})}const $S={succeeded:"bg-emerald-500",failed:"bg-red-500",pending:"bg-amber-500",refunded:"bg-muted-foreground/60",partially_refunded:"bg-muted-foreground/60"},qS={succeeded:"Succeeded",failed:"Failed",pending:"Pending",refunded:"Refunded",partially_refunded:"Partially refunded"},af={initial:"Initial",renewal:"Renewal",auto_renewal:"Auto-renewal",upgrade:"Upgrade",manual:"Manual"};function IS({member:t,onRecordPayment:s}){const[a,n]=o.useState(1),[r,i]=o.useState(null),[l,m]=o.useState(null),{data:c}=Ex(t.id),{data:d,isLoading:u}=j0(t.id,a),h=d?.items??[],p=d?.pages??0;return e.jsxs("div",{className:"space-y-6",children:[c&&e.jsxs("div",{className:"grid gap-4 sm:grid-cols-3",children:[e.jsxs(L,{children:[e.jsx(ne,{className:"pb-2",children:e.jsxs(ie,{className:"flex items-center gap-2.5",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy
1/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(Ua,{className:"h-4 w-4"})}),"Total paid"]})}),e.jsx($,{children:e.jsxs("div",{className:"text-2xl font-semibold tracking-tight",children:["$",c.total_paid.toFixed(2)]})})]}),e.jsxs(L,{children:[e.jsx(ne,{className:"pb-2",children:e.jsxs(ie,{className:"flex items-center gap-2.5",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(ii,{className:"h-4 w-4"})}),"Payments"]})}),e.jsx($,{children:e.jsx("div",{className:"text-2xl font-semibold tracking-tight",children:c.payment_count})})]}),e.jsxs(L,{children:[e.jsx(ne,{className:"pb-2",children:e.jsxs(ie,{className:"flex items-center gap-2.5",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(Yt,{className:"h-4 w-4"})}),"Last payment"]})}),e.jsxs($,{children:[e.jsx("div",{className:"text-2xl font-semibold tracking-tight",children:c.last_payment_amount!=null?`$${c.last_payment_amount.toFixed(2)}`:"â"}),c.last_payment_date&&e.jsx("p",{className:"text-xs text-muted-foreground",children:Be(Ps(c.last_payment_date),"MMM d, yyyy")})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"text-lg font-semibold",children:"Payment History"}),e.jsxs(g,{size:"sm",onClick:s,children:[e.jsx(Rt,{className:"mr-2 h-4 w-4"}),"Record Payment"]})]}),u?e.jsx("div",{className:"space-y-2",children:Array.from({length:5}).map((x,f)=>e.jsx(Y,{className:"h-12 w-full"},f))}):h.length===0?e.jsx("div",{className:"rounded-md border bg-gray-50 py-12 text-center",children:e.jsx("p",{className:"text-muted-foreground",children:"No payments recorded for this member."})}):e.jsxs(e.Fragment,{children:[e.jsxs(Pt,{children:[e.jsx(At,{children:e.jsxs(Ue,{children:[e.jsx(H,{children:"Date"}),e.jsx(H,{className:"text-right",children:"Amount"}),e.jsx(H,{children:"Type"}),e.jsx(H,{children:"Method"}),e.jsx(H,{children:"Status"}),e.jsx(H,{children:"Notes"}),e.jsx(H,{className:"text-right",children:"Actions"})]})}),e.jsx(Et,{children:h.map(x=>e.jsx(OS,{payment:x,onSendReceipt:()=>i(x),onRefund:()=>m(x)},x.id))})]}),p>1&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Page ",a," of ",p]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(g,{variant:"outline",size:"sm",disabled:a<=1,onClick:()=>n(x=>x-1),children:"Previous"}),e.jsx(g,{variant:"outline",size:"sm",disabled:a>=p,onClick:()=>n(x=>x+1),children:"Next"})]})]})]}),e.jsx(US,{payment:r,memberEmail:t.email,open:!!r,onOpenChange:x=>!x&&i(null)}),e.jsx(sf,{open:!!l,onOpenChange:x=>{x||m(null)},payment:l})]})}function OS({payment:t,onSendReceipt:s,onRefund:a}){const n=(t.status==="succeeded"||t.status==="partially_refunded")&&!!t.stripe_payment_intent_id&&Number(t.net_amount)-Number(t.refunded_amount)>0,r=t.status==="succeeded"||n;return e.jsxs(Ue,{children:[e.jsx(G,{className:"whitespace-nowrap",children:Be(Ct(t.created_at),"MMM d, yyyy")}),e.jsxs(G,{className:"text-right font-medium",children:[(t.is_comped?0:Number(t.net_amount)).toLocaleString("en-US",{style:"currency",currency:"USD"}),t.is_comped&&e.jsx("span",{className:"block text-xs text-muted-foreground",children:"comped â no cash collected"}),(t.is_comped?Number(t.amount)>
10:Number(t.net_amount)<Number(t.amount))&&e.jsxs("span",{className:"block text-xs text-muted-foreground",children:[e.jsx("span",{className:"line-through",children:Number(t.amount).toLocaleString("en-US",{style:"currency",currency:"USD"})})," ","booked"]}),Number(t.refunded_amount)>0&&e.jsxs("span",{className:"block text-xs text-amber-600",children:["-",Number(t.refunded_amount).toLocaleString("en-US",{style:"currency",currency:"USD"})," ","refunded"]})]}),e.jsx(G,{children:e.jsxs("span",{className:"inline-flex items-center gap-1.5 whitespace-nowrap",children:[e.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-muted-foreground/60"}),e.jsx("span",{className:"text-xs font-medium",children:af[t.payment_type]||t.payment_type})]})}),e.jsx(G,{className:"text-sm",children:{stripe_card:"Stripe",card:"Card (imported)",check:"Check",comp:"Comp"}[t.payment_method??""]||t.payment_method||"â"}),e.jsx(G,{children:e.jsxs("span",{className:"inline-flex items-center gap-1.5 whitespace-nowrap",children:[e.jsx("span",{className:`h-1.5 w-1.5 shrink-0 rounded-full ${$S[t.status]||"bg-muted-foreground/60"}`}),e.jsx("span",{className:"text-xs font-medium",children:qS[t.status]||t.status})]})}),e.jsx(G,{className:"max-w-[200px] truncate text-sm text-muted-foreground",children:t.notes||t.reference_number||"â"}),e.jsx(G,{className:"text-right",children:r&&e.jsxs(Ws,{children:[e.jsx(Vs,{asChild:!0,children:e.jsx(g,{variant:"ghost",size:"icon",className:"h-8 w-8",children:e.jsx(Pn,{className:"h-4 w-4"})})}),e.jsxs($s,{align:"end",children:[t.status==="succeeded"&&e.jsxs(wt,{onClick:s,children:[e.jsx($t,{className:"mr-2 h-4 w-4"}),"Send Receipt"]}),n&&e.jsxs(wt,{onClick:a,className:"text-destructive focus:text-destructive",children:[e.jsx(fi,{className:"mr-2 h-4 w-4"}),"Refund"]})]})]})})]})}function US({payment:t,memberEmail:s,open:a,onOpenChange:n}){const[r,i]=o.useState(""),l=w0(),m=d=>{d&&t&&i(s),n(d)},c=async()=>{if(!(!t||!r.trim()))try{await l.mutateAsync({paymentId:t.id,toEmail:r.trim()}),n(!1)}catch{}};return e.jsx(Fe,{open:a,onOpenChange:m,children:e.jsxs(Te,{children:[e.jsx(Ae,{children:e.jsx(Ee,{children:"Send Receipt"})}),t&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-md bg-muted p-3 text-sm",children:[e.jsxs("div",{className:"font-medium",children:["$",Number(t.net_amount).toFixed(2)," â"," ",af[t.payment_type]||t.payment_type]}),e.jsx("div",{className:"text-muted-foreground",children:Be(Ct(t.created_at),"MMM d, yyyy")})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"receipt-email",children:"Send to email"}),e.jsx(O,{id:"receipt-email",type:"email",placeholder:"[email protected]",value:r,onChange:d=>i(d.target.value)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Sends the invoice/receipt PDF for this payment."})]})]}),e.jsxs(Ge,{children:[e.jsx(g,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsx(g,{onClick:c,disabled:l.isPending||!r.trim(),children:l.isPending?"Sending...":"Send"})]})]})})}const zS=[{value:"check",label:"Check"},{value:"cash",label:"Cash"},{value:"credit_card_offline",label:"Credit Card (Offline)"},{value:"comp",label:"Comp / Waived"},{value:"wire",label:"Wire Transfer"},{value:"other",label:"Other"}];function nf({open:t,onOpenChange:s,member:a,onSuccess:n}){const r=_0(),i=Be(new Date,"yyyy-MM-dd"),[l,m]=o.useState(a||null),[c,d]=o.useState(""),[u,h]=o.useState(""),[p,x]=o.useState(""),[f,b]=o.useState(""),[N,j]=o.useState(i),[w,v]=o.useState(""),[k,S]=o.useState(!0),_=()=>{m(a||null),d(""),h(""),x(""),b(""),j(i),v(""),S(!0)},y=async P=>{P.preventDefault();const A=a?.id||l?.id;!A||!u||!C&&!c||(await r.mutateAsync({member_id:A,amount:C?0:parseFloat(c),payment_method:u,reference_number:p||null,notes:f||null,period_start:N||null,period_end:w||null,activate_membership:k}),_(),s(!1),n?.())},C=u==="comp";return e.jsx(Fe,{open:t,onOpenChange:P=>{P||_(),s(P)},children:e.jsxs(Te,{className:"max-h-[90vh] w-[95vw] max-w-lg overflow-y-auto",children:[e.jsxs(Ae,{children:[e.jsx(Ee,{children:"Record Manual Payment"}),e.jsx(tt,{children:a?`Record a payment for ${a.first_name} ${a.last_name}`:"Record an offline payment for a member"})]}),e.jsxs("form",{onSubmit:y,className:"space-y-4",children:[a?e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{children:"Member"}),e.jsxs("div",{className:"rounded-md border bg-gray-50 px-3 py-2 text-sm",children:[a.first_name," ",a.last_name,e.jsx("span",{className:"ml-2 text-muted-foreground",children:a.email})]})]}):e.jsx(ho,{selectedMember:l,onSelectMember:m,onClearMember:()=>m(null),inputId:"payment-member-search"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{children:"Payment method"}),e.jsxs(qe,{value:u,onValueChange:h,children:[e.jsx(Le,{children:e.jsx(Ie,{placeholder:"Select methodâ¦"})}),e.jsx($e,{children:zS.map(P=>e.jsx(q,{value:P.value,children:P.label},P.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"amount",children:"Amount ($)"}),e.jsx(O,{id:"amount",type:"number",min:"0",step:"0.01",placeholder:"0.00",value:C?"0":c,onChange:P=>d(P.target.value),disabled:C})]}),!C&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"reference",children:"Reference number"}),e.jsx(O,{id:"reference",placeholder:"Check #, receipt #, etc.",value:p,onChange:P=>x(P.target.value)})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"period-start",children:"Period start"}),e.jsx(O,{id:"period-start",type:"date",value:N,onChange:P=>j(P.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"period-end",children:"Period end"}),e.jsx(O,{id:"period-end",type:"date",value:w,onChange:P=>v(P.target.value)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"notes",children:"Notes"}),e.jsx(It,{id:"notes",placeholder:C?"Reason for comp/waiverâ¦":"Optional notesâ¦",value:f,onChange:P=>b(P.target.value),rows:2})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(ot,{id:"activate",checked:k,onCheckedChange:P=>S(P===!0)}),e.jsx(T,{htmlFor:"activate",className:"text-sm font-normal",children:"Activate membership upon recording payment"})]}),e.jsxs(Ge,{className:"flex-col gap-2 sm:flex-row",children:[e.jsx(g,{type:"submit",className:"min-h-[44px] w-full sm:w-auto",disabled:r.isPending||!a&&!l||!u||!C&&!c,children:r.isPending?"Recording...":"Record Payment"}),e.jsx(g,{type:"button",variant:"outline",className:"min-h-[44px] w-full sm:w-auto",onClick:()=>{_(),s(!1)},disabled:r.isPending,children:"Cancel"})]})]})]})})}const Gr={};function BS(t){return Gr[t]||(Gr[t]=rd(t).then(s=>(s||delete Gr[t],s),()=>(delete Gr[t],null))),Gr[t]}function Td(t,s){const[a,n]=o.useState(null);if(!t)return a!==null&&n(null),null;if(a&&a.key===t&&a.attempt===s)return a.promise;const r={key:t,attempt:s,promise:BS(t)};return n(r),r.promise}function Ei(t,s){const[a,n]=o.useState(t?1:0),[r,i]=o.useState(t),l=t&&!r?a+1:a;return t!==r&&(i(t),n(l)),{stripePromise:Td(t?s:null,l),elementsKey:l}}const KS={member_deleted:"Member was deleted",customer_mismatch:"Card belongs to a different customer",tier_changed:"Membership type changed after the charge",reversed_before_settlement:"Refunded or disputed before it was recorded",initial_already_settled:"Dues already paid",renewal_unsupported_duration:"Renewal type isn't supported automatically",renewal_no_anchor:"Member has no end date to renew from",existing_coverage:"Membership already paid ahead",renewal_already_applied:"Renewal already applied",legacy_admin_unknown_purpose:"Charge started before an update",missing_training_anchor:"Missing training end date"};function Fd(t){if(!t)return"Needs review";
1const s=KS[t];if(s)return s;const a=/^status_(.+)$/.exec(t);return a?`Member was already ${a[1].replace(/_/g," ")}`:"Needs review"}function Rd(t){return t.payment_metadata?.settlement??null}function QS(t){const s=Rd(t);return s?.classification==="review"&&!s.resolution}function WS({open:t,onOpenChange:s,member:a}){const n=v0(),[r,i]=o.useState(null),{stripePromise:l,elementsKey:m}=Ei(t,r?.publishableKey??null);return o.useEffect(()=>{t&&!r&&!n.isPending&&n.mutate(a.id,{onSuccess:c=>{i({clientSecret:c.client_secret,publishableKey:c.publishable_key,amount:c.amount,memberName:c.member_name,membershipTypeName:c.membership_type_name})}})},[t]),o.useEffect(()=>{t||(i(null),n.reset())},[t]),e.jsx(Fe,{open:t,onOpenChange:s,children:e.jsxs(Te,{className:"max-h-[90vh] w-[95vw] overflow-y-auto sm:max-w-[480px]",children:[e.jsxs(Ae,{children:[e.jsx(Ee,{children:"Charge card"}),e.jsxs(tt,{children:["Process a card payment for ",a.first_name," ",a.last_name]})]}),n.isPending&&e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-b-2 border-primary"})}),n.isError&&e.jsx("div",{className:"rounded-md border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-800 dark:border-red-800 dark:bg-red-950/20 dark:text-red-200",children:n.error?.response?.data?.detail||"Failed to initialize payment. Check that Stripe is configured."}),r&&l&&e.jsx(dn,{stripe:l,options:{clientSecret:r.clientSecret,appearance:{theme:"stripe",variables:{colorPrimary:"#0f172a"}}},children:e.jsx(VS,{amount:r.amount,memberName:r.memberName,membershipTypeName:r.membershipTypeName,memberId:a.id,onSuccess:()=>s(!1)})},m)]})})}function VS({amount:t,memberName:s,membershipTypeName:a,memberId:n,onSuccess:r}){const i=mn(),l=un(),m=J(),[c,d]=o.useState(!1),[u,h]=o.useState(null),[p,x]=o.useState(!1),[f,b]=o.useState(null),[N,j]=o.useState(!1),w=()=>{m.invalidateQueries({queryKey:["member",n]}),m.invalidateQueries({queryKey:["memberPayments",n]}),m.invalidateQueries({queryKey:["memberPaymentSummary",n]}),m.invalidateQueries({queryKey:["payments"]}),m.invalidateQueries({queryKey:["dashboard"]})},v=async k=>{if(k.preventDefault(),!i||!l||!N)return;d(!0),h(null);const S=await i.confirmPayment({elements:l,confirmParams:{return_url:window.location.href},redirect:"if_required"});if(S.error){h(S.error.message||"Payment failed"),d(!1);try{await Ba.logPaymentFailure({member_id:n,error_code:S.error.code||void 0,decline_code:S.error.decline_code||void 0,error_message:S.error.message||void 0,payment_intent_id:S.error.payment_intent?.id||void 0})}catch{}}else if(S.paymentIntent?.status==="succeeded"){try{await Ba.confirmPayment(S.paymentIntent.id,n)}catch(_){const y=_?.response?.data?.detail;if(_?.response?.status===409&&y?.code==="needs_review"){b(Fd(y.reason)),d(!1),w();return}console.error("Backend confirm failed:",_)}x(!0),d(!1),w()}};return f?e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{role:"status",className:"rounded-md border border-blue-200 bg-blue-50 px-4 py-3 dark:border-blue-900/50 dark:bg-blue-950/30",children:[e.jsx("p",{className:"text-sm font-medium text-blue-900 dark:text-blue-200",children:"Payment recorded for office review â the membership was not changed."}),e.jsxs("p",{className:"mt-1 text-xs text-blue-800 dark:text-blue-300",children:["$",(t/100).toFixed(2)," was charged for ",a,". Reason:"," ",f,"."]})]}),e.jsx(g,{className:"w-full",onClick:r,children:"Done"})]}):p?e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"rounded-md border border-green-200 bg-green-50 px-4 py-3 text-center dark:border-green-800 dark:bg-green-950/20",children:[e.jsx("p",{className:"text-sm font-medium text-green-800 dark:text-green-200",children:"Payment successful!"}),e.jsxs("p",{className:"mt-1 text-xs text-green-700 dark:text-green-300",children:["$",(t/100).toFixed(2)," charged for ",a]})]}),e.jsx(g,{className:"w-full",onClick:r,children:"Done"})]}):e.jsxs("form",{onSubmit:v,className:"space-y-4",children:[e.jsx("div",{className:"rounded-md border bg-gray-50 px-4 py-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:a}),e.jsx("p",{className:"text-xs text-muted-foreground",children:s})]}),e.jsxs("p",{className:"text-lg font-semibold tracking-tight",children:["$",(t/100).toFixed(2)]})]})}),e.jsx(hn,{onReady:()=>j(!0)}),u&&e.jsx("div",{className:"rounded-md border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-800 dark:border-red-800 dark:bg-red-950/20 dark:text-red-200",children:u}),e.jsx(g,{type:"submit",className:"w-full",disabled:!i||!N||c,children:c?"Processing...":`Charge $${(t/100).toFixed(2)}`})]})}function rf({invoice:t,open:s,onOpenChange:a}){const[n,r]=o.useState(""),i=rw();o.useEffect(()=>{t&&s&&r(t.member_email||"")},[t,s]);const l=async()=>
1{if(!(!t||!n.trim()))try{await i.mutateAsync({id:t.id,data:{to_email:n.trim()}}),a(!1)}catch{}};return e.jsx(Fe,{open:s,onOpenChange:a,children:e.jsxs(Te,{children:[e.jsx(Ae,{children:e.jsx(Ee,{children:"Send / Forward Invoice"})}),t&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-md bg-muted p-3 text-sm",children:[e.jsx("div",{className:"font-medium",children:t.invoice_number}),e.jsxs("div",{className:"text-muted-foreground",children:[t.member_name," â $",Number(t.amount).toFixed(2)]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"forward-email",children:"Send to email"}),e.jsx(O,{id:"forward-email",type:"email",placeholder:"[email protected]",value:n,onChange:m=>r(m.target.value)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Change the email to forward to a different address. The member's original email is pre-filled.",n!==t.member_email&&e.jsx("span",{className:"mt-1 block text-amber-600 dark:text-amber-400",children:"Forwarding to a different address will not update the invoice status."})]})]})]}),e.jsxs(Ge,{children:[e.jsx(g,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(g,{onClick:l,disabled:i.isPending||!n.trim(),children:i.isPending?"Sending...":"Send"})]})]})})}const GS={draft:"bg-muted-foreground/60",sent:"bg-amber-500",paid:"bg-emerald-500",void:"bg-red-500"},YS={draft:"Draft",sent:"Sent",paid:"Paid",void:"Void"};function HS({member:t}){const[s,a]=o.useState(1),[n,r]=o.useState(null),{data:i,isLoading:l}=eg(t.id,s),m=async(d,u)=>{try{const h=await Bs.downloadPdf(d),p=window.URL.createObjectURL(h),x=document.createElement("a");x.href=p,x.download=`${u}.pdf`,x.click(),window.URL.revokeObjectURL(p)}catch{}};if(l)return e.jsxs(L,{children:[e.jsx(ne,{children:e.jsxs(ie,{className:"flex items-center gap-2.5",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(cs,{className:"h-4 w-4"})}),"Invoices"]})}),e.jsx($,{children:e.jsx("div",{className:"space-y-2",children:Array.from({length:3}).map((d,u)=>e.jsx(Y,{className:"h-12 w-full"},u))})})]});const c=i?.items||[];return e.jsxs(e.Fragment,{children:[e.jsxs(L,{children:[e.jsx(ne,{children:e.jsxs(ie,{className:"flex items-center gap-2.5",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(cs,{className:"h-4 w-4"})}),"Invoices"]})}),e.jsxs($,{children:[c.length===0?e.jsx("p",{className:"py-4 text-center text-sm text-muted-foreground",children:"No invoices yet."}):e.jsx("div",{className:"space-y-3",children:c.map(d=>e.jsxs("div",{className:"flex items-center justify-between border-b py-2 last:border-0",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx("p",{className:"font-mono text-sm",children:d.invoice_number}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[d.description," â Due"," ",Be(Ps(d.due_date),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-sm font-medium",children:Number(d.amount).toLocaleString("en-US",{style:"currency",currency:"USD"})}),e.jsxs("span",{className:"inline-flex items-center gap-1.5 whitespace-nowrap",children:[e.jsx("span",{className:`h-1.5 w-1.5 shrink-0 rounded-full ${GS[d.status]||"bg-muted-foreground/60"}`}),e.jsx("span",{className:"text-xs font-medium",children:YS[d.status]||d.status})]}),e.jsxs(Ws,{children:[e.jsx(Vs,{asChild:!0,children:e.jsx(g,{variant:"ghost",size:"icon",className:"h-8 w-8",children:e.jsx(Pn,{className:"h-4 w-4"})})}),e.jsxs($s,{align:"end",children:[d.pdf_path&&e.jsxs(wt,{onClick:()=>m(d.id,d.invoice_number),children:[e.jsx(vs,{className:"mr-2 h-4 w-4"}),"Download PDF"]}),d.status!=="void"&&e.jsxs(wt,{onClick:()=>r(d),children:[e.jsx($t,{className:"mr-2 h-4 w-4"}),"Send / Forward Email"]})]})]})]})]},d.id))}),i&&i.pages>1&&e.jsxs("div",{className:"mt-4 flex justify-center gap-2",children:[e.jsx(g,{variant:"outline",size:"sm",disabled:s<=1,onClick:()=>a(s-1),children:"Previous"}),e.jsxs("span",{className:"px-2 py-1 text-sm text-muted-foreground",children:["Page ",s," of ",i.pages]}),e.jsx(g,{variant:"outline",size:"sm",disabled:s>=i.pages,onClick:()=>a(s+1),children:"Next"})]})]})]}),e.jsx(rf,{invoice:n,open:!!n,onOpenChange:d=>!d&&r(null)})]})}function JS(){const{id:t}=Ds(),s=kt(),{data:a,isLoading:n,error:r}=Px(t),{data:i}=Q0(a?.email),{selectedSocietyId:l}
1=V(),m=Ax(),[c,d]=o.useState(!1),[u,h]=o.useState(!1),[p,x]=o.useState(!1),[f,b]=o.useState(!1),[N,j]=o.useState(!1),[w,v]=o.useState("details"),[k,S]=o.useState(!1),[_,y]=o.useState(!1),[C,P]=o.useState(!1),[A,E]=o.useState(!1),Q=async()=>{if(!a||k)return;S(!0);const xe=window.open("about:blank","_blank");try{const z=await Gt.impersonate(a.id);localStorage.setItem("portal_access_token",z.access_token),localStorage.setItem("portal_member",JSON.stringify(z.member)),localStorage.setItem("portal_society_slug",z.society_slug),localStorage.setItem("portal_impersonated_by","admin");const ae=`/${z.society_slug}/portal/dashboard`;xe?xe.location.href=ae:window.open(ae,"_blank")}catch{xe?.close()}finally{S(!1)}},U=async()=>{a&&(await m.mutateAsync(a.id),s("/members"))},D=async xe=>{if(a){j(!0);try{await Gt.resetPassword(a.id,xe),b(!1)}finally{j(!1)}}},K=async()=>{if(!(!a||_)){y(!0),E(!1);try{await Gt.bulkSendAccessEmail([a.id],l??void 0),P(!0),setTimeout(()=>P(!1),3e3)}catch{E(!0),setTimeout(()=>E(!1),3e3)}finally{y(!1)}}};return n?e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(Y,{className:"h-10 w-10"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Y,{className:"h-8 w-48"}),e.jsx(Y,{className:"h-4 w-32"})]})]}),e.jsxs("div",{className:"grid gap-6 md:grid-cols-2",children:[e.jsx(Y,{className:"h-64"}),e.jsx(Y,{className:"h-64"})]})]}):r||!a?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12",children:[e.jsx("h2",{className:"text-xl font-semibold tracking-tight",children:"Member not found"}),e.jsx("p",{className:"mt-2 text-muted-foreground",children:"The member you're looking for doesn't exist."}),e.jsx(g,{asChild:!0,className:"mt-4",children:e.jsx(je,{to:"/members",children:"Back to members"})})]}):e.jsxs("div",{className:"space-y-6 overflow-x-hidden",children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[e.jsx(g,{variant:"ghost",size:"icon",className:"min-h-[44px] min-w-[44px]","aria-label":"Back to members",asChild:!0,children:e.jsx(je,{to:"/members",children:e.jsx(es,{className:"h-4 w-4"})})}),e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(kn,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("h1",{className:"text-2xl font-semibold tracking-tight",children:[a.first_name," ",a.last_name]}),i&&(i.scope==="marketing"||i.scope==="all")&&e.jsxs("span",{className:me("inline-flex items-center gap-1.5 rounded-full px-2.5 py-0.5 text-[11px] font-medium","bg-muted text-muted-foreground"),children:[e.jsx("span",{className:me("h-1.5 w-1.5 rounded-full",i.scope==="all"?"bg-red-500":"bg-amber-500"),"aria-hidden":"true"}),i.scope==="all"?"Email suppressed":"Unsubscribed from marketing"]})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:a.email})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(g,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs(je,{to:`/members/${a.id}/edit`,children:[e.jsx(Hs,{className:"mr-2 h-4 w-4"}),"Edit"]})}),e.jsxs(g,{size:"sm",onClick:()=>x(!0),children:[e.jsx(Qt,{className:"mr-2 h-4 w-4"}),"Charge card"]}),e.jsxs(Ws,{children:[e.jsx(Vs,{asChild:!0,children:e.jsxs(g,{variant:"outline",size:"icon",className:"h-9 w-9",children:[e.jsx(Pn,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"More actions"})]})}),e.jsxs($s,{align:"end",className:"w-56",children:[e.jsxs(wt,{onClick:()=>h(!0),children:[e.jsx(Ua,{className:"mr-2 h-4 w-4"}),"Record payment"]}),e.jsxs(wt,{onClick:K,disabled:_||C,className:A?"text-destructive focus:text-destructive":"",children:[e.jsx($t,{className:"mr-2 h-4 w-4"}),C?"Sent!":A?"Failed â try again":_?"Sendingâ¦":"Send access email"]}),e.jsxs(wt,{onClick:Q,disabled:k,children:[e.jsx(Kl,{className:"mr-2 h-4 w-4"}),"View as member"]}),e.jsxs(wt,{onClick:()=>b(!0),children:[e.jsx(An,{className:"mr-2 h-4 w-4"}),"Reset password"]}),e.jsx(Aa,{}),e.jsxs(wt,{onClick:()=>d(!0),className:"text-destructive focus:bg-destructive/10 focus:text-destructive",children:[e.jsx(Ft,{className:"mr-2 h-4 w-4"}),"Delete"]})]})]})]})]}),a.status==="pending"&&e.jsx(ZS,{memberId:a.id,onViewInvoices:()=>v("invoices")}),e.jsxs(Ur,{value:w,onValueChange:v,children:[e.jsx("div",{className:"-mx-1 overflow-x-auto px-1",children:e.jsxs(ir,{className:"inline-flex w-auto min-w-full justify-start",children:[e.jsx(bs,{value:"details",className:"min-h-[44px]",children:"Details"}),e.jsx(bs,{value:"payments",className:"min-h-[44px]",children:"Payments"}),e.jsx(bs,{value:"invoices",className:"min-h-[44px]",children:"Invoices"}),e.jsx(bs,{value:"history",className:"min-h-[44px]",children:"History"}),e.jsx(bs,{value:"override",className:"min-h-[44px]",children:"Status override"})]})}),e.jsxs(js,{value:"details",children:[e.jsx(O_,{member:a,onSwitchToHistory:()=>v("history")}),e.jsx(eS,{memberId:a.id}),e.jsxs("div",{className:"mt-6",children:[e.jsx("h3",{className:"mb-3 text-lg font-semibold tracking-tight",children:"Notes"}),e.jsx(tS,{memberId:a.id})]})]}),e.jsx(js,{value:"payments",children:e.jsx(IS,{member:a,onRecordPayment:()=>h(!0)})}),e.jsx(js,{value:"invoices",children:e.jsx(HS,{member:a})}),e.jsx(js,{value:"history",children:e.jsx(Z_,{memberId:a.id})}),e.jsx(js,{value:"override",children:e.jsx(K_,{member:a})})]}),e.jsx(Hg,{member:a,open:c,onOpenChange:d,onConfirm:U,isDeleting:m.isPending}),e.jsx(nf,{open:u,onOpenChange:h,member:a}),e.jsx(WS,{open:p,onOpenChange:x,member:a}),e.jsx(oS,{member:a,open:f,onOpenChange:b,onConfirm:D,isResetting:N})]})}function ZS({memberId:t,onViewInvoices:s}){const{data:a}=eg(t);return(a?.items||[]).some(i=>i.status==="draft"||i.status==="sent")?e.jsx(L,{className:"min-w-0 overflow-hidden border-amber-200 bg-amber-50 dark:border-amber-700 dark:bg-amber-950/20",children:e.jsxs($,{className:"flex items-center gap-3 py-3",children:[e.jsx(Bt,{className:"h-5 w-5 shrink-0 text-amber-600 dar
1k:text-amber-400"}),e.jsx("p",{className:"flex-1 text-sm text-amber-800 dark:text-amber-200",children:"Awaiting payment â this member has an outstanding invoice for membership dues."}),e.jsx(g,{variant:"outline",size:"sm",onClick:s,className:"shrink-0",children:"View invoices"})]})}):null}const XS={active:"Active",pending:"Pending",rejected:"Rejected",grace:"Grace",lapsed:"Lapsed",expired:"Expired",cancelled:"Cancelled",suspended:"Suspended",archived:"Archived"},e1={active:"bg-emerald-500",pending:"bg-amber-500",rejected:"bg-red-500",grace:"bg-orange-500",lapsed:"bg-red-500",expired:"bg-red-500",cancelled:"bg-red-500",suspended:"bg-red-500",archived:"bg-muted-foreground/60"},t1={first_name:"",last_name:"",email:"",secondary_email:"",organization:"",phone:"",address_line1:"",address_line2:"",city:"",state:"",county:"",postal_code:"",country:"US",membership_type_id:"",status:"active",join_date:"",membership_start_date:"",membership_end_date:"",auto_renew:!0,show_in_directory:!0,admin_notes:"",custom_fields:{},password:""};function qm(){const{id:t}=Ds(),s=kt(),a=J(),n=t&&t!=="new",{data:r,isLoading:i}=Px(n?t:void 0),{data:l}=oa(),{data:m,isLoading:c}=er(),d=pv(),u=xv(),[h,p]=o.useState({...t1}),[x,f]=o.useState({}),[b,N]=o.useState(!n);o.useEffect(()=>{r&&(p({first_name:r.first_name||"",last_name:r.last_name||"",email:r.email||"",secondary_email:r.secondary_email||"",organization:r.organization||"",phone:r.phone||"",address_line1:r.address_line1||"",address_line2:r.address_line2||"",city:r.city||"",state:r.state||"",county:r.county||"",postal_code:r.postal_code||"",country:r.country||"US",membership_type_id:r.membership_type_id||"",status:r.status||"active",join_date:r.join_date||"",membership_start_date:r.membership_start_date||"",membership_end_date:r.membership_end_date||"",auto_renew:r.auto_renew??!0,show_in_directory:r.show_in_directory??!0,admin_notes:r.admin_notes||"",custom_fields:r.custom_fields||{},password:""}),N(!0))},[r]);const j=()=>{const y={};return h.first_name.trim()||(y.first_name="First name is required"),h.last_name.trim()||(y.last_name="Last name is required"),h.email.trim()||(y.email="Email is required"),h.email&&!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(h.email)&&(y.email="Invalid email format"),h.membership_type_id||(y.membership_type_id="Membership type is required"),!n&&h.password&&h.password.length<8&&(y.password="Password must be at least 8 characters"),m?.forEach(C=>{if(C.is_required&&C.is_active){const P=h.custom_fields[C.field_key];(P==null||P==="")&&(y[`custom_${C.field_key}`]=`${C.label} is required`)}}),f(y),Object.keys(y).length===0},w=async y=>{if(y.preventDefault(),!!j())try{if(n)await u.mutateAsync({id:t,data:{first_name:h.first_name,last_name:h.last_name,email:h.email,secondary_email:h.secondary_email||null,organization:h.organization||null,phone:h.phone||null,address_line1:h.address_line1||null,address_line2:h.address_line2||null,city:h.city||null,state:h.state||null,county:h.county||null,postal_code:h.postal_code||null,country:h.country||null,membership_type_id:h.membership_type_id||null,join_date:h.join_date||null,membership_start_date:h.membership_start_date||null,membership_end_date:h.membership_end_date||null,auto_renew:h.auto_renew,show_in_directory:h.show_in_directory,admin_notes:h.admin_notes||null,custom_fields:h.custom_fields}}),a.invalidateQueries({queryKey:["members"]}),a.invalidateQueries({queryKey:["member",t]}),s(`/members/${t}`);else{const C=await d.mutateAsync({first_name:h.first_name,last_name:h.last_name,email:h.email,secondary_email:h.secondary_email||null,organization:h.organization||null,phone:h.phone||null,address_line1:h.address_line1||null,address_line2:h.address_line2||null,city:h.city||null,state:h.state||null,county:h.county||null,postal_code:h.postal_code||null,country:h.country||null,membership_type_id:h.membership_type_id||null,status:h.status,join_date:h.join_date||null,membership_start_date:h.membership_start_date||null,membership_end_date:h.membership_end_date||null,auto_renew:h.auto_renew,show_in_directory:h.show_in_directory,admin_notes:h.admin_notes||null,custom_fields:h.custom_fields,password:h.password||null});a.invalidateQueries({queryKey:["members"]}),s(`/members/${C.id}`)}}catch(C){C.response?.data?.detail?f({submit:typeof C.response.data.detail=="string"?C.response.data.detail:JSON.stringify(C.response.data.detail)}):f({submit:"An error occurred. Please try again."})}},v=(y,C)=>{if(y.startsWith("custom_")){const P=y.replace("custom_","");p(A=>({...A,custom_fields:{...A.custom_fields,[P]:C}
1}))}else p(P=>({...P,[y]:C}));x[y]&&f(P=>{const A={...P};return delete A[y],A})},k=y=>{if(!y.is_active)return null;const C=`custom_${y.field_key}`,P=h.custom_fields[y.field_key],A=x[C];switch(y.field_type){case"text":case"email":case"phone":case"url":return e.jsxs("div",{className:"space-y-2",children:[e.jsxs(T,{htmlFor:C,children:[y.label," ",y.is_required&&"*"]}),e.jsx(O,{id:C,type:y.field_type==="email"?"email":y.field_type==="url"?"url":"text",value:P||"",onChange:E=>v(C,E.target.value),placeholder:y.placeholder||void 0,className:A?"border-destructive":""}),y.help_text&&e.jsx("p",{className:"text-sm text-muted-foreground",children:y.help_text}),A&&e.jsx("p",{className:"text-sm text-destructive",children:A})]},y.id);case"textarea":return e.jsxs("div",{className:"space-y-2",children:[e.jsxs(T,{htmlFor:C,children:[y.label," ",y.is_required&&"*"]}),e.jsx(It,{id:C,value:P||"",onChange:E=>v(C,E.target.value),placeholder:y.placeholder||void 0,className:A?"border-destructive":""}),y.help_text&&e.jsx("p",{className:"text-sm text-muted-foreground",children:y.help_text}),A&&e.jsx("p",{className:"text-sm text-destructive",children:A})]},y.id);case"number":return e.jsxs("div",{className:"space-y-2",children:[e.jsxs(T,{htmlFor:C,children:[y.label," ",y.is_required&&"*"]}),e.jsx(O,{id:C,type:"number",value:P??"",onChange:E=>v(C,E.target.value?Number(E.target.value):null),placeholder:y.placeholder||void 0,className:A?"border-destructive":""}),y.help_text&&e.jsx("p",{className:"text-sm text-muted-foreground",children:y.help_text}),A&&e.jsx("p",{className:"text-sm text-destructive",children:A})]},y.id);case"date":return e.jsxs("div",{className:"space-y-2",children:[e.jsxs(T,{htmlFor:C,children:[y.label," ",y.is_required&&"*"]}),e.jsx(O,{id:C,type:"date",value:P||"",onChange:E=>v(C,E.target.value),className:A?"border-destructive":""}),y.help_text&&e.jsx("p",{className:"text-sm text-muted-foreground",children:y.help_text}),A&&e.jsx("p",{className:"text-sm text-destructive",children:A})]},y.id);case"dropdown":return e.jsxs("div",{className:"space-y-2",children:[e.jsxs(T,{htmlFor:C,children:[y.label," ",y.is_required&&"*"]}),e.jsxs(qe,{value:P||"",onValueChange:E=>v(C,E),children:[e.jsx(Le,{className:A?"border-destructive":"",children:e.jsx(Ie,{placeholder:y.placeholder||`Select ${y.label}`})}),e.jsx($e,{children:y.options?.map(E=>e.jsx(q,{value:E,children:E},E))})]}),y.help_text&&e.jsx("p",{className:"text-sm text-muted-foreground",children:y.help_text}),A&&e.jsx("p",{className:"text-sm text-destructive",children:A})]},y.id);case"checkbox":return e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(ot,{id:C,checked:P||!1,onCheckedChange:E=>v(C,E===!0)}),e.jsxs(T,{htmlFor:C,className:"font-normal",children:[y.label," ",y.is_required&&"*"]}),y.help_text&&e.jsx("p",{className:"ml-2 text-sm text-muted-foreground",children:y.help_text}),A&&e.jsx("p",{className:"text-sm text-destructive",children:A})]},y.id);default:return null}};if(n&&i||c||!b||!l)return e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-b-2 border-primary"})});const S=d.isPending||u.isPending,_=n?Hs:fa;return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(g,{variant:"ghost",size:"icon",onClick:()=>s(n?`/members/${t}`:"/members"),children:e.jsx(es,{className:"h-4 w-4"})}),e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(_,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:n?"Edit member":"Add new member"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:n?"Update member information":"Create a new member record"})]})]}),x.submit&&e.jsx("div",{className:"rounded-md bg-destructive/15 p-3 text-sm text-destructive",children:x.submit}),e.jsxs("form",{onSubmit:w,className:"space-y-6",children:[e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy
1/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(fa,{className:"h-4 w-4"})}),"Personal information"]})}),e.jsxs($,{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"first_name",children:"First name *"}),e.jsx(O,{id:"first_name",value:h.first_name,onChange:y=>v("first_name",y.target.value),className:x.first_name?"border-destructive":""}),x.first_name&&e.jsx("p",{className:"text-sm text-destructive",children:x.first_name})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"last_name",children:"Last name *"}),e.jsx(O,{id:"last_name",value:h.last_name,onChange:y=>v("last_name",y.target.value),className:x.last_name?"border-destructive":""}),x.last_name&&e.jsx("p",{className:"text-sm text-destructive",children:x.last_name})]})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"email",children:"Email *"}),e.jsx(O,{id:"email",type:"email",value:h.email,onChange:y=>v("email",y.target.value),className:x.email?"border-destructive":""}),x.email&&e.jsx("p",{className:"text-sm text-destructive",children:x.email})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"secondary_email",children:"Secondary email"}),e.jsx(O,{id:"secondary_email",type:"email",value:h.secondary_email,onChange:y=>v("secondary_email",y.target.value)})]})]}),e.jsx("div",{className:"grid gap-4 sm:grid-cols-2",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"phone",children:"Phone"}),e.jsx(O,{id:"phone",type:"tel",value:h.phone,onChange:y=>v("phone",y.target.value)})]})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"organization",children:"Organization"}),e.jsx(O,{id:"organization",value:h.organization,onChange:y=>v("organization",y.target.value),placeholder:"Practice, institution, or employer"})]})]})]}),e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(Fa,{className:"h-4 w-4"})}),"Address"]})}),e.jsxs($,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"address_line1",children:"Address line 1"}),e.jsx(O,{id:"address_line1",value:h.address_line1,onChange:y=>v("address_line1",y.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"address_line2",children:"Address line 2"}),e.jsx(O,{id:"address_line2",value:h.address_line2,onChange:y=>v("address_line2",y.target.value)})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"city",children:"City"}),e.jsx(O,{id:"city",value:h.city,onChange:y=>v("city",y.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"state",children:"State"}),e.jsx(O,{id:"state",value:h.state,onChange:y=>v("state",y.target.value)})]})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"county",children:"County"}),e.jsx(O,{id:"county",value:h.county,onChange:y=>v("county",y.target.value),placeholder:"Auto-fills from ZIP"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"postal_code",children:"Postal code"}),e.jsx(O,{id:"postal_code",value:h.postal_code,onChange:y=>v("postal_code",y.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"country",children:"Country"}),e.jsx(O,{id:"country",value:h.country,onChange:y=>v("country",y.target.value),placeholder:"US"})]})]})]})]}),e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy
1/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(qn,{className:"h-4 w-4"})}),"Membership"]})}),e.jsxs($,{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"membership_type_id",children:"Membership type *"}),e.jsxs(qe,{value:h.membership_type_id,onValueChange:y=>v("membership_type_id",y),children:[e.jsx(Le,{className:x.membership_type_id?"border-destructive":"",children:e.jsx(Ie,{placeholder:"Select membership type"})}),e.jsx($e,{children:l?.map(y=>e.jsxs(q,{value:y.id,children:[y.name," â $",y.price]},y.id))})]}),x.membership_type_id&&e.jsx("p",{className:"text-sm text-destructive",children:x.membership_type_id})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{children:"Status"}),n?e.jsxs("div",{className:"flex h-10 items-center",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5 whitespace-nowrap",children:[e.jsx("span",{className:`h-1.5 w-1.5 shrink-0 rounded-full ${e1[h.status]||"bg-muted-foreground/60"}`}),e.jsx("span",{className:"text-xs font-medium",children:XS[h.status]||h.status})]}),e.jsx("span",{className:"ml-2 text-xs text-muted-foreground",children:"Use Status Override on detail page to change"})]}):e.jsxs(qe,{value:h.status,onValueChange:y=>v("status",y),children:[e.jsx(Le,{children:e.jsx(Ie,{})}),e.jsxs($e,{children:[e.jsx(q,{value:"active",children:"Active"}),e.jsx(q,{value:"pending",children:"Pending"})]})]})]})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"join_date",children:"Join date"}),e.jsx(O,{id:"join_date",type:"date",value:h.join_date,onChange:y=>v("join_date",y.target.value)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Defaults to today if not set"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"membership_start_date",children:"Membership start"}),e.jsx(O,{id:"membership_start_date",type:"date",value:h.membership_start_date,onChange:y=>v("membership_start_date",y.target.value)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Defaults to today if not set"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"membership_end_date",children:"Membership end"}),e.jsx(O,{id:"membership_end_date",type:"date",value:h.membership_end_date,onChange:y=>v("membership_end_date",y.target.value)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Leave blank for lifetime memberships. Auto-calculated for annual types if not set."})]}),e.jsxs("div",{className:"flex flex-wrap gap-6 pt-2",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(ot,{id:"auto_renew",checked:h.auto_renew,onCheckedChange:y=>v("auto_renew",y===!0)}),e.jsx(T,{htmlFor:"auto_renew",className:"font-normal",children:"Auto-renew membership"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(ot,{id:"show_in_directory",checked:h.show_in_directory,onCheckedChange:y=>v("show_in_directory",y===!0)}),e.jsx(T,{htmlFor:"show_in_directory",className:"font-normal",children:"Show in member directory"})]})]})]})]}),e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(cs,{className:"h-4 w-4"})}),"Admin notes"]})}),e.jsx($,{children:e.jsx(It,{id:"admin_notes",value:h.admin_notes,onChange:y=>v("admin_notes",y.target.value),placeholder:"Internal notes about this member (not visible to the member)",rows:4})})]}),m&&m.length>0&&e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy
1/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(Zc,{className:"h-4 w-4"})}),"Additional information"]})}),e.jsx($,{children:e.jsx("div",{className:"grid gap-4 sm:grid-cols-2",children:m.map(y=>k(y))})})]}),!n&&e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(An,{className:"h-4 w-4"})}),"Account setup"]})}),e.jsx($,{className:"space-y-4",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"password",children:"Portal password"}),e.jsx(O,{id:"password",type:"password",value:h.password,onChange:y=>v("password",y.target.value),className:x.password?"border-destructive":""}),x.password&&e.jsx("p",{className:"text-sm text-destructive",children:x.password}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Leave blank to skip portal access. Member can be sent a login link later."})]})})]}),e.jsxs("div",{className:"flex justify-end gap-3",children:[e.jsx(g,{type:"button",variant:"outline",onClick:()=>s(n?`/members/${t}`:"/members"),children:"Cancel"}),e.jsx(g,{type:"submit",disabled:S,children:S?"Savingâ¦":n?"Save changes":"Create member"})]})]})]})}function pa({icon:t}){return e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(t,{className:"h-4 w-4","aria-hidden":"true"})})}function s1({selectedSocietyId:t,mailchimpEnabled:s,mailerliteEnabled:a,modulesKnown:n=!0}){const[r,i]=o.useState(!0),[l,m]=o.useState(!0),[c,d]=o.useState(!0),{data:u,isLoading:h,refetch:p}=to(t),x=Lx(),f=$x(),b=Hv(),[N,j]=o.useState({stripe_publishable_key:"",stripe_secret_key:"",stripe_webhook_secret:""}),[w,v]=o.useState(null),[k,S]=o.useState(null),{data:_,isLoading:y,refetch:C}=tr(t),P=qx(),A=Ix(),E=Ox(),[Q,U]=o.useState({mailchimp_api_key:"",mailchimp_server_prefix:""}),[D,K]=o.useState(null),[xe,z]=o.useState(null),{data:ae,isLoading:ue,refetch:_e}=sr(t),ee=Ux(),se=zx(),le=Bx(),[oe,Pe]=o.useState(""),[M,I]=o.use
1State(null),[R,X]=o.useState(null),Se=e0(),ce=t0(),[ke,ve]=o.useState(""),[Ne,Qe]=o.useState(null),[Oe,Ce]=o.useState(null),[ze,Ze]=o.useState(!1),Re=o.useMemo(()=>{const be=[];return s&&_?.mailchimp_connected&&_.list_id&&be.push({key:"mailchimp",label:`Mailchimp â ${_.list_name||_.list_id}`}),a&&ae?.mailerlite_connected&&ae.group_id&&be.push({key:"mailerlite",label:`MailerLite â ${ae.group_name||ae.group_id}`}),be},[s,_,a,ae]),de=ke||(Re.length===1?Re[0].key:""),ge=Se.isPending||ce.isPending,mt=s0(),[ye,Ke]=o.useState(null),[ut,De]=o.useState(null),he=!!(s&&_?.mailchimp_connected&&_.list_id),Xe=async()=>{Ke(null),De(null);try{const be=await mt.mutateAsync(t);Ke(be)}catch(be){const lt=be?.response?.data?.detail;De(lt||(be instanceof Error?be.message:"Failed to sync suppressions."))}},rt=async()=>{Qe(null),Ce(null),Ze(!1);try{let be;de==="mailchimp"?be=await Se.mutateAsync({societyId:t,listId:_.list_id}):be=await ce.mutateAsync({societyId:t,groupId:ae.group_id}),Qe(be)}catch(be){const lt=be?.response?.data?.detail;Ce(lt||(be instanceof Error?be.message:"Sync failed."))}},yt=u?.stripe_mode||"live",dt=yt==="test",jt=dt?"live":"test",Ot=k||yt;return e.jsxs("div",{className:"space-y-4",children:[e.jsxs(L,{className:dt?"border-amber-400 dark:border-amber-600":"","data-tour":"stripe-card",children:[e.jsxs(ne,{className:"cursor-pointer select-none",onClick:()=>i(!r),children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsxs(ie,{className:"flex items-center gap-2.5",children:[e.jsx(pa,{icon:Qt}),"Stripe configuration"]}),h?e.jsx(Y,{className:"h-6 w-28"}):u?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:`inline-flex items-center gap-1 rounded-full px-2.5 py-0.5 text-xs font-medium ${u.stripe_connected?"bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400":"bg-gray-100 text-gray-600 dark:bg-gray-800 dark:text-gray-400"}`,children:u.stripe_connected?e.jsxs(e.Fragment,{children:[e.jsx(vn,{className:"h-3 w-3"})," Connected"]}):e.jsxs(e.Fragment,{children:[e.jsx(Ca,{className:"h-3 w-3"})," Not Connected"]})}),e.jsx("span",{className:`inline-flex items-center gap-1 rounded-full px-2.5 py-0.5 text-xs font-medium ${dt?"bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400":"bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400"}`,children:dt?"Test Mode":"Live Mode"})]}):null]}),e.jsx(ps,{className:`h-4 w-4 text-muted-foreground transition-transform ${r?"rotate-180":""}`})]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Connect your Stripe account to accept membership payments.",u?.publishable_key_prefix&&e.jsxs(e.Fragment,{children:[" ","Active key:"," ",e.jsx("code",{className:"rounded bg-muted px-1 py-0.5 text-xs",children:u.publishable_key_prefix})]})]})]}),r&&e.jsxs($,{className:"space-y-4","data-tour":"stripe-keys-form",children:[dt&&e.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-amber-200 bg-amber-50 px-3 py-2 text-sm text-amber-800 dark:border-amber-800 dark:bg-amber-900/20 dark:text-amber-300",children:[e.jsx(Bt,{className:"h-4 w-4 shrink-0"}),e.jsx("span",{children:"Test mode is active. Payments will use Stripe test keys. No real charges will be made."})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Stripe Mode"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:dt?"Using test keys â switch to live for real payments":"Using live keys â switch to test for safe testing"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:`text-xs font-medium ${dt?"text-muted-foreground":"text-blue-600 dark:text-blue-400"}`,children:"Live"}),e.jsx("button",{type:"button",role:"switch","aria-checked":dt,disabled:b.isPending,className:`relative inline-flex h-6 w-11 shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 ${dt?"bg-amber-500":"bg-blue-600"}`,onClick:async be=>{be.stopPropagation(),v(null);try{await b.mutateAsync({societyId:t,mode:jt}),v({type:"success",message:`Switched to ${jt} mode.`}),S(null),p()}catch(lt){const ht=lt instanceof Error?lt.message:"Failed to toggle mode.",zt=lt?.response?.data?.detail;(zt||ht).toLowerCase().includes("no stripe")&&(zt||ht).toLowerCase().includes("keys configured")?(S(jt),v({type:"error",message:`Add your ${jt} keys below first, then toggle modes.`})):v({type:"error",message:zt||ht})}},children:e.jsx("span",{className:`pointer-events-none inline-block h-5 w-5 transform rounded-full bg-white shadow ring-0 transition duration-200 ease-in-out ${dt?"translate-x-5":"translate-x-0"}`})}),e.jsx("span",{className:`text-xs font-medium ${dt?"text-amber-600 dar
1k:text-amber-400":"text-muted-foreground"}`,children:"Test"})]})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsxs("div",{className:`rounded-lg border p-3 ${dt?"":"border-blue-200 bg-blue-50/50 dark:border-blue-800 dark:bg-blue-900/10"}`,children:[e.jsx("p",{className:"mb-1 text-xs font-medium text-muted-foreground",children:"Live Keys"}),dt?u?.has_inactive_publishable_key?e.jsx("p",{className:"text-sm",children:e.jsx("code",{className:"rounded bg-muted px-1 py-0.5 text-xs",children:u.inactive_publishable_key_prefix})}):e.jsx("button",{type:"button",className:"text-sm text-blue-600 hover:underline dark:text-blue-400",onClick:()=>S("live"),children:"+ Add live keys"}):u?.has_publishable_key?e.jsx("p",{className:"text-sm",children:e.jsx("code",{className:"rounded bg-muted px-1 py-0.5 text-xs",children:u.publishable_key_prefix})}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Not configured"})]}),e.jsxs("div",{className:`rounded-lg border p-3 ${dt?"border-amber-200 bg-amber-50/50 dark:border-amber-800 dark:bg-amber-900/10":""}`,children:[e.jsx("p",{className:"mb-1 text-xs font-medium text-muted-foreground",children:"Test Keys"}),dt?u?.has_publishable_key?e.jsx("p",{className:"text-sm",children:e.jsx("code",{className:"rounded bg-muted px-1 py-0.5 text-xs",children:u.publishable_key_prefix})}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Not configured"}):u?.has_inactive_publishable_key?e.jsx("p",{className:"text-sm",children:e.jsx("code",{className:"rounded bg-muted px-1 py-0.5 text-xs",children:u.inactive_publishable_key_prefix})}):e.jsx("button",{type:"button",className:"text-sm text-blue-600 hover:underline dark:text-blue-400",onClick:()=>S("test"),children:"+ Add test keys"})]})]}),e.jsxs("div",{className:"border-t pt-4",children:[e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsx("p",{className:"text-sm font-medium",children:k?`Enter ${k} keys`:`Enter ${yt} keys`}),!k&&e.jsxs("button",{type:"button",className:"rounded-md border border-blue-200 bg-blue-50 px-2.5 py-1 text-xs font-medium text-blue-700 hover:bg-blue-100 dark:border-blue-800 dark:bg-blue-900/20 dark:text-blue-400 dark:hover:bg-blue-900/40",onClick:()=>S(jt),children:["Enter ",jt," keys instead"]}),k&&e.jsxs("button",{type:"button",className:"rounded-md border px-2.5 py-1 text-xs font-medium text-muted-foreground hover:bg-muted",onClick:()=>S(null),children:["Back to ",yt," keys"]})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"stripe_publishable_key",children:"Publishable key"}),e.jsx(O,{id:"stripe_publishable_key",placeholder:Ot==="test"?"pk_test_...":"pk_live_...",value:N.stripe_publishable_key,onChange:be=>j(lt=>({...lt,stripe_publishable_key:be.target.value}))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"stripe_secret_key",children:"Secret key"}),e.jsx(O,{id:"stripe_secret_key",type:"password",placeholder:Ot==="test"?"sk_test_...":"sk_live_...",value:N.stripe_secret_key,onChange:be=>j(lt=>({...lt,stripe_secret_key:be.target.value}))})]})]}),e.jsxs("div",{className:"mt-4 space-y-2",children:[e.jsx(T,{htmlFor:"stripe_webhook_secret",children:"Webhook secret (optional)"}),e.jsx(O,{id:"stripe_webhook_secret",type:"password",placeholder:"whsec_...",value:N.stripe_webhook_secret,onChange:be=>j(lt=>({...lt,stripe_webhook_secret:be.target.value}))})]})]}),w&&e.jsx("p",{className:`text-sm ${w.type==="success"?"text-green-600":"text-destructive"}`,children:w.message}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(g,{disabled:!N.stripe_publishable_key||!N.stripe_secret_key||x.isPending,onClick:async()=>{v(null);try{await x.mutateAsync({societyId:t,data:{stripe_publishable_key:N.stripe_publishable_key,stripe_secret_key:N.stripe_secret_key,stripe_webhook_secret:N.stripe_webhook_secret||void 0,mode:Ot}}),v({type:"success",message:`${Ot==="test"?"Test":"Live"} keys saved successfully.`}),j({stripe_publishable_key:"",stripe_secret_key:"",stripe_webhook_secret:""}),S(null),p()}catch{v({type:"error",message:"Failed to save keys."})}},children:x.isPending?"Saving...":`Save ${Ot==="test"?"Test":"Live"} Keys`}),e.jsx(g,{variant:"outline",disabled:f.isPending||!u?.has_secret_key,onClick:async()=>{v(null);try{const be=await f.mutateAsync(t);be.success?(v({type:"success",message:`Connection successful${be.account_name?`: ${be.account_name}`:""} (${be.account_id})`}),p()):v({type:"error",message:be.error||"Test failed."})}catch{v({type:"error",message:"Connection test failed."})}},children:f.isPending?"Testing...":"Test Connection"})]})]})]}),s&&e.jsxs(L,{children:[e.jsxs(ne,{className:"cursor-pointer select-none",onClick:()=>m(!l),children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsxs(ie,{className:"flex items-center gap-2.5",children:[e.jsx(pa,{icon:$t}),"Mailchimp configuration"]}),y?e.jsx(Y,{className:"h-6 w-28"}):_?e.jsx("span",{className:`inline-flex items-center gap-1 rounded-full px-2.5 py-0.5 text-xs font-medium ${_.mailchimp_connected?"bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400":"bg-gray-100 text-gray-600 dark:bg-gray-800 dark:text-gray-400"}`,children:_.mailchimp_connected?e.jsxs(e.Fragment,{children:[e.jsx(vn,{className:"h-3 w-3"})," Connected"]}):e.jsxs(e.Fragment,{children:[e.jsx(Ca,{className:"h-3 w-3"})," Not Connected"]})}):null]}),e.jsx(ps,{className:`h-4 w-4 text-muted-foreground transition-transform ${l?"rotate-180":""}`})]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Connect your Mailchimp account to sync members to an audie
1nce.",_?.server_prefix&&e.jsxs(e.Fragment,{children:[" ","Server:"," ",e.jsx("code",{className:"rounded bg-muted px-1 py-0.5 text-xs",children:_.server_prefix})]}),_?.list_id&&e.jsxs(e.Fragment,{children:[" ","· List:"," ",e.jsx("code",{className:"rounded bg-muted px-1 py-0.5 text-xs",children:_.list_id})]})]})]}),l&&e.jsxs($,{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"mailchimp_api_key",children:"API Key"}),e.jsx(O,{id:"mailchimp_api_key",type:"password",placeholder:"xxxxxxxxxxxxxxxx-us14",value:Q.mailchimp_api_key,onChange:be=>U(lt=>({...lt,mailchimp_api_key:be.target.value}))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"mailchimp_server_prefix",children:"Server prefix"}),e.jsx(O,{id:"mailchimp_server_prefix",placeholder:"us14",value:Q.mailchimp_server_prefix,onChange:be=>U(lt=>({...lt,mailchimp_server_prefix:be.target.value}))}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Found in your API key after the dash (e.g., us14)"})]})]}),D&&e.jsx("p",{className:`text-sm ${D.type==="success"?"text-green-600":"text-destructive"}`,children:D.message}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(g,{disabled:!Q.mailchimp_api_key||!Q.mailchimp_server_prefix||P.isPending||A.isPending,onClick:async()=>{K(null),z(null);try{await P.mutateAsync({societyId:t,data:{mailchimp_api_key:Q.mailchimp_api_key,mailchimp_server_prefix:Q.mailchimp_server_prefix}});const be=await A.mutateAsync(t);be.success?(K({type:"success",message:`Connected${be.account_name?` to ${be.account_name}`:""}. ${be.lists?.length?"Select an audience below.":"No audiences found."}`}),be.lists&&be.lists.length>0&&z(be.lists),U({mailchimp_api_key:"",mailchimp_server_prefix:""}),C()):K({type:"error",message:be.error||"Connection test failed."})}catch{K({type:"error",message:"Failed to save or test credentials."})}},children:P.isPending||A.isPending?"Saving & Testing...":"Save & Test"}),_?.has_api_key&&e.jsx(g,{variant:"outline",disabled:A.isPending,onClick:async()=>{K(null),z(null);try{const be=await A.mutateAsync(t);be.success?(K({type:"success",message:`Connected${be.account_name?` to ${be.account_name}`:""}`}),be.lists&&be.lists.length>0&&z(be.lists),C()):K({type:"error",message:be.error||"Test failed."})}catch{K({type:"error",message:"Connection test failed."})}},children:A.isPending?"Testing...":"Test Connection"})]}),xe&&xe.length>0&&e.jsxs("div",{className:"space-y-2 border-t pt-4",children:[e.jsx(T,{children:"Select audience"}),e.jsx("div",{className:"space-y-2",children:xe.map(be=>e.jsxs("button",{type:"button",className:`w-full rounded-md border p-3 text-left transition-colors hover:bg-muted ${_?.list_id===be.id?"border-blue-500 bg-blue-50 dark:bg-blue-900/30":""}`,onClick:async()=>{try{await E.mutateAsync({societyId:t,listId:be.id}),K({type:"success",message:`Selected audience: ${be.name}`}),C()}catch{K({type:"error",message:"Failed to select audience."})}},disabled:E.isPending,children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"font-medium",children:be.name}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:[be.member_count.toLocaleString()," contacts"]})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:be.id})]},be.id))})]})]})]}),a&&e.jsxs(L,{children:[e.jsxs(ne,{className:"cursor-pointer select-none",onClick:()=>d(!c),children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsxs(ie,{className:"flex items-center gap-2.5",children:[e.jsx(pa,{icon:$t}),"MailerLite configuration"]}),ue?e.jsx(Y,{className:"h-6 w-28"}):ae?e.jsx("span",{className:`inline-flex items-center gap-1 rounded-full px-2.5 py-0.5 text-xs font-medium ${ae.mailerlite_connected?"bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400":"bg-gray-100 text-gray-600 dark:bg-gray-800 dark:text-gray-400"}`,children:ae.mailerlite_connected?e.jsxs(e.Fragment,{children:[e.jsx(vn,{className:"h-3 w-3"})," Connected"]}):e.jsxs(e.Fragment,{children:[e.jsx(Ca,{className:"h-3 w-3"})," Not Connected"]})}):null]}),e.jsx(ps,{className:`h-4 w-4 text-muted-foreground transition-transform ${c?"rotate-180":""}`})]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Connect your MailerLite account to sync members to a group.",ae?.group_id&&e.jsxs(e.Fragment,{children:[" ","· Group:"," ",e.jsx("code",{className:"rounded bg-muted px-1 py-0.5 text-xs",children:ae.group_id})]})]})]}),c&&e.jsxs($,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"mailerlite_api_key",children:"API Key"}),e.jsx(O,{id:"mailerlite_api_key",type:"password",placeholder:"Enter your MailerLite API key",value:oe,onChange:be=>Pe(be.target.value)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Found in MailerLite â Integrations â API"})]}),M&&e.jsx("p",{className:`text-sm ${M.type==="success"?"text-green-600":"text-destructive"}`,children:M.message}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(g,{disabled:!oe||ee.isPending||se.isPending,onClick:async()=>{I(null),X(null);try{await ee.mutateAsync({societyId:t,data:{mailerlite_api_key:oe}});const be=await se.mutateAsync(t);be.success?(I({type:"success",message:`Connected${be.account_name?` to ${be.account_name}`:""}
1. ${be.groups?.length?"Select a group below.":"No groups found."}`}),be.groups&&be.groups.length>0&&X(be.groups),Pe(""),_e()):I({type:"error",message:be.error||"Connection test failed."})}catch{I({type:"error",message:"Failed to save or test credentials."})}},children:ee.isPending||se.isPending?"Saving & Testing...":"Save & Test"}),ae?.has_api_key&&e.jsx(g,{variant:"outline",disabled:se.isPending,onClick:async()=>{I(null),X(null);try{const be=await se.mutateAsync(t);be.success?(I({type:"success",message:`Connected${be.account_name?` to ${be.account_name}`:""}`}),be.groups&&be.groups.length>0&&X(be.groups),_e()):I({type:"error",message:be.error||"Test failed."})}catch{I({type:"error",message:"Connection test failed."})}},children:se.isPending?"Testing...":"Test Connection"})]}),R&&R.length>0&&e.jsxs("div",{className:"space-y-2 border-t pt-4",children:[e.jsx(T,{children:"Select group"}),e.jsx("div",{className:"space-y-2",children:R.map(be=>e.jsx("button",{type:"button",className:`w-full rounded-md border p-3 text-left transition-colors hover:bg-muted ${ae?.group_id===be.id?"border-green-500 bg-green-50 dark:bg-green-900/30":""}`,onClick:async()=>{try{await le.mutateAsync({societyId:t,groupId:be.id}),I({type:"success",message:`Selected group: ${be.name}`}),_e()}catch{I({type:"error",message:"Failed to select group."})}},disabled:le.isPending,children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"font-medium",children:be.name}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:[be.subscriber_count.toLocaleString()," subscribers"]}
1)]})},be.id))})]})]})]}),n&&(!s||!a)&&e.jsxs("p",{className:"rounded-lg border bg-muted/30 px-4 py-3 text-sm text-muted-foreground",children:[[!s&&"Mailchimp",!a&&"MailerLite"].filter(Boolean).join(" and ")," ",!s&&!a?"are":"is"," turned off for this society. Korevera turns features on and off; contact support to use"," ",!s&&!a?"them":"it","."]}),Re.length>0&&e.jsxs(L,{children:[e.jsxs(ne,{children:[e.jsxs(ie,{className:"flex items-center gap-2.5",children:[e.jsx(pa,{icon:St}),"Sync members"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Push your member list to an email provider."})]}),e.jsxs($,{className:"space-y-4",children:[Re.length>1&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"sync_provider",children:"Email provider"}),e.jsxs("select",{id:"sync_provider",className:"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",value:de,onChange:be=>{ve(be.target.value),Qe(null),Ce(null)},children:[e.jsx("option",{value:"",children:"Select a provider..."}),Re.map(be=>e.jsx("option",{value:be.key,children:be.label},be.key))]})]}),Re.length===1&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Provider:"," ",e.jsx("span",{className:"font-medium text-foreground",children:Re[0].label})]}),e.jsx(g,{disabled:!de||ge,onClick:rt,children:ge?e.jsxs(e.Fragment,{children:[e.jsx(St,{className:"mr-2 h-4 w-4 animate-spin"}),"Syncing..."]}):"Sync Members"}),Ne&&e.jsxs("div",{className:`rounded-md border p-3 text-sm ${Ne.errors.length>0?"border-amber-200 bg-amber-50 text-amber-800 dark:border-amber-800 dark:bg-amber-900/20 dark:text-amber-300":"border-green-200 bg-green-50 text-green-800 dark:border-green-800 dark:bg-green-900/20 dark:text-green-300"}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(vn,{className:"h-4 w-4 shrink-0"}),e.jsxs("span",{children:["Synced ",Ne.added+Ne.updated," members. Added:"," ",Ne.added,", Updated: ",Ne.updated,Ne.skipped?`, Skipped (suppressed): ${Ne.skipped}`:"",", Errors: ",Ne.errors.length]})]}),Ne.errors.length>0&&e.jsxs("div",{className:"mt-2",children:[e.jsxs("button",{type:"button",className:"flex items-center gap-1 text-xs font-medium hover:underline",onClick:()=>Ze(!ze),children:[e.jsx(ts,{className:`h-3 w-3 transition-transform ${ze?"rotate-90":""}`}),ze?"Hide":"Show"," error details"]}),ze&&e.jsx("ul",{className:"mt-1 space-y-1 text-xs",children:Ne.errors.map((be,lt)=>e.jsxs("li",{children:[be.email?e.jsxs(e.Fragment,{children:[e.jsx("code",{children:be.email}),":"," "]}):null,be.error]},lt))})]})]}),Oe&&e.jsx("p",{className:"text-sm text-destructive",children:Oe}),he&&e.jsxs("div",{className:"space-y-2 border-t pt-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Push bounced and complained addresses from your suppression list to Mailchimp as unsubscribed, so they're never emailed there."}),e.jsx(g,{variant:"outline",disabled:mt.isPending,onClick:Xe,children:mt.isPending?e.jsxs(e.Fragment,{children:[e.jsx(St,{className:"mr-2 h-4 w-4 animate-spin"}),"Syncing..."]}):"Sync suppressions to Mailchimp"}),ye&&e.jsxs("p",{className:"text-sm text-green-700 dark:text-green-300",children:["Unsubscribed ",ye.unsubscribed," suppressed address",ye.unsubscribed===1?"":"es"," in Mailchimp.",ye.errors.length>0?` ${ye.errors.length} could not be updated.`:""]}),ut&&e.jsx("p",{className:"text-sm text-destructive",children:ut})]})]})]})]})}function a1({selectedSocietyId:t,mailchimpEnabled:s,mailerliteEnabled:a}){const n=to(t),r=Or(t),i=tr(s?t:void 0),l=sr(a?t:void 0),m=[{name:"Stripe (payments)",query:n,detail:n.data?.stripe_connected?`Connected${n.data.stripe_mode==="test"?" (test mode)":""}`:"Not connected"},{name:"Email sender",query:r,detail:r.data?.connected?`Connected${r.data.from_address?`: sends as ${r.data.from_address}`:""}`:"Koreveraâs platform sender"}];return s&&m.push({name:"Mailchimp",query:i,detail:i.data?.mailchimp_connected?`Connected${i.data.list_name?`: ${i.data.list_name}`:""}`:"Not connected"}),a&&m.push({name:"MailerLite",query:l,detail:l.data?.mailerlite_connected?`Connected${l.data.group_name?`: ${l.data.group_name}`:""}`:"Not connected"}),e.jsxs(L,{children:[e.jsxs(ne,{children:[e.jsxs(ie,{className:"flex items-center gap-2.5 text-base font-semibold tracking-tight",children:[e.jsx(pa,{icon:Ql}),"Integrations"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Payments, email and mailing-list connections are set up and changed by Korevera platform admins. Ask them if something here needs to change."})]}),e.jsx($,{children:e.jsx("dl",{className:"divide-y rounded-md border text-sm",children:m.map(c=>e.jsxs("div",{className:"flex items-center justify-between gap-4 px-4 py-3",children:[e.jsx("dt",{className:"font-medium",children:c.name}),e.jsx("dd",{className:"text-right text-muted-foreground",children:c.query.isLoading?e.jsx(Y,{className:"h-4 w-28","aria-label":`Loading ${c.name} status`}):c.query.isError?"Status couldnât be loaded":c.detail})]},c.name))})})]})}const n1=2*1024*1024,Im=["image/png","image/jpeg","image/webp"],r1={logo:{noun:"logo",alt:"Society logo",previewClass:"h-16 w-auto max-w-[200px]",hint:"PNG, JPEG, or WebP â max 2 MB"},favicon:{noun:"favicon",alt:"Society favicon",previewClass:"h-8 w-8",hint:"Square PNG, JPEG, or WebP, at least 192Ã192px â max 2 MB"}};function Pl({societyId:t,kind:s,url:a}){const n=r1[s],r=Wv(),i=Vv(),l=Gv(),m=Yv(),c=s==="logo"?r:l,d=s==="logo"?i:m,u=o.useRef(null),[h,p]=o.use
1State(!1),[x,f]=o.useState(null),b=async j=>{if(f(null),!Im.includes(j.type)){f("Invalid file type. Please upload a PNG, JPEG, or WebP image.");return}if(j.size>n1){f("File too large. Maximum size is 2 MB.");return}try{await c.mutateAsync({societyId:t,file:j})}catch{f(`Failed to upload the ${n.noun}. Please try again.`)}},N=async()=>{f(null);try{await d.mutateAsync(t)}catch{f(`Failed to remove the ${n.noun}. Please try again.`)}};return e.jsxs("div",{className:"space-y-4",children:[a&&e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("img",{src:`${ds}${a}`,alt:n.alt,className:`${n.previewClass} rounded border object-contain`}),e.jsxs(g,{type:"button",variant:"outline",size:"sm",onClick:()=>{N()},disabled:d.isPending,className:"text-destructive hover:text-destructive",children:[d.isPending?e.jsx(He,{className:"mr-1.5 h-4 w-4 animate-spin","aria-hidden":"true"}):e.jsx(Ft,{className:"mr-1.5 h-4 w-4","aria-hidden":"true"}),"Remove ",n.noun]})]}),e.jsx("button",{type:"button",className:`relative flex w-full cursor-pointer flex-col items-center justify-center rounded-lg border-2 border-dashed px-6 py-8 transition-colors ${h?"border-foreground
1/40 bg-muted/50":"border-border hover:border-foreground/30"}`,"data-tour":s==="logo"?"logo-upload":void 0,onClick:()=>u.current?.click(),onDragOver:j=>{j.preventDefault(),p(!0)},onDragLeave:()=>p(!1),onDrop:j=>{j.preventDefault(),p(!1);const w=j.dataTransfer.files[0];w&&b(w)},disabled:c.isPending,children:c.isPending?e.jsx(He,{className:"h-8 w-8 animate-spin text-muted-foreground","aria-hidden":"true"}):e.jsxs(e.Fragment,{children:[e.jsx(Wl,{className:"mb-2 h-8 w-8 text-muted-foreground","aria-hidden":"true"}),e.jsxs("span",{className:"text-sm font-medium text-muted-foreground",children:["Click or drag & drop to upload a ",n.noun]}),e.jsx("span",{className:"mt-1 text-xs text-muted-foreground",children:n.hint})]})}),e.jsx("input",{ref:u,type:"file",accept:Im.join(","),className:"hidden","aria-label":`Upload ${n.noun}`,onChange:j=>{const w=j.target.files?.[0];w&&b(w),j.target.value=""}}),x&&e.jsx("p",{role:"alert",className:"text-sm text-destructive",children:x})]})}const Al=/^#[0-9a-fA-F]{6}$/;function lf({value:t,onChange:s,onBlur:a,error:n,disabled:r,inputRef:i}){return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("input",{type:"color","aria-label":"Pick brand color",value:Al.test(t)?t:"#000000",onChange:l=>s(l.target.value),disabled:r,className:"h-10 w-14 cursor-pointer rounded border p-1"}),e.jsx(O,{ref:i,value:t,onChange:l=>s(l.target.value),onBlur:a,"aria-label":"Brand color hex value","aria-invalid":!!n,placeholder:"#1a365d",disabled:r,className:"w-32 font-mono"}),e.jsx("div",{className:"h-10 flex-1 rounded border",style:{backgroundColor:Al.test(t)?t:void 0},"aria-hidden":"true"})]}),n&&e.jsx("p",{role:"alert",className:"text-sm text-destructive",children:n}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Applied to the member portal header, buttons, and signup page."})]})}const i1="#1a365d";function l1({selectedSocietyId:t}){const s=J(),{data:a}=Qs(),n=a?.primary_color||i1,[r,i]=o.useState(null),l=r?.societyId===t?r.value:void 0,m=b=>i(b===void 0?null:{societyId:t,value:b}),c=l??n,[d,u]=o.useState(null),h=d?.societyId===t?d:null,p=b=>u(b&&{...b,societyId:t}),x=W({mutationFn:({societyId:b,primary_color:N})=>Ks.update(b,{primary_color:N}),onSuccess:(b,{societyId:N})=>{s.setQueryData(["society",N],b),i(j=>j?.societyId===N&&j.value===b.primary_color?null:j),s.invalidateQueries({queryKey:["society",N]}),s.invalidateQueries({queryKey:["societies"]})}}),f=!Al.test(c);return e.jsxs(L,{children:[e.jsxs(ne,{children:[e.jsxs(ie,{className:"flex items-center gap-2.5",children:[e.jsx(pa,{icon:Vl}),"Branding"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Logo, favicon and brand color used on the member portal and invoices. Images save as soon as you choose or remove them."})]}),e.jsxs($,{className:"space-y-6",children:[e.jsx(Pl,{societyId:t,kind:"logo",url:a?.logo_url},`logo-${t}`),e.jsxs("div",{className:"space-y-3 border-t pt-4",children:[e.jsx("p",{className:"text-sm font-medium",children:"Favicon (browser and home-screen icon)"}),e.jsx(Pl,{societyId:t,kind:"favicon",url:a?.favicon_url},`favicon-${t}`)]}),e.jsxs("div",{className:"space-y-3 border-t pt-4",children:[e.jsx("p",{className:"text-sm font-medium",children:"Brand color"}),e.jsx(lf,{value:c,onChange:b=>{p(null),m(b)},error:l!==void 0&&f?"Must be a valid hex color (e.g. #1a365d)":void 0}),h&&!(h.ok&&c!==n)&&e.jsx("p",{role:h.ok?"status":"alert",className:`text-sm ${h.ok?"text-emerald-700 dark:text-emerald-400":"text-destructive"}`,children:h.message}),e.jsx(g,{disabled:x.isPending||f||c===n,onClick:async()=>{p(null);try{await x.mutateAsync({societyId:t,primary_color:c}),p({ok:!0,message:"Brand color saved."})}catch{p({ok:!1,message:"Brand color wasnât saved. Please try again."})}},children:x.isPending?"Savingâ¦":"Save brand color"})]})]})]})}const o1=[{key:"city",label:"City"},{key:"state",label:"State"},{key:"organization",label:"Organization"},{key:"membership_type",label:"Membership Type"},{key:"email",label:"Email"},{key:"phone",label:"Phone"}],c1=["name","city","state","organization","membership_type"];function d1({selectedSocietyId:t}
1){const[s,a]=o.useState(!0),[n,r]=o.useState(!0),i=J(),{data:l,isLoading:m}=re({queryKey:["society-settings",t],queryFn:()=>ks.getSocietySettings(t),enabled:!!t}),c=W({mutationFn:S=>ks.updateSocietySettings(S,t),onSuccess:()=>{i.invalidateQueries({queryKey:["society-settings"]}),i.invalidateQueries({queryKey:["setup-status"]})}}),[d,u]=o.useState(!0),[h,p]=o.useState(c1),[x,f]=o.useState(null);o.useEffect(()=>{if(l){u(l.member_directory_enabled===!0);const S=l.member_directory_fields;Array.isArray(S)&&p(S)}},[l]);const b=S=>{p(_=>_.includes(S)?_.filter(y=>y!==S):[..._,S])},[N,j]=o.useState({invoice_check_payable_to:"",invoice_mailing_address:"",invoice_online_payment_url:"",invoice_notes:"",enable_check_payment:!1}),[w,v]=o.useState(null);o.useEffect(()=>{l&&j({invoice_check_payable_to:l.invoice_check_payable_to||"",invoice_mailing_address:l.invoice_mailing_address||"",invoice_online_payment_url:l.invoice_online_payment_url||"",invoice_notes:l.invoice_notes||"",enable_check_payment:!!l.enable_check_payment})},[l]);const k=l?.emails_paused===!0;return e.jsxs("div",{className:"space-y-4",children:[e.jsxs(L,{className:k?"border-amber-500":"",children:[e.jsxs(ne,{children:[e.jsxs(ie,{className:"flex items-center gap-2.5",children:[e.jsx("span",{className:`flex h-7 w-7 shrink-0 items-center justify-center rounded-lg ${k?"bg-amber-100 text-amber-600 dark:bg-amber-900/30 dark:text-amber-400":"bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300"}`,children:e.jsx($t,{className:"h-4 w-4"})}),"Email automations"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Controls all automated emails: renewal reminders, dunning notices, welcome emails, and receipts."})]}),e.jsx($,{children:m?e.jsx(Y,{className:"h-10 w-40"}):e.jsxs("div",{className:`flex items-center justify-between rounded-lg border p-4 ${k?"border-amber-500 bg-amber-50 dark:bg-amber-950/20":""}`,children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(T,{className:"text-base font-semibold",children:k?"Email automations paused":"Email automations enabled"}),e.jsx("p",{className:`text-sm ${k?"text-amber-700 dark:text-amber-400":"text-muted-foreground"}`,children:k?"All outgoing emails are blocked. Toggle on to resume sending.":"Emails are sending normally. Toggle off to pause all outgoing emails."})]}),e.jsx(ss,{checked:!k,disabled:c.isPending,onCheckedChange:async S=>{await c.mutateAsync({emails_paused:!S})}})]})})]}),e.jsxs(L,{children:[e.jsxs(ne,{className:"cursor-pointer select-none",onClick:()=>a(!s),children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(ie,{className:"flex items-center gap-2.5",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(Lt,{className:"h-4 w-4"})}),"Member directory"]}),e.jsx(ps,{className:`h-4 w-4 text-muted-foreground transition-transform ${s?"rotate-180":""}`})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Allow portal members to browse and search the member directory."})]}),s&&e.jsx($,{className:"space-y-4",children:m?e.jsx(Y,{className:"h-10 w-40"}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-4",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(T,{children:"Enable member directory"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Members can browse other members who opt in via their profile."})]}),e.jsx(ss,{checked:d,onCheckedChange:u})]}),d&&e.jsxs("div",{className:"space-y-3 border-t pt-4",children:[e.jsx(T,{children:"Visible fields"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Name is always shown. Select additional fields to display."}),e.jsx("div",{className:"grid gap-2 sm:grid-cols-2",children:o1.map(S=>e.jsxs("label",{className:"flex cursor-pointer items-center gap-2 rounded-md border p-3 transition-colors hover:bg-muted/50",children:[e.jsx("input",{type:"checkbox",checked:h.includes(S.key),onChange:()=>b(S.key),className:"h-4 w-4 accent-primary"}),e.jsx("span",{className:"text-sm font-medium",children:S.label})]},S.key))})]}),x&&e.jsx("p",{className:`text-sm ${x.type==="success"?"text-green-600":"text-destructive"}`,children:x.message}),e.jsx(g,{disabled:c.isPending,onClick:async()=>{f(null);try{await c.mutateAsync({member_directory_enabled:d,member_directory_fields:d?h:void 0}),f({type:"success",message:"Directory settings saved."})}catch{f({type:"error",message:"Failed to save directory settings."})}},children:c.isPending?"Saving...":"Save Directory Settings"})]})})]}),e.jsxs(L,{"data-tour":"invoice-settings",children:[e.jsxs(ne,{className:"cursor-pointer select-none",onClick:()=>r(!n),children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(ie,{className:"flex items-center gap-2.5",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy
1/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(cs,{className:"h-4 w-4"})}),"Invoice settings"]}),e.jsx(ps,{className:`h-4 w-4 text-muted-foreground transition-transform ${n?"rotate-180":""}`})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Configure payment instructions shown on invoice PDFs."})]}),n&&e.jsx($,{className:"space-y-4",children:m?e.jsx(Y,{className:"h-32"}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-4",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(T,{children:"Allow pay by check on signup & renewal"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Members can choose to pay by check instead of credit card. An invoice will be emailed to them."})]}),e.jsx(ss,{checked:!!N.enable_check_payment,onCheckedChange:S=>j(_=>({..._,enable_check_payment:S}))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"invoice_check_payable_to",children:"Check payable to"}),e.jsx(O,{id:"invoice_check_payable_to",placeholder:"e.g. New York Society of Gastroenterology",value:N.invoice_check_payable_to,onChange:S=>j(_=>({..._,invoice_check_payable_to:S.target.value}))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"invoice_mailing_address",children:"Mailing address"}),e.jsx(It,{id:"invoice_mailing_address",placeholder:`123 Main St 2Suite 100 3New York, NY 10001`,rows:3,value:N.invoice_mailing_address,onChange:S=>j(_=>({..._,invoice_mailing_address:S.target.value}))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"invoice_notes",children:"Invoice notes"}),e.jsx(It,{id:"invoice_notes",placeholder:"Optional notes shown at the bottom of invoices",rows:2,value:N.invoice_notes,onChange:S=>j(_=>({..._,invoice_notes:S.target.value}))})]}),w&&e.jsx("p",{className:`text-sm ${w.type==="success"?"text-green-600":"text-destructive"}`,children:w.message}),e.jsx(g,{disabled:c.isPending,onClick:async()=>{v(null);try{await c.mutateAsync(N),v({type:"success",message:"Invoice settings saved."})}catch{v({type:"error",message:"Failed to save invoice settings."})}},children:c.isPending?"Saving...":"Save Invoice Settings"})]})})]})]})}const Ro={list:async t=>{const s=t?{society_id:t}:{};return(await F.get("/api-tokens",{params:s})).data},create:async(t,s)=>{const a=s?{society_id:s}:{};return(await F.post("/api-tokens",{name:t},{params:a})).data},revoke:async(t,s)=>{const a=s?{society_id:s}:{};await F.delete(`/api-tokens/${t}`,{params:a})}};function m1(){const{selectedSocietyId:t}=V(),s=J(),[a,n]=o.useState(!0),[r,i]=o.useState(!1),[l,m]=o.useState(null),[c,d]=o.useState(""),[u,h]=o.useState(null),[p,x]=o.useState(null),{data:f,isLoading:b}=re({queryKey:["api-tokens",t],queryFn:()=>Ro.list(t)}),N=W({mutationFn:y=>Ro.create(y,t),onSuccess:y=>{h(y),d(""),s.invalidateQueries({queryKey:["api-tokens"]})}}),j=W({mutationFn:y=>Ro.revoke(y,t),onSuccess:()=>{m(null),s.invalidateQueries({queryKey:["api-tokens"]})}}),w=()=>{c.trim()&&N.mutate(c.trim())},v=async()=>{u&&(await navigator.clipboard.writeText(u.token),x("token"),setTimeout(()=>x(null),2e3))},k=async()=>{if(!u)return;const y=JSON.stringify({mcpServers:{ams:{type:"sse",url:`${ds}/mcp/sse`,headers:{Authorization:`Bearer ${u.token}`}}}},null,2);await navigator.clipboard.writeText(y),x("config"),setTimeout(()=>x(null),2e3)},S=`${ds}/mcp/sse`,_=f?.find(y=>y.id===l);return e.jsxs(e.Fragment,{children:[e.jsxs(L,{children:[e.jsxs(ne,{className:"cursor-pointer select-none",onClick:()=>n(!a),children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(ie,{className:"flex items-center gap-2.5",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx($b,{className:"h-4 w-4"})}),"API tokens"]}),e.jsx(ps,{className:`h-4 w-4 text-muted-foreground transition-transform ${a?"rotate-180":""}`})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Create tokens for AI tools (Claude Code, Claude desktop, MCP) to ask read-only questions about your members, like whoâs up for renewal or lapsed recently. Answers never include email addresses, phone numbers or payment details."})]}),a&&e.jsxs($,{className:"space-y-4",children:[b?e.jsx(Y,{className:"h-20 w-full"}):f&&f.length>0?e.jsx("div",{className:"rounded-md border",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b bg-muted/50",children:[e.jsx("th",{className:"px-3 py-2 text-left text-[11px] font-medium uppercase tracking-wider text-muted-foreground
3/80",children:"Name"}),e.jsx("th",{className:"px-3 py-2 text-left text-[11px] font-medium uppercase tracking-wider text-muted-foreground/80",children:"Prefix"}),e.jsx("th",{className:"hidden px-3 py-2 text-left text-[11px] font-medium uppercase tracking-wider text-muted-foreground/80 sm:table-cell",children:"Last used"}),e.jsx("th",{className:"hidden px-3 py-2 text-left text-[11px] font-medium uppercase tracking-wider text-muted-foreground/80 md:table-cell",children:"Created"}),e.jsx("th",{className:"px-3 py-2 text-right text-[11px] font-medium uppercase tracking-wider text-muted-foreground/80"})]})}),e.jsx("tbody",{children:f.map(y=>e.jsxs("tr",{className:"border-b last:border-0",children:[e.jsx("td",{className:"px-3 py-2",children:y.name}),e.jsxs("td",{className:"px-3 py-2 font-mono text-xs text-muted-foreground",children:[y.token_prefix,"..."]}),e.jsx("td",{className:"hidden px-3 py-2 text-muted-foreground sm:table-cell",children:y.last_used_at?Ct(y.last_used_at).toLocaleDateString():"Never"}),e.jsx("td",{className:"hidden px-3 py-2 text-muted-foreground md:table-cell",children:Ct(y.created_at).toLocaleDateString()}),e.jsx("td",{className:"px-3 py-2 text-right",children:e.jsx(g,{variant:"ghost",size:"sm",className:"text-red-600 hover:bg-red-50 hover:text-red-700 dark:text-red-400 dark:hover:bg-red-950/30",onClick:()=>m(y.id),children:e.jsx(Ft,{className:"h-4 w-4"})})})]},y.id))})]})}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"No API tokens yet."}),e.jsxs(g,{variant:"outline",size:"sm",onClick:()=>{i(!0),h(null)},children:[e.jsx(Rt,{className:"mr-1 h-4 w-4"}),"Create Token"]})]})]}),e.jsx(Fe,{open:r,onOpenChange:y=>{N.isPending||(i(y),h(null),d(""))},children:e.jsxs(Te,{className:"sm:max-w-lg",children:[e.jsxs(Ae,{children:[e.jsx(Ee,{children:u?"Token Created":"Create API Token"}),e.jsx(tt,{children:u?"Copy your token now â it won't be shown again.":"Give your token a name to identify it later."})]}),u?e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"flex select-all items-center gap-2 break-all rounded-md bg-muted p-3 font-mono text-xs",children:u.token}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(g,{variant:"outline",size:"sm",onClick:v,children:[p==="token"?e.jsx(Xt,{className:"mr-1 h-4 w-4"}):e.jsx(za,{className:"mr-1 h-4 w-4"}),p==="token"?"Copied":"Copy Token"]}),e.jsxs(g,{variant:"outline",size:"sm",onClick:k,children:[p==="config"?e.jsx(Xt,{className:"mr-1 h-4 w-4"}):e.jsx(za,{className:"mr-1 h-4 w-4"}),p==="config"?"Copied":"Copy MCP Config"]})]}),e.jsxs("div",{className:"space-y-1 rounded-md border bg-muted/50 p-3 text-xs",children:[e.jsx("p",{className:"font-medium text-foreground",children:"MCP Connection"}),e.jsxs("p",{className:"text-muted-foreground",children:["URL: ",e.jsx("span",{className:"font-mono",children:S})]}),e.jsxs("p",{className:"text-muted-foreground",children:["Auth: ",e.jsxs("span",{className:"font-mono",children:["Bearer ",u.token_prefix,"..."]})]})]}),e.jsxs("div",{className:"flex items-start gap-2 text-xs text-amber-600 dark:text-amber-400",children:[e.jsx(Bt,{className:"mt-0.5 h-4 w-4 shrink-0"}),e.jsx("span",{children:"This token grants read-only access to your society data. Store it securely and revoke it if compromised."})]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(T,{htmlFor:"token-name",children:"Token name"}),e.jsx(O,{id:"token-name",placeholder:"e.g. Claude Code",value:c,onChange:y=>d(y.target.value),onKeyDown:y=>{y.key==="Enter"&&w()},maxLength:100})]}),N.isError&&e.jsx("p",{className:"text-sm text-destructive",children:N.error?.message||"Failed to create token"})]}),e.jsx(Ge,{children:u?e.jsx(g,{onClick:()=>{i(!1),h(null)},children:"Done"}):e.jsxs(e.Fragment,{children:[e.jsx(g,{variant:"outline",onClick:()=>{i(!1),d("")},children:"Cancel"}),e.jsxs(g,{onClick:w,disabled:!c.trim()||N.isPending,children:[N.isPending&&e.jsx(He,{className:"mr-1 h-4 w-4 animate-spin"}),"Create"]})]})})]})}),e.jsx(Fe,{open:!!l,onOpenChange:y=>{j.isPending||m(y?l:null)},children:e.jsxs(Te,{className:"sm:max-w-md",children:[e.jsxs(Ae,{children:[e.jsx(Ee,{children:"Revoke Token"}),e.jsxs(tt,{children:["Are you sure you want to revoke ",e.jsx("strong",{children:_?.name}),"? Any tools using this token will stop working immediately."]})]}),j.isError&&e.jsx("p",{className:"text-sm text-destructive",children:j.error?.message||"Failed to revoke token"}),e.jsxs(Ge,{children:[e.jsx(g,{variant:"outline",onClick:()=>m(null),disabled:j.isPending,children:"Cancel"}),e.jsxs(g,{variant:"destructive",onClick:()=>l&&j.mutate(l),disabled:j.isPending,children:[j.isPending&&e.jsx(He,{className:"mr-1 h-4 w-4 animate-spin"}),"Revoke"]})]})]})})]})}function u1(){const[t,s]=o.useState(!0),{user:a}=V(),n=a?.role==="super_admin"||a?.role==="society_admin";return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["These apply to this society. Your own sign-in settings, like passkeys, are in"," ",e.jsx(je,{to:"/account",className:"font-medium text-foreground underline underline-offset-2",children:"Your account"}),"."]}),n&&e.jsx(m1,{}),e.jsx(h1,{open:t,onToggle:()=>s(!t)})]})}function h1({open:t,onToggle:s}){const{data:a,isLoading:n}=Mx(),r=Av(),i=Dx(),l=r.isPending||i.isPending;return e.jsxs(L,{children:[e.jsxs(ne,{className:"cursor-pointer select-none",onClick:s,children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsxs(ie,{className:"flex items-center gap-2.5",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy
3/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(wo,{className:"h-4 w-4"})}),"Demo data"]}),a?.has_demo_data&&e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full bg-amber-100 px-2.5 py-0.5 text-xs font-medium text-amber-700 dark:bg-amber-900/30 dark:text-amber-400",children:[e.jsx(wo,{className:"h-3 w-3"})," Active"]})]}),e.jsx(ps,{className:`h-4 w-4 text-muted-foreground transition-transform ${t?"rotate-180":""}`})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:a?.seed_allowed===!1&&!a?.has_demo_data?"Demo data is only available before a society has real member data.":"Load realistic sample data to populate dashboard widgets for demos. All demo data can be cleared with one click before going live."})]}),t&&e.jsx($,{children:n?e.jsx(Y,{className:"h-10 w-40"}):a?.has_demo_data?e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("span",{className:"text-sm text-muted-foreground",children:[a.counts.members," members, ",a.counts.events," events, ",a.counts.polls," ","polls"]})}),e.jsxs(g,{variant:"outline",className:"border-red-300 text-red-600 hover:bg-red-50 hover:text-red-700 dark:border-red-700 dark:text-red-400 dark:hover:bg-red-950/30 dark:hover:text-red-300",onClick:()=>i.mutate(),disabled:l,children:[i.isPending?e.jsx(He,{className:"mr-1 h-4 w-4 animate-spin"}):e.jsx(Ft,{className:"mr-1 h-4 w-4"}),"Clear Demo Data"]}),i.isError&&e.jsx("p",{className:"text-sm text-destructive",children:i.error?.response?.data?.detail||i.error?.message||"Failed to clear"})]}):a?.seed_allowed===!1?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Demo data is unavailable for this society because it has real member data."}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs(g,{onClick:()=>r.mutate(),disabled:l,children:[r.isPending?e.jsx(He,{className:"mr-1 h-4 w-4 animate-spin"}):e.jsx(wo,{className:"mr-1 h-4 w-4"}),"Load Demo Data"]}),r.isError&&e.jsx("p",{className:"text-sm text-destructive",children:r.error?.response?.data?.detail||r.error?.message||"Failed to seed"})]})})]})}function p1(){const{selectedSocietyId:t,user:s}=V(),{data:a}=Qs(),n=s?.role==="super_admin",[r,i]=ws(),l=r.get("tab")??"integrations",m=l==="account"?"data":l,c=d=>{const u=new URLSearchParams(r);u.set("tab",d),i(u,{replace:!0})};return t?e.jsx(nr,{tourIds:["connect-stripe","upload-logo","invoice-settings"],children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(cn,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:"Society settings"}),e.jsxs("p",{className:"mt-1 text-sm text-muted-foreground",children:["Integrations and configuration for"," ",e.jsx("span",{className:"font-medium text-foreground",children:a?.name??"this society"})]})]})]}),n&&a?.name&&e.jsx("div",{className:"rounded-md border border-amber-300 bg-amber-50/60 px-4 py-3 text-sm text-amber-800 dark:border-amber-700 dark:bg-amber-950/20 dark:text-amber-300",children:"Integration changes here affect this society's live payments and email."}),e.jsxs(Ur,{value:m,onValueChange:c,children:[e.jsx("div",{className:"-mx-1 overflow-x-auto px-1",children:e.jsxs(ir,{className:"inline-flex h-auto w-auto min-w-full gap-1 rounded-lg bg-muted/60 p-1",children:[e.jsxs(bs,{value:"integrations",className:"min-h-[40px] gap-2 rounded-md px-4 data-[state=active]:bg-background data-[state=active]:shadow-sm",children:[e.jsx(Ql,{className:"h-4 w-4"}),"Integrations"]}),e.jsxs(bs,{value:"branding",className:"min-h-[40px] gap-2 rounded-md px-4 data-[state=active]:bg-background data-[state=active]:shadow-sm",children:[e.jsx(Vl,{className:"h-4 w-4"}),"Branding"]}),e.jsxs(bs,{value:"general",className:"min-h-[40px] gap-2 rounded-md px-4 data-[state=active]:bg-background data-[state=active]:shadow-sm",children:[e.jsx(kp,{className:"h-4 w-4"}),"General"]}),e.jsxs(bs,{value:"data",className:"min-h-[40px] gap-2 rounded-md px-4 data-[state=active]:bg-background data-[state=active]:shadow-sm",children:[e.jsx(An,{className:"h-4 w-4","aria-hidden":"true"}),"API & demo data"]})]})}),e.jsx(js,{value:"integrations",className:"mt-6",children:n?e.jsx(s1,{selectedSocietyId:t,mailchimpEnabled:a?.settings?.mailchimp_enabled===!0,mailerliteEnabled:a?.settings?.mailerlite_enabled===!0,modulesKnown:!!a}):e.jsx(a1,{selectedSocietyId:t,mailchimpEnabled:a?.settings?.mailchimp_enabled===!0,mailerliteEnabled:a?.settings?.mailerlite_enabled===!0})}),e.jsx(js,{value:"branding",className:"mt-6",children:e.jsx(l1,{selectedSocietyId:t})}),e.jsx(js,{value:"general",className:"mt-6",children:e.jsx(d1,{selectedSocietyId:t})}),e.jsx(js,{value:"data",className:"mt-6",children:e.jsx(u1,{})})]})]})}):e.jsxs("div",{className:"space-y-2",children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:"Society settings"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Your account isnât linked to a society, so there are no society settings to show. Your own settings are in"," ",e.jsx(je,{to:"/account",className:"font-medium text-foreground underline underline-offset-2",children:"Your account"}),"."]})]})}const x1={annual:"Annual",until_date:"Until Date",lifetime:"Lifetime"},g1={annual:"Membership renews every year",until_date:"Membership valid until a specific date",lifetime:"One-time payment, never expires"};function f1({types:t,onEdit:s,onDelete:a,onToggleActive:n,onReorder:r}){const i=(c,d)=>{c.dataTransfer.setData("text/plain",String(d)),c.dataTransfer.effectAllowed="move"},l=c=>{c.preventDefault(),c.dataTransfer.dropEffect="move"},m=(c,d)=>{c.preventDefault();const u=parseInt(c.dataTransfer.getData("text/plain"),10);u!==d&&r(u,d)};return t.length===0?e.jsxs("div",{className:"rounded-md border bg-muted py-12 text-center","data-tour":"mt-list",children:[e.jsx("p",{className:"text-muted-foreground",children:"No membership types defined yet."}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:'Click "Add Type" to create your first membership type.'})]}):e.jsx("div",{className:"space-y-2","data-tour":"mt-list",children:t.map((c,d)=>e.jsxs("div",{draggable:!0,onDragStart:u=>i(u,d),onDragOver:l,onDrop:u=>
3m(u,d),className:`flex cursor-move items-center gap-4 rounded-md border bg-card p-4 transition-colors hover:bg-muted ${c.is_active?"":"opacity-60"}`,children:[e.jsx(Tr,{className:"h-5 w-5 flex-shrink-0 text-muted-foreground"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium text-foreground",children:c.name}),e.jsxs(fs,{children:[e.jsx(ys,{asChild:!0,children:e.jsxs("span",{className:"inline-flex cursor-default items-center gap-1.5 whitespace-nowrap",children:[e.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-muted-foreground/60"}),e.jsx("span",{className:"text-xs font-medium",children:x1[c.duration_type]||c.duration_type})]})}),e.jsx(hs,{children:g1[c.duration_type]||c.duration_type})]}),c.auto_renew_enabled&&c.duration_type==="annual"&&e.jsxs(fs,{children:[e.jsx(ys,{asChild:!0,children:e.jsxs("span",{className:"inline-flex cursor-default items-center gap-1.5 whitespace-nowrap",children:[e.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-emerald-500"}),e.jsx("span",{className:"text-xs font-medium",children:"Auto-renew"})]})}),e.jsx(hs,{children:"Automatically renews at the end of the membership period"})]}),c.show_on_signup&&e.jsxs(fs,{children:[e.jsx(ys,{asChild:!0,children:e.jsxs("span",{className:"inline-flex cursor-default items-center gap-1.5 whitespace-nowrap",children:[e.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-emerald-500"}),e.jsx("span",{className:"text-xs font-medium",children:"Signup"})]})}),e.jsx(hs,{children:"Shown as an option on the public signup form"})]})]}),e.jsxs("div",{className:"mt-1 flex items-center gap-3 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"font-medium text-foreground",children:["$",Number(c.price).toFixed(2)]}),c.auto_renew_enabled&&c.auto_renew_discount_percent>0&&e.jsxs("span",{children:[c.auto_renew_discount_percent,"% off with auto-renew"]}),e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(Lt,{className:"h-3 w-3"}),c.member_count," member",c.member_count!==1?"s":""]}),c.description&&e.jsx("span",{className:"max-w-[200px] truncate",children:c.description})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(fs,{children:[e.jsx(ys,{asChild:!0,children:e.jsxs("div",{className:"mr-2 flex items-center gap-2",children:[c.is_active?e.jsx(ca,{className:"h-4 w-4 text-green-600"}):e.jsx(Er,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(ss,{checked:c.is_active,onCheckedChange:()=>n(c),"aria-label":c.is_active?"Deactivate type":"Activate type"})]})}),e.jsx(hs,{children:c.is_active?"Active â visible to admins and members":"Inactive â hidden from members"})]}),e.jsxs(fs,{children:[e.jsx(ys,{asChild:!0,children:e.jsxs(g,{variant:"ghost",size:"icon",onClick:()=>s(c),children:[e.jsx(Hs,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Edit"})]})}),e.jsx(hs,{children:"Edit"})]}),e.jsxs(fs,{children:[e.jsx(ys,{asChild:!0,children:e.jsxs(g,{variant:"ghost",size:"icon",onClick:()=>a(c),disabled:c.member_count>0,children:[e.jsx(Ft,{className:`h-4 w-4 ${c.member_count>0?"text-muted-foreground":"text-destructive"}`}),e.jsx("span",{className:"sr-only",children:"Delete"})]})}),e.jsx(hs,{children:c.member_count>0?"Cannot delete â members are assigned to this type":"Delete"})]})]})]},c.id))})}const Mo="__none__";function Ss({value:t,onChange:s,noneLabel:a,placeholder:n,disabled:r,children:i,className:l,ariaLabel:m}){return e.jsxs(qe,{value:t??Mo,onValueChange:c=>s(c===Mo?null:c),disabled:r,children:[e.jsx(Le,{className:l,"aria-label":m,children:e.jsx(Ie,{placeholder:n??a})}),e.jsxs($e,{children:[e.jsx(q,{value:Mo,children:a}),i]})]})}const y1=[{value:"annual",label:"Annual"},{value:"until_date",label:"Until Date"},{value:"lifetime",label:"Lifetime"}];function b1({open:t,onOpenChange:s,membershipType:a,allTypes:n,onSave:r,isSubmitting:i,error:l}){const m=!!a,{register:c,handleSubmit:d,reset:u,watch:h,setValue:p,formState:{errors:x}}=Fr({defaultValues:{name:"",description:"",price:0,duration_type:"annual",auto_renew_enabled:!0,auto_renew_discount_percent:10,is_active:!0,show_on_signup:!0,requires_approval:!0,counts_as_active:!0,eligible_as_non_member_role:!0,converts_to_type_id:null,conversion_grace_days:365,term_length_years:null}}),f=h("duration_type"),b=h("auto_renew_enabled"),N=h("price"),j=h("term_length_years"),w=j===null&&b;o.useEffect(()=>{u(a?{name:a.name,description:a.description||"",price:a.price,duration_type:a.duration_type,auto_renew_enabled:a.auto_renew_enabled,auto_renew_discount_percent:a.auto_renew_discount_percent,is_active:a.is_active,show_on_signup:a.show_on_signup,requires_approval:a.requires_approval,counts_as_active:a.counts_as_active,eligible_as_non_member_role:a.is_non_member?!1:a.eligible_as_non_member_role,converts_to_type_id:a.c
3onverts_to_type_id||null,conversion_grace_days:a.conversion_grace_days,term_length_years:a.term_length_years?String(a.term_length_years):null}:{name:"",description:"",price:0,duration_type:"annual",auto_renew_enabled:!0,auto_renew_discount_percent:10,is_active:!0,show_on_signup:!0,requires_approval:!0,counts_as_active:!0,eligible_as_non_member_role:!0,converts_to_type_id:null,conversion_grace_days:365,term_length_years:null})},[a,u]);const v=n.filter(S=>S.id!==a?.id),k=async S=>{const _={name:S.name,description:S.description||null,price:S.price,duration_type:S.duration_type,auto_renew_enabled:S.auto_renew_enabled,auto_renew_discount_percent:S.auto_renew_enabled?S.auto_renew_discount_percent:0,is_active:S.is_active,show_on_signup:S.show_on_signup,requires_approval:S.requires_approval,counts_as_active:S.counts_as_active,eligible_as_non_member_role:S.eligible_as_non_member_role,converts_to_type_id:S.converts_to_type_id,conversion_grace_days:S.conversion_grace_days,term_length_years:S.term_length_years===null?null:Number(S.term_length_years)};await r(_)};return e.jsx(Fe,{open:t,onOpenChange:s,children:e.jsxs(Te,{className:"max-h-[90vh] max-w-lg overflow-y-auto",children:[e.jsxs(Ae,{children:[e.jsx(Ee,{children:m?"Edit Membership Type":"Add Membership Type"}),e.jsx(tt,{children:m?"Update the membership type details below.":"Configure a new membership tier for your society."})]}),e.jsxs("form",{onSubmit:d(k),className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"name",children:"Name *"}),e.jsx(O,{id:"name",...c("name",{required:"Name is required"}),placeholder:"Regular Member"}),x.name&&e.jsx("p",{className:"text-sm text-destructive",children:x.name.message})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"description",children:"Description"}),e.jsx(It,{id:"description",...c("description"),placeholder:"Annual membership for physiciansâ¦",rows:2})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"price",children:"Price ($)"}),e.jsx(O,{id:"price",type:"number",step:"0.01",min:"0",...c("price",{valueAsNumber:!0,min:{value:0,message:"Must be >= 0"}})}),x.price&&e.jsx("p",{className:"text-sm text-destructive",children:x.price.message})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"duration_type",children:"Duration"}),e.jsxs(qe,{value:h("duration_type"),onValueChange:S=>p("duration_type",S),children:[e.jsx(Le,{children:e.jsx(Ie,{})}),e.jsx($e,{children:y1.map(S=>e.jsx(q,{value:S.value,children:S.label},S.value))})]})]})]}),f==="annual"&&e.jsxs("div",{className:"space-y-3 rounded-md border p-3",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(ot,{id:"auto_renew_enabled",checked:w,onCheckedChange:S=>p("auto_renew_enabled",!!S),disabled:j!==null}),e.jsx(T,{htmlFor:"auto_renew_enabled",className:"cursor-pointer",children:"Enable auto-renewal"})]}),j!==null&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fixed-term types do not auto-renew"}),w&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"auto_renew_discount_percent",children:"Discount for auto-renew (%)"}),e.jsx(O,{id:"auto_renew_discount_percent",type:"number",min:"0",max:"100",...c("auto_renew_discount_percent",{valueAsNumber:!0,min:{value:0,message:"Min 0"},max:{value:100,message:"Max 100"}})})]})]}),v.length>0&&e.jsxs("div",{className:"space-y-3 rounded-md border p-3",children:[e.jsx(T,{children:"Term length & conversion (optional)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Set a fixed term length and/or convert members to another type"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"term_length_years",children:"Term length"}),e.jsxs(Ss,{value:j,onChange:S=>{p("term_length_years",S),S!==null&&p("auto_renew_enabled",!1)},noneLabel:"None (renewable)",children:[e.jsx(q,{value:"1",children:"1 year"}),e.jsx(q,{value:"2",children:"2 years"}),e.jsx(q,{value:"3",children:"3 years"}),e.jsx(q,{value:"4",children:"4 years"}),e.jsx(q,{value:"5",children:"5 years"})]})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"converts_to_type_id",children:"Converts to"}),j!==null&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Select the membership type this converts to when the term ends"}),e.jsx(Ss,{value:h("converts_to_type_id"),onChange:S=>p("converts_to_type_id",S),noneLabel:"None",placeholder:"None",children:v.map(S=>e.jsx(q,{value:S.id,children:S.name},S.id))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"conversion_grace_days",children:"Grace days"}),e.jsx(O,{id:"conversion_grace_days",type:"number",min:"0",...c("conversion_grace_days",{valueAsNumber:!0,min:0})})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{children:"Display settings"}),e.jsxs("div",{className:"space-y-2 pl-2",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(ot,{id:"is_active",checked:h("is_active"),onCheckedChange:S=>p("is_active",!!S)}),e.jsx(T,{htmlFor:"is_active",className:"cursor-pointer font-normal",children:"Active (visible to admins)"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(ot,{id:"show_on_signup",checked:h("show_on_signup"),onCheckedChange:S=>p("show_on_signup",!!S)}),e.jsx(T,{htmlFor:"show_on_signup",className:"cursor-pointer font-normal",children:"Show on public signup form"})]}),N===0&&e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(ot,{id:"requires_approval",checked:h("requires_approval"),onCheckedChange:S=>p("requires_approval",!!S)}),e.jsx(T,{htmlFor:"requires_approval",className:"cursor-pointer font-normal",children:"Requires admin approval"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"(free tier only)"})]}),e.jsxs("div",{className:"flex items-start space-x-2",children:[e.jsx(ot,{id:"counts_as_active",checked:h("counts_as_active"),onCheckedChange:S=>p("counts_as_active",!!S)}),e.jsxs("div",{className:"grid gap-0.5 leading-none",children:[e.jsx(T,{htmlFor:"counts_as_active",className:"cursor-pointer font-normal",children:"Include in active member count"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"When unchecked, members of this type won't be counted in the dashboard active members metric"})]})]}),e.jsxs("div",{className:"flex items-start space-x-2",children:[e.jsx(ot,{id:"eligible_as_non_member_role",checked:h("eligible_as_non_member_role"),onCheckedChange:S=>p("eligible_as_non_member_role",!!S),disabled:a?.is_non_member}),e.jsxs("div",{className:"grid gap-0.5 leading-none",children:[e.jsx(T,{htmlFor:"eligible_as_non_member_role",className:"cursor-pointer font-normal",children:"Offer as a role at event checkout"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["When checked, non-members can select this role at event registration and receive role-specific pricing.",a?.is_non_member&&" (Disabled for the system Non-Member type.)"]})]})]})]})]}),l&&e.jsx("p",{className:"text-sm text-destructive",children:l}),e.jsxs(Ge,{children:[e.jsx(g,{type:"button",variant:"outline",onClick:()=>s(!1),disabled:i,children:"Cancel"}),e.jsx(g,{type:"submit",disabled:i,children:i?"Saving...":m?"Update":"Create"})]})]})]})})}function j1(){const{data:t,isLoading:s}=oa(!0),a=qv(),n=Iv(),r=Ov(),i=Uv(),[l,m]=o.useState(!1),[c,d]=o.use
3State(null),[u,h]=o.useState(null),[p,x]=o.useState(null),f=[...t||[]].sort((S,_)=>S.display_order-_.display_order),b=S=>{d(S),m(!0)},N=()=>{d(null),m(!0)},j=async S=>{x(null);try{c?await n.mutateAsync({id:c.id,data:S}):await a.mutateAsync(S),m(!1),d(null)}catch(_){const y=_?.response?.data?.detail;x(typeof y=="string"&&y.trim()?y:"Failed to save membership type. Please try again.")}},w=async()=>{if(u)try{await r.mutateAsync(u.id),h(null)}catch(S){if(an(S)&&S.response?.status===422){const _=S.response.data?.detail;Ut.error(typeof _=="string"&&_.trim()?_:"Failed to delete membership type. Please try again.")}}},v=S=>{n.mutate({id:S.id,data:{is_active:!S.is_active}})},k=(S,_)=>{const y=[...f],[C]=y.splice(S,1);y.splice(_,0,C),i.mutate(y.map(P=>P.id))};return s?e.jsxs("div",{className:"space-y-6",children:[e.jsx(Y,{className:"h-8 w-48"}),e.jsx(Y,{className:"h-24 w-full"}),e.jsx(Y,{className:"h-24 w-full"}),e.jsx(Y,{className:"h-24 w-full"})]}):e.jsx(nr,{tourIds:["membership-types"],children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(qn,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:"Membership types"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Manage membership tiers, pricing, and renewal settings. Drag to reorder."})]})]}),e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:e.jsxs(g,{onClick:N,"data-tour":"mt-create-btn",children:[e.jsx(Rt,{className:"mr-2 h-4 w-4"}),"Add type"]})})]}),e.jsx(f1,{types:f,onEdit:b,onDelete:h,onToggleActive:v,onReorder:k}),e.jsx(b1,{open:l,onOpenChange:S=>{m(S),S||(d(null),x(null))},membershipType:c,allTypes:f,onSave:j,isSubmitting:a.isPending||n.isPending,error:p}),e.jsx(Fe,{open:!!u,onOpenChange:S=>!S&&h(null),children:e.jsxs(Te,{children:[e.jsxs(Ae,{children:[e.jsx(Ee,{children:"Delete membership type"}),e.jsxs(tt,{children:["Are you sure you want to delete ",e.jsx("strong",{children:u?.name}),"?",u&&u.member_count>0&&e.jsxs(e.Fragment,{children:[" ","This type has ",e.jsx("strong",{children:u.member_count})," assigned members and cannot be deleted. Reassign members first."]})]})]}),e.jsxs(Ge,{children:[e.jsx(g,{variant:"outline",onClick:()=>h(null),disabled:r.isPending,children:"Cancel"}),e.jsx(g,{variant:"destructive",onClick:w,disabled:r.isPending||(u?.member_count??0)>0,children:r.isPending?"Deletingâ¦":"Delete"})]})]})})]})})}function v1({open:t,onOpenChange:s,payment:a,onRefund:n}){const r=S0(),[i,l]=o.useState(!1),[m,c]=o.useState("");if(!a)return null;const d=()=>{l(!1),c(""),r.reset(),s(!1)},u=f=>{r.mutate({paymentId:a.id,action:f,note:m.trim()||void 0},{onSuccess:d})},h=Fd(Rd(a)?.review_reason),p=m.trim().length===0,x=!!a.stripe_payment_intent_id;return e.jsx(Fe,{open:t,onOpenChange:f=>{f?s(f):d()},children:e.jsxs(Te,{className:"max-h-[90vh] w-[95vw] max-w-lg overflow-y-auto",children:[e.jsxs(Ae,{children:[e.jsx(Ee,{children:"Resolve payment"}),e.jsxs(tt,{children:["This card payment was recorded but did not change the membership. Reason: ",h,"."]})]}),e.jsxs("div",{className:"space-y-3 text-sm",children:[e.jsxs("div",{className:"space-y-1 rounded-md border bg-muted/50 p-3",children:[e.jsx("p",{className:"font-medium",children:"1. Refund"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Return the money to the member. The review clears automatically once the refund succeeds."}),e.jsx(g,{type:"button",variant:"outline",size:"sm",disabled:!x||r.isPending,onClick:()=>{d(),n(a)},children:"Refund this payment"})]}),e.jsxs("div",{className:"space-y-1 rounded-md border bg-muted/50 p-3",children:[e.jsx("p",{className:"font-medium",children:"2. Accept as payment for the membership"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Set the member's membership first, then accept this payment for it. The payment is then counted as their dues."}),e.jsx(g,{type:"button",size:"sm",disabled:r.isPending,onClick:()=>u("accept_as_membership_payment"),children:"Accept as payment for the membership"})]}),e.jsxs("div",{className:"space-y-2 rounded-md border bg-muted/50 p-3",children:[e.jsx("p",{className:"font-medium",children:"3. Keep separate"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Keep the payment on record without tying it to the membership. A note is required."}),i?e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"settlement-note",children:"Note"}),e.jsx(It,{id:"settlement-note",placeholder:"Why is this payment being kept separate?",value:m,onChange:f=>c(f.target.value),maxLength:500,rows:3}),e.jsx(g,{type:"button",size:"sm",disabled:p||r.isPending,onClick:()=>u("keep_independent"),children:r.isPending?"Savingâ¦":"Keep separate"})]}):e.jsx(g,{type:"button",variant:"outline",size:"sm",disabled:r.isPending,onClick:()=>l(!0),children:"Keep separate"})]}),r.isError&&e.jsx("p",{role:"alert",className:"text-sm text-destructive",children:Xn(r.error,"Could not resolve this payment. Please try again.")})]}),e.jsx(Ge,{children:e.jsx(g,{type:"button",variant:"outline",onClick:d,disabled:r.isPending,children:"Cancel"})})]})})}const w1={succeeded:"bg-emerald-500",failed:"bg-red-500",pending:"bg-amber-500",refunded:"bg-muted-foreground
3/60",partially_refunded:"bg-muted-foreground/60"},N1={initial:"Initial",renewal:"Renewal",auto_renewal:"Auto-renewal",upgrade:"Upgrade",manual:"Manual"};function k1(){const[t,s]=o.useState(1),[a,n]=o.useState("all"),[r,i]=o.useState("all"),[l,m]=o.useState(""),[c,d]=o.useState(""),[u,h]=o.useState(!1),[p,x]=o.useState(null),[f,b]=o.useState(!1),[N,j]=o.useState(null),{selectedSocietyId:w}=V(),v=P=>{w&&$a.exportPayments({format:P,date_from:l||void 0,date_to:c||void 0},w)},{data:k,isLoading:S}=b0({page:t,size:20,status:a==="all"?void 0:a,paymentType:r==="all"?void 0:r,dateFrom:l||void 0,dateTo:c||void 0,needsReview:f}),_=k?.items??[],y=k?.total??0,C=k?.pages??0;return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(Qt,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:"Payments"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"View and manage payment records"})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(Ws,{children:[e.jsx(Vs,{asChild:!0,children:e.jsxs(g,{variant:"outline",children:[e.jsx(vs,{className:"mr-2 h-4 w-4"}),"Export",e.jsx(ps,{className:"ml-2 h-4 w-4"})]})}),e.jsxs($s,{align:"end",children:[e.jsx(wt,{onClick:()=>v("csv"),children:"Export CSV"}),e.jsx(wt,{onClick:()=>v("xlsx"),children:"Export Excel"}),e.jsx(wt,{onClick:()=>v("quickbooks"),children:"QuickBooks CSV"})]})]}),e.jsxs(g,{onClick:()=>h(!0),children:[e.jsx(Rt,{className:"mr-2 h-4 w-4"}),"Record payment"]})]})]}),e.jsxs("div",{className:"flex flex-wrap items-end gap-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Status"}),e.jsxs(qe,{value:a,onValueChange:P=>{n(P),s(1)},children:[e.jsx(Le,{className:"w-40",children:e.jsx(Ie,{})}),e.jsxs($e,{children:[e.jsx(q,{value:"all",children:"All statuses"}),e.jsx(q,{value:"succeeded",children:"Succeeded"}),e.jsx(q,{value:"pending",children:"Pending"}),e.jsx(q,{value:"failed",children:"Failed"}),e.jsx(q,{value:"refunded",children:"Refunded"}),e.jsx(q,{value:"partially_refunded",children:"Partially refunded"})]})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Type"}),e.jsxs(qe,{value:r,onValueChange:P=>{i(P),s(1)},children:[e.jsx(Le,{className:"w-40",children:e.jsx(Ie,{})}),e.jsxs($e,{children:[e.jsx(q,{value:"all",children:"All types"}),e.jsx(q,{value:"initial",children:"Initial"}),e.jsx(q,{value:"renewal",children:"Renewal"}),e.jsx(q,{value:"auto_renewal",children:"Auto-renewal"}),e.jsx(q,{value:"manual",children:"Manual"})]})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"From"}),e.jsx(O,{type:"date",className:"w-40",value:l,onChange:P=>{m(P.target.value),s(1)}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"To"}),e.jsx(O,{type:"date",className:"w-40",value:c,onChange:P=>{d(P.target.value),s(1)}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("span",{className:"block text-xs text-muted-foreground",children:"Review"}),e.jsxs(g,{type:"button",variant:"outline","aria-pressed":f,className:me(f&&"border-amber-500 bg-amber-50 dark:bg-amber-900/20"),onClick:()=>{b(P=>!P),s(1)},children:[e.jsx("span",{className:"mr-2 h-1.5 w-1.5 rounded-full bg-amber-500","aria-hidden":"true"}),"Needs review"]})]})]}),S?e.jsx("div",{className:"space-y-2",children:Array.from({length:8}).map((P,A)=>e.jsx(Y,{className:"h-12 w-full"},A))}):_.length===0?e.jsx("div",{className:"rounded-md border bg-muted py-12 text-center",children:e.jsx("p",{className:"text-muted-foreground",children:"No payments found."})}):e.jsxs(e.Fragment,{children:[e.jsxs(Pt,{children:[e.jsx(At,{className:"bg-muted/30",children:e.jsxs(Ue,{className:"hover:bg-transparent",children:[e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground
3/80",children:"Date"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Member"}),e.jsx(H,{className:"h-10 text-right text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Amount"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Type"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Method"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Status"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Reference"}),e.jsx(H,{className:"h-10 w-[1%]"})]})}),e.jsx(Et,{children:_.map(P=>e.jsx(_1,{payment:P,onRefund:x,onResolve:j},P.id))})]}),C>1&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Showing ",(t-1)*20+1,"â",Math.min(t*20,y)," of ",y]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(g,{variant:"outline",size:"sm",disabled:t<=1,onClick:()=>s(P=>P-1),children:"Previous"}),e.jsx(g,{variant:"outline",size:"sm",disabled:t>=C,onClick:()=>s(P=>P+1),children:"Next"})]})]})]}),e.jsx(nf,{open:u,onOpenChange:h}),e.jsx(sf,{open:!!p,onOpenChange:P=>{P||x(null)},payment:p}),e.jsx(v1,{open:!!N,onOpenChange:P=>{P||j(null)},payment:N,onRefund:x})]})}function _1({payment:t,onRefund:s,onResolve:a}){const n=QS(t),r=Fd(Rd(t)?.review_reason),i=(t.status==="succeeded"||t.status==="partially_refunded")&&!!t.stripe_payment_intent_id&&Number(t.net_amount)-Number(t.refunded_amount)>0;return e.jsxs(Ue,{className:"hover:bg-brand-navy/[0.04] dark:hover:bg-brand-navy/10",children:[e.jsx(G,{className:"whitespace-nowrap",children:Be(Ct(t.created_at),"MMM d, yyyy")}),e.jsxs(G,{children:[t.member_name?e.jsx(je,{to:`/members/${t.member_id}`,className:"font-medium hover:underline",children:t.member_name}):e.jsx("span",{className:"text-muted-foreground",children:"â"}),t.member_email&&e.jsx("span",{className:"block text-xs text-muted-foreground",children:t.member_email})]}),e.jsxs(G,{className:"text-right font-medium",children:[(t.is_comped?0:Number(t.net_amount)).toLocaleString("en-US",{style:"currency",currency:"USD"}),t.is_comped&&e.jsx("span",{className:"block text-xs text-muted-foreground",children:"comped â no cash collected"}),(t.is_comped?Number(t.amount)>
30:Number(t.net_amount)<Number(t.amount))&&e.jsxs("span",{className:"block text-xs text-muted-foreground",children:[e.jsx("span",{className:"line-through",children:Number(t.amount).toLocaleString("en-US",{style:"currency",currency:"USD"})})," ","booked"]}),Number(t.refunded_amount)>0&&e.jsxs("span",{className:"block text-xs text-amber-600 dark:text-amber-400",children:["-",Number(t.refunded_amount).toLocaleString("en-US",{style:"currency",currency:"USD"})," ","refunded"]})]}),e.jsx(G,{children:e.jsxs("span",{className:"inline-flex items-center gap-1.5 whitespace-nowrap",children:[e.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-muted-foreground/60"}),e.jsx("span",{className:"text-xs font-medium",children:N1[t.payment_type]||t.payment_type})]})}),e.jsx(G,{className:"text-sm",children:{stripe_card:"Stripe",card:"Card (imported)",check:"Check",comp:"Comp"}[t.payment_method??""]||t.payment_method||"â"}),e.jsxs(G,{children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx("span",{className:me("h-1.5 w-1.5 rounded-full",w1[t.status]||"bg-muted-foreground"),"aria-hidden":"true"}),e.jsx("span",{className:"text-xs font-medium capitalize text-foreground/85",children:t.status.replace("_"," ")})]}),n&&e.jsxs("span",{className:"mt-1 block",title:r,"data-testid":`needs-review-${t.id}`,children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-amber-500","aria-hidden":"true"}),e.jsx("span",{className:"text-xs font-medium text-amber-700 dark:text-amber-400",children:"Needs review"})]}),e.jsx("span",{className:"block text-xs text-muted-foreground",children:r})]})]}),e.jsx(G,{className:"text-sm text-muted-foreground",children:t.reference_number||"â"}),e.jsxs(G,{className:"whitespace-nowrap",children:[n&&e.jsx(g,{variant:"ghost",size:"sm",className:"text-xs text-amber-700 hover:bg-amber-100 hover:text-amber-800 dark:text-amber-400 dark:hover:bg-amber-900/30",onClick:()=>a(t),children:"Resolve"}),i&&e.jsx(g,{variant:"ghost",size:"sm",className:"text-xs text-destructive hover:bg-destructive/10 hover:text-destructive",onClick:()=>s(t),children:"Refund"})]})]})}function S1(t){const s=new Date,a=Be(s,"yyyy-MM-dd");switch(t){case"this_month":return{start:Be(om(s),"yyyy-MM-dd"),end:a};case"last_month":{const n=pj(s);return{start:Be(om(n),"yyyy-MM-dd"),end:Be(xj(n),"yyyy-MM-dd")}}case"this_quarter":{const n=Math.floor(s.getMonth()/3)*3,r=new Date(s.getFullYear(),n,1);return{start:Be(r,"yyyy-MM-dd"),end:a}}case"ytd":return{start:Be(lm(s),"yyyy-MM-dd"),end:a};case"last_year":{const n=new Date(s.getFullYear()-1,0,1);return{start:Be(n,"yyyy-MM-dd"),end:Be(new Date(s.getFullYear()-1,11,31),"yyyy-MM-dd")}}default:return{start:Be(lm(s),"yyyy-MM-dd"),end:a}}}const Bi=["#3b82f6","#6366f1","#0891b2","#64748b","#8b5cf6","#0d9488","#7c3aed","#475569"];function C1(){const[t,s]=ws(),a=t.get("preset")||"ytd",n=t.get("start")||"",r=t.get("end")||"",i=_=>{const y={preset:_};_==="custom"&&(n&&(y.start=n),r&&(y.end=r)),s(y)},l=_=>{s({preset:"custom",start:_,end:r})},m=_=>{s({preset:"custom",start:n,end:_})},c=o.useMemo(()=>a==="custom"&&n&&r?{start:n,end:r}:S1(a),[a,n,r]),d=C0(c.start,c.end),u=P0(),h=A0(),p=T0(90),x=eo(),f=Gx(),b=Yx(),N=Rx(),j=ul(),{data:w}=Qs(),v=w?.settings?.commerce_enabled===!0,k=()=>{const _=[];if(d.data?.by_month?.length&&(_.push("Revenue by Month"),_.push("Month,Revenue"),d.data.by_month.forEach(E=>_.push(`${E.month},${E.revenue.toFixed(2)}`)),_.push("")),d.data&&(_.push("Revenue Summary"),_.push(`Total Revenue,$${d.data.total_revenue.toFixed(2)}`),_.push(`Payment Count,${d.data.payment_count}`),_.push(`Average Payment,$${d.data.average_payment.toFixed(2)}`),_.push("")),d.data?.by_payment_type&&Object.keys(d.data.by_payment_type).length>0&&(_.push("Revenue by Type"),_.push("Type,Revenue,Count"),Object.entries(d.data.by_payment_type).forEach(([E,Q])=>_.push(`"${E}",${Q.revenue.toFixed(2)},${Q.count}`)),_.push("")),u.data&&(_.push("Membership Breakdown"),_.push("Type,Count"),Object.entries(u.data.by_type).forEach(([E,Q])=>_.push(`"${E}",${Q}`)),_.push(`Total,${u.data.total_members}
3`),_.push(""),_.push("Membership Status Summary"),_.push(`Active Members (incl. grace + lapsed),${u.data.active_members+u.data.grace_members+u.data.lapsed_members}`),_.push(` Active,${u.data.active_members}`),_.push(` Grace,${u.data.grace_members}`),_.push(` Lapsed,${u.data.lapsed_members}`),_.push(`Pending,${u.data.pending_members}`),_.push(`Expired,${u.data.expired_members}`),_.push("")),h.data&&(_.push("Retention Metrics"),_.push(`Renewal Rate,${h.data.renewal_rate.toFixed(1)}%`),_.push(`Retention Rate,${h.data.retention_rate.toFixed(1)}%`),_.push(`Churn Rate,${h.data.churn_rate.toFixed(1)}%`),_.push(""),h.data.cohorts?.length&&(_.push("Cohort Retention"),_.push("Period,Started,Retained,Rate"),h.data.cohorts.forEach(E=>_.push(`${E.period},${E.started},${E.retained},${E.rate.toFixed(1)}%`)),_.push(""))),p.data?.expiring_members?.length&&(_.push("Expiring Members (next 90 days)"),_.push("Name,Email,Type,Expires,Auto-Renew"),p.data.expiring_members.forEach(E=>_.push(`"${E.name}","${E.email}","${E.type||""}",${E.expires},${E.auto_renew?"Yes":"No"}`)),_.push("")),N.data){const E=N.data;if(_.push("Renewal Progress"),E.mode==="cycle"&&E.closed_cycle&&E.open_cycle){const Q=E.in_campaign?[["Current Cycle",E.closed_cycle],["Upcoming Cycle",E.open_cycle]]:[["Previous Cycle",E.closed_cycle],["Current Cycle",E.open_cycle]];for(const[U,D]of Q)_.push(`${U},${D.cycle_start} to ${D.cycle_end}`),_.push(`${U} Renewed,${D.renewed}`),_.push(`${U} Not Renewed,${D.not_renewed}`),_.push(`${U} Total Due,${D.total_due}`),_.push(`${U} Renewal Rate,${D.renewal_rate.toFixed(1)}%`);_.push(`Auto-Renew Pending,${E.auto_renew_pending}`),E.open_cycle.pacing_prev_rate!==null&&_.push(`Same Point Last Campaign,${E.open_cycle.pacing_prev_rate.toFixed(1)}%`)}else _.push(`Renewed,${E.renewed}`),_.push(`Outstanding,${E.not_renewed}`),_.push(`Total Due,${E.total_due}`),_.push(`Renewal Rate,${E.renewal_rate.toFixed(1)}%`),_.push(`Auto-Renew Pending,${E.auto_renew_pending}`),E.previous_cycle?.total_due&&(_.push(`Previous Cycle Renewed,${E.previous_cycle.renewed}`),_.push(`Previous Cycle Total,${E.previous_cycle.total_due}`),_.push(`Previous Cycle Rate,${E.previous_cycle.renewal_rate.toFixed(1)}%`));_.push("")}if(j.data&&j.data.total_lapsed>0){const E=j.data;_.push("Lapsed Recovery"),_.push(`Total Lapsed,${E.total_lapsed}`),_.push(`Recovered,${E.recovered}`),_.push(`Still Lapsed,${E.still_lapsed}`),_.push(`Recovery Rate,${E.recovery_rate.toFixed(1)}%`),_.push("")}if(f.data?.current_year?.length&&(_.push(`Member Growth - ${f.data.current_year_label}`),_.push("Month,Total,New Joins,Departures,Net Change"),f.data.current_year.forEach(E=>_.push(`${E.month},${E.total},${E.new_joins},${E.departures},${E.net_change}`)),_.push("")),f.data?.previous_year?.length&&(_.push(`Member Growth - ${f.data.previous_year_label}`),_.push("Month,Total,New Joins,Departures,Net Change"),f.data.previous_year.forEach(E=>_.push(`${E.month},${E.total},${E.new_joins},${E.departures},${E.net_change}`)),_.push("")),b.data&&b.data.total_invoice_count>0&&(_.push("Accounts Receivable Aging"),_.push("Bucket,Count,Amount"),b.data.buckets.forEach(E=>_.push(`"${E.label}",${E.count},$${E.total_amount.toFixed(2)}`)),_.push(`Total,${b.data.total_invoice_count},$${b.data.total_outstanding.toFixed(2)}`),_.push("")),_.length===0)return;const y=_.join(` 4`),C=new Blob([y],{type:"text/csv"}),P=URL.createObjectURL(C),A=document.createElement("a");A.href=P,A.download=`reports-${c.start}
4-to-${c.end}.csv`,A.click(),URL.revokeObjectURL(P)},S=d.data||u.data||h.data||p.data;return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col gap-3 print:hidden sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(Sa,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:"Reports"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Membership and revenue analytics"})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(g,{variant:"outline",onClick:()=>window.print(),disabled:!S,children:[e.jsx(ni,{className:"mr-2 h-4 w-4"}),"Print"]}),e.jsxs(g,{variant:"outline",onClick:k,disabled:!S,children:[e.jsx(vs,{className:"mr-2 h-4 w-4"}),"Export CSV"]})]})]}),e.jsx(L,{className:"min-w-0 overflow-hidden print:hidden",children:e.jsx($,{className:"pt-6",children:e.jsxs("div",{className:"flex flex-wrap items-end gap-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(T,{children:"Date range"}),e.jsxs(qe,{value:a,onValueChange:_=>i(_),children:[e.jsx(Le,{className:"w-[180px]",children:e.jsx(Ie,{})}),e.jsxs($e,{children:[e.jsx(q,{value:"this_month",children:"This month"}),e.jsx(q,{value:"last_month",children:"Last month"}),e.jsx(q,{value:"this_quarter",children:"This quarter"}),e.jsx(q,{value:"ytd",children:"Year to date"}),e.jsx(q,{value:"last_year",children:"Last year"}),e.jsx(q,{value:"custom",children:"Custom range"})]})]})]}),a==="custom"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(T,{children:"Start"}),e.jsx(O,{type:"date",value:n,onChange:_=>l(_.target.value),className:"w-[160px]"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(T,{children:"End"}),e.jsx(O,{type:"date",value:r,onChange:_=>m(_.target.value),className:"w-[160px]"})]})]}),e.jsxs("div",{className:"flex items-center gap-1 text-sm text-muted-foreground",children:[e.jsx(Yt,{className:"h-4 w-4"}),c.start," to ",c.end]})]})})}),e.jsx(A1,{revenue:d.data,membership:u.data,dashboard:x.data,isLoading:d.isLoading||u.isLoading||x.isLoading}),e.jsxs("div",{className:"grid grid-cols-1 gap-6 lg:grid-cols-2",children:[e.jsx(T1,{data:d.data,isLoading:d.isLoading}),e.jsx(R1,{data:u.data,isLoading:u.isLoading})]}),e.jsx(Cg,{}),v&&d.data&&e.jsx(L1,{data:d.data}),e.jsx($1,{}),e.jsxs("div",{className:"grid grid-cols-1 gap-6 lg:grid-cols-2",children:[e.jsx(M1,{data:h.data,isLoading:h.isLoading}),e.jsx(D1,{data:p.data,isLoading:p.isLoading})]})]})}function P1({current:t,previous:s}){if(s===0||t===s)return null;const a=t-s,n=(a/s*100).toFixed(1),r=a>0;return e.jsxs("div",{className:`flex items-center gap-0.5 text-xs font-medium ${r?"text-emerald-600 dark:text-emerald-400":"text-red-600 dark:text-red-400"}`,children:[r?e.jsx(zs,{className:"h-3 w-3"}):e.jsx(Hn,{className:"h-3 w-3"}),e.jsxs("span",{children:[r?"+":"",n,"% YoY"]})]})}function A1({revenue:t,membership:s,dashboard:a,isLoading:n}){const r=a?.yoy,i=[{title:"Total revenue",value:t?`$${t.total_revenue.toLocaleString(void 0,{minimumFractionDigits:2})}`:"$0",icon:Ua,color:"text-emerald-600",bgColor:"bg-emerald-100 dark:bg-emerald-950",current:t?.total_revenue??0,previous:0},{title:"Payments",value:t?.payment_count?.toLocaleString()??"0",icon:Qt,color:"text-blue-600",bgColor:"bg-blue-100 dark:bg-blue-950",current:0,previous:0},{title:"Avg payment",value:t?`$${Math.round(t.average_payment).toLocaleString()}`:"$0",icon:zs,color:"text-purple-600",bgColor:"bg-purple-100 dark:bg-purple-950",current:0,previous:0},{title:"New members (YTD)",value:s?.new_this_year?.toLocaleString()??"0",icon:fa,color:"text-amber-600",bgColor:"bg-amber-100 dark:bg-amber-950",current:s?.total_members??0,previous:r?.total_members_prev??0}];return n?e.jsx("div",{className:"grid grid-cols-2 gap-4 xl:grid-cols-4",children:[...Array(4)].map((l,m)=>e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsxs(ne,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Y,{className:"h-4 w-24"}),e.jsx(Y,{className:"h-8 w-8 rounded-full"})]}),e.jsx($,{children:e.jsx(Y,{className:"h-8 w-20"})})]},m))}):e.jsx("div",{className:"grid grid-cols-2 gap-4 xl:grid-cols-4",children:i.map(l=>e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsxs(ne,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(ie,{className:"text-sm font-medium text-muted-foreground",children:l.title}),e.jsx("div",{className:`rounded-full p-2 ${l.bgColor}`,children:e.jsx(l.icon,{className:`h-4 w-4 ${l.color}`})})]}),e.jsxs($,{children:[e.jsx("div",{className:"text-2xl font-semibold tracking-tight",children:l.value}),e.jsx(P1,{current:l.current,previous:l.previous})]})]}
4,l.title))})}function E1({active:t,payload:s,label:a,onUpdate:n}){if(t&&s?.length){const r={month:a,revenue:s[0].value};queueMicrotask(()=>n(r))}return null}function T1({data:t,isLoading:s}){const[a,n]=o.useState(null),r=o.useRef(null),i=o.useCallback(d=>{d&&d.month!==r.current&&(r.current=d.month,n(d))},[]),l=o.useCallback(()=>{r.current=null,n(null)},[]),m=t?.by_month?.map(d=>({month:d.month,revenue:d.revenue}))||[],c=m.reduce((d,u)=>d+u.revenue,0);return e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs("div",{className:"flex items-baseline justify-between gap-3",children:[e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(Sa,{className:"h-4 w-4"})}),"Revenue trend"]}),e.jsx("p",{className:"text-sm",children:a?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"font-normal text-muted-foreground",children:a.month})," ",e.jsx("span",{className:"font-medium text-emerald-600 dark:text-emerald-400",children:a.revenue.toLocaleString("en-US",{style:"currency",currency:"USD"})})]}):e.jsxs("span",{className:"text-muted-foreground",children:["Total:"," ",c.toLocaleString("en-US",{style:"currency",currency:"USD"})]})})]})}),e.jsx($,{children:s?e.jsx(Y,{className:"h-[300px] w-full"}):m.length===0?e.jsx("div",{className:"flex h-[300px] items-center justify-center text-muted-foreground",children:"No revenue data for this period."}):e.jsx("div",{className:"h-[300px] w-full",onMouseLeave:l,children:e.jsx(nn,{width:"100%",height:"100%",children:e.jsxs(mi,{data:m,margin:{top:10,right:10,left:0,bottom:0},children:[e.jsx(Yl,{strokeDasharray:"3 3",vertical:!1,stroke:"hsl(var(--border))"}),e.jsx(_n,{dataKey:"month",fontSize:12,tick:{fill:"hsl(var(--muted-foreground))"},stroke:"hsl(var(--border))"}),e.jsx(rn,{fontSize:12,tickFormatter:d=>`$${d.toLocaleString()}`,tick:{fill:"hsl(var(--muted-foreground))"},stroke:"hsl(var(--border))"}),e.jsx(ln,{content:e.jsx(E1,{onUpdate:i}),cursor:{fill:"hsl(var(--muted-foreground) / 0.08)"},isAnimationActive:!1}),e.jsx(Nr,{dataKey:"revenue",fill:"#10b981",radius:[4,4,0,0]})]})})})})]})}function F1({active:t,payload:s,onUpdate:a}){if(t&&s?.length){const n=s[0],r={name:n.name,value:n.value,color:n.payload?.fill??""};queueMicrotask(()=>a(r))}return null}function R1({data:t,isLoading:s}){const[a,n]=o.useState(null),r=o.useRef(null),i=o.useCallback(u=>{u&&u.name!==r.current&&(r.current=u.name,n(u))},[]),l=o.useCallback(()=>{r.current=null,n(null)},[]),m=t?.by_type?Object.entries(t.by_type).map(([u,h])=>({name:u,value:h})):[],c=t?.total_members??0,d=a?(a.value/c*100).toFixed(1):null;return e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsxs(ne,{className:"pb-3",children:[e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(_p,{className:"h-4 w-4"})}),"Membership breakdown"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Current roster only â non-terminal statuses on real member types (members without a type appear as âNo membership typeâ). The dashboardâs membership overview also counts cancelled/suspended/archived, so its per-type numbers differ."})]}),e.jsx($,{children:s?e.jsx(Y,{className:"h-[300px] w-full"}):m.length===0?e.jsx("div",{className:"flex h-[300px] items-center justify-center text-muted-foreground",children:"No membership data available."}):e.jsxs("div",{className:"flex flex-col items-center gap-4 sm:flex-row",children:[e.jsxs("div",{className:"flex flex-shrink-0 flex-col items-center",children:[e.jsx("div",{className:"h-[220px] w-[220px] sm:h-[260px] sm:w-[260px]",onMouseLeave:l,children:e.jsx(nn,{width:"100%",height:"100%",children:e.jsxs(ij,{children:[e.jsx(lj,{data:m,cx:"50%",cy:"50%",innerRadius:50,outerRadius:90,paddingAngle:2,dataKey:"value",activeShape:u=>{const{cx:h,cy:p,innerRadius:x,outerRadius:f,startAngle:b,endAngle:N,fill:j}=u;return e.jsx("g",{children:e.jsx(cj,{cx:h,cy:p,innerRadius:x,outerRadius:f+6,startAngle:b,endAngle:N,fill:j,style:{filter:"brightness(1.1)"}})})},children:m.map((u,h)=>e.jsx(oj,{fill:Bi[h%Bi.length],style:{cursor:"pointer"}},h))}),e.jsx(ln,{content:e.jsx(F1,{onUpdate:i}),cursor:!1,isAnimationActive:!1})]})})}),e.jsx("div",{className:"h-6 text-center text-sm",children:a?e.jsxs("span",{children:[e.jsx("span",{className:"mr-1.5 inline-block h-2.5 w-2.5 rounded-full align-middle",style:{backgroundColor:a.color}}),e.jsx("span",{className:"font-medium",children:a.name}),e.jsxs("span",{className:"text-muted-foreground",children:[" ","â ",a.value.toLocaleStr
4ing()," (",d,"%)"]})]}):e.jsxs("span",{className:"text-muted-foreground",children:["Roster: ",c.toLocaleString()," members"]})})]}),e.jsxs("div",{className:"w-full min-w-0 flex-1 space-y-2 sm:w-auto",children:[m.map((u,h)=>e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx("div",{className:"h-3 w-3 flex-shrink-0 rounded-full",style:{backgroundColor:Bi[h%Bi.length]}}),e.jsx("span",{className:"truncate",children:u.name})]}),e.jsx("span",{className:"ml-2 font-medium",children:u.value.toLocaleString()})]},u.name)),e.jsxs("div",{className:"mt-2 space-y-1 border-t pt-2",children:[e.jsx($r,{children:e.jsxs(fs,{children:[e.jsx(ys,{asChild:!0,children:e.jsxs("div",{className:"flex cursor-default justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground underline decoration-dotted underline-offset-4",children:"Active (incl. grace + lapsed)"}),e.jsx("span",{className:"font-medium text-emerald-600 dark:text-emerald-400",children:((t?.active_members??0)+(t?.grace_members??0)+(t?.lapsed_members??0)).toLocaleString()})]})}),e.jsxs(hs,{side:"left",className:"space-y-0.5 text-xs",children:[e.jsxs("div",{className:"flex justify-between gap-4",children:[e.jsx("span",{children:"Active"}),e.jsx("span",{className:"font-medium",children:t?.active_members?.toLocaleString()})]}),(t?.grace_members??0)>0&&e.jsxs("div",{className:"flex justify-between gap-4",children:[e.jsx("span",{children:"Grace"}),e.jsx("span",{className:"font-medium",children:t?.grace_members?.toLocaleString()})]}),(t?.lapsed_members??0)>0&&e.jsxs("div",{className:"flex justify-between gap-4",children:[e.jsx("span",{children:"Lapsed"}),e.jsx("span",{className:"font-medium",children:t?.lapsed_members?.toLocaleString()})]})]})]})}),e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Pending"}),e.jsx("span",{className:"font-medium text-amber-600 dark:text-amber-400",children:t?.pending_members?.toLocaleString()})]}),e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Expired"}),e.jsx("span",{className:"font-medium text-red-600 dark:text-red-400",children:t?.expired_members?.toLocaleString()})]}),e.jsxs("div",{className:"flex justify-between border-t pt-1.5 text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Roster total"}),e.jsx("span",{className:"font-medium",children:c.toLocaleString()})]})]})]})]})})]})}function M1({data:t,isLoading:s}){const a=o.useMemo(()=>{const n=t?.cohorts?.slice(1).filter(i=>i.started>0)??[];if(n.length<2)return null;const r=n[0].rate-n[1].rate;return{delta:r,isPositive:r>0}},[t?.cohorts]);return e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(St,{className:"h-4 w-4"})}),"Retention metrics"]})}),e.jsx($,{children:s?e.jsx(Y,{className:"h-[200px] w-full"}):t?e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs("div",{className:"text-center",children:[e.jsxs("p",{className:"text-2xl font-semibold tracking-tight text-emerald-600 dark:text-emerald-400",children:[Math.min(t.renewal_rate,100).toFixed(1),"%"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Renewal rate"}),a&&e.jsxs("div",{className:`mt-1 flex items-center justify-center gap-0.5 text-xs font-medium ${a.isPositive?"text-emerald-600 dark:text-emerald-400":"text-red-600 dark:text-red-400"}`,children:[a.isPositive?e.jsx(zs,{className:"h-3 w-3"}):e.jsx(Hn,{className:"h-3 w-3"}),e.jsxs("span",{children:[a.isPositive?"+":"",a.delta.toFixed(1),"pp"]})]})]}),e.jsxs("div",{className:"text-center",children:[e.jsxs("p",{className:"text-2xl font-semibold tracking-tight text-blue-600 dar
4k:text-blue-400",children:[Math.min(t.retention_rate,100).toFixed(1),"%"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Retention rate"})]}),e.jsxs("div",{className:"text-center",children:[e.jsxs("p",{className:"text-2xl font-semibold tracking-tight text-red-600 dark:text-red-400",children:[Math.min(t.churn_rate,100).toFixed(1),"%"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Churn rate"})]})]}),t.cohorts&&t.cohorts.length>0&&e.jsxs("div",{children:[e.jsx("h4",{className:"mb-2 text-sm font-medium",children:"Cohort retention"}),e.jsx("div",{className:"overflow-hidden rounded-md border",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-muted/30",children:e.jsxs("tr",{className:"hover:bg-transparent",children:[e.jsx("th",{className:"h-10 px-3 text-left text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Period"}),e.jsx("th",{className:"h-10 px-3 text-right text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Started"}),e.jsx("th",{className:"h-10 px-3 text-right text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Retained"}),e.jsx("th",{className:"h-10 px-3 text-right text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Rate"})]})}),e.jsx("tbody",{children:t.cohorts.map(n=>e.jsxs("tr",{className:"border-t hover:bg-brand-navy/[0.04] dark:hover:bg-brand-navy/10",children:[e.jsx("td",{className:"px-3 py-2",children:n.period}),e.jsx("td",{className:"px-3 py-2 text-right",children:n.started}),e.jsx("td",{className:"px-3 py-2 text-right",children:n.retained}),e.jsx("td",{className:"px-3 py-2 text-right",children:n.started===0?e.jsx("span",{className:"text-muted-foreground",children:"â"}):e.jsxs("span",{className:n.rate>=70?"text-emerald-600 dark:text-emerald-400":n.rate>=50?"text-amber-600 dark:text-amber-400":"text-red-600 dark:text-red-400",children:[Math.min(n.rate,100).toFixed(0),"%"]})})]},n.period))})]})})]})]}):e.jsx("div",{className:"flex h-[200px] items-center justify-center text-muted-foreground",children:"No retention data available."})})]})}function D1({data:t,isLoading:s}){const[a,n]=o.useState(30),r=[{days:7,count:t?.next_7_days??0,auto:t?.next_7_days_auto_renew??0,chip:"bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400",dot:"bg-red-500",ring:"ring-red-500/70"},{days:30,count:t?.next_30_days??0,auto:t?.next_30_days_auto_renew??0,chip:"bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400",dot:"bg-amber-500",ring:"ring-amber-500/70"},{days:90,count:t?.next_90_days??0,auto:t?.next_90_days_auto_renew??0,chip:"bg-muted text-muted-foreground",dot:"bg-muted-foreground/60",ring:"ring-muted-foreground/50"}],i=r.find(c=>c.days===a)?.count??0,l=(t?.expiring_members??[]).slice(0,i),m=20;return e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(ea,{className:"h-4 w-4"})}),"Expiring soon"]})}),e.jsx($,{children:s?e.jsx(Y,{className:"h-[200px] w-full"}):t?e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"flex flex-wrap gap-2",children:e.jsx($r,{children:r.map(c=>e.jsxs(fs,{children:[e.jsx(ys,{asChild:!0,children:e.jsxs("button",{type:"button","aria-pressed":a===c.days,onClick:()=>n(c.days),className:`inline-flex cursor-pointer items-center gap-1.5 rounded-full px-2.5 py-1 text-[11px] font-medium transition-shadow ${c.chip} ${a===c.days?`ring-2 ring-offset-1 ring-offset-card ${c.ring}`:"hover:ring-1 hover:ring-border"}`,children:[e.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${c.dot}`,"aria-hidden":"true"}),c.days," days: ",c.count,c.auto>0&&e.jsxs("span",{className:"opacity-75",children:["(",c.auto," auto)"]})]})}),c.auto>0&&e.jsxs(hs,{children:[c.auto," will auto-renew"]})]},c.days))})}),l.length>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"max-h-[250px] overflow-hidden overflow-y-auto rounded-md border",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"sticky top-0 bg-muted/30 backdrop-blur-sm",children:e.jsxs("tr",{className:"hover:bg-transparent",children:[e.jsx("th",{className:"h-10 px-3 text-left text-[11px] font-semibold uppercase tracking-wider text-muted-foreground
4/80",children:"Member"}),e.jsx("th",{className:"h-10 px-3 text-left text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Type"}),e.jsx("th",{className:"h-10 px-3 text-right text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Expires"}),e.jsx("th",{className:"h-10 px-3 text-center text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Auto-renew"})]})}),e.jsx("tbody",{children:l.slice(0,m).map(c=>{const d=Math.ceil((Ps(c.expires).getTime()-Date.now())/864e5);return e.jsxs("tr",{className:"border-t hover:bg-brand-navy/[0.04] dark:hover:bg-brand-navy/10",children:[e.jsx("td",{className:"px-3 py-2",children:e.jsx(je,{to:`/members/${c.id}`,className:"text-blue-600 hover:underline dark:text-blue-400",children:c.name})}),e.jsx("td",{className:"px-3 py-2 text-muted-foreground",children:c.type||"â"}),e.jsx("td",{className:"px-3 py-2 text-right",children:e.jsx("span",{className:d<=7?"font-medium text-red-600 dark:text-red-400":d<=30?"text-amber-600 dark:text-amber-400":"",children:c.expires})}),e.jsx("td",{className:"px-3 py-2 text-center",children:c.auto_renew?e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-emerald-500","aria-hidden":"true"}),e.jsx("span",{className:"text-xs font-medium text-foreground/85",children:"Yes"})]}):e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-muted-foreground/60","aria-hidden":"true"}),e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"No"})]})})]},c.id)})})]})}),i>m&&e.jsxs(je,{to:`/members?expiring_within_days=${a}`,className:"flex items-center gap-1 text-sm text-blue-600 hover:underline dark:text-blue-400",children:["View all ",i.toLocaleString()," expiring within ",a," days",e.jsx(Rs,{className:"h-3 w-3"})]})]}):e.jsxs("p",{className:"text-sm text-muted-foreground",children:["No members expiring in the next ",a," days."]})]}):e.jsx("div",{className:"flex h-[200px] items-center justify-center text-muted-foreground",children:"No expiration data available."})})]})}const Om=["initial","renewal","auto_renewal","upgrade","manual"];function L1({data:t}){const s=t.by_payment_type;if(!s||Object.keys(s).length===0)return null;const a=Om.reduce((p,x)=>p+(s[x]?.revenue??0),0),n=Om.reduce((p,x)=>p+(s[x]?.count??0),0),r=s.event?.revenue??0,i=s.event?.count??0,l=s.product?.revenue??0,m=s.product?.count??0,c=s.donation?.revenue??0,d=s.donation?.count??0;if(r===0&&l===0&&c===0)return null;const u=[{label:"Dues",revenue:a,count:n,color:"bg-blue-500"},{label:"Events",revenue:r,count:i,color:"bg-purple-500"},{label:"Products",revenue:l,count:m,color:"bg-emerald-500"},{label:"Donations",revenue:c,count:d,color:"bg-amber-500"}].filter(p=>p.revenue>0),h=u.reduce((p,x)=>p+x.revenue,0);return e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(gi,{className:"h-4 w-4"})}),"Revenue by category"]})}),e.jsxs($,{children:[e.jsx("div",{className:"mb-4 flex h-4 overflow-hidden rounded-full",children:u.map(p=>e.jsx("div",{className:`${p.color} transition-all`,style:{width:`${p.revenue/h*100}%`}},p.label))}),e.jsx("div",{className:"grid grid-cols-2 gap-4 sm:grid-cols-4",children:u.map(p=>e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:`h-3 w-3 rounded-full ${p.color}`}),e.jsx("span",{className:"text-sm font-medium",children:p.label})]}),e.jsxs("p",{className:"text-2xl font-semibold tracking-tight",children:["$",p.revenue.toLocaleString(void 0,{minimumFractionDigits:2,maximumFractionDigits:2})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[p.count," payment",p.count!==1?"s":""," (",(p.revenue/h*100).toFixed(0),"%)"]})]},p.label))})]})]})}const Um=["bg-emerald-500","bg-amber-500","bg-orange-500","bg-red-500","bg-red-700"];function $1(){const{data:t,isLoading:s}=Yx();if(s)return e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy
4/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(rm,{className:"h-4 w-4"})}),"Accounts receivable aging"]})}),e.jsx($,{children:e.jsx(Y,{className:"h-[200px] w-full"})})]});if(!t||t.total_invoice_count===0)return null;const a=Number(t.total_outstanding),n=t.overdue_invoices.length>0;return e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(rm,{className:"h-4 w-4"})}),"Accounts receivable aging"]}),e.jsxs("div",{className:"text-right",children:[e.jsxs("p",{className:"text-2xl font-semibold tracking-tight",children:["$",a.toLocaleString(void 0,{minimumFractionDigits:2,maximumFractionDigits:2})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[t.total_invoice_count," outstanding invoice",t.total_invoice_count!==1?"s":""]})]})]})}),e.jsx($,{children:e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"flex h-6 overflow-hidden rounded-full",children:t.buckets.map((r,i)=>{const l=a>0?Number(r.total_amount)/a*100:0;return l===0?null:e.jsx($r,{children:e.jsxs(fs,{children:[e.jsx(ys,{asChild:!0,children:e.jsx("div",{className:`${Um[i]} cursor-default transition-all`,style:{width:`${l}%`}})}),e.jsxs(hs,{children:[r.label,": ",r.count," invoices ($",Number(r.total_amount).toLocaleString(void 0,{minimumFractionDigits:2}),")"]})]})},r.label)})}),e.jsx("div",{className:"grid grid-cols-2 gap-3 sm:grid-cols-5",children:t.buckets.map((r,i)=>e.jsxs("div",{className:"text-center",children:[e.jsxs("div",{className:"mb-1 flex items-center justify-center gap-1.5",children:[e.jsx("div",{className:`h-2.5 w-2.5 rounded-full ${Um[i]}`}),e.jsx("span",{className:"text-xs font-medium",children:r.label})]}),e.jsxs("p",{className:"text-sm font-semibold tracking-tight",children:["$",Number(r.total_amount).toLocaleString(void 0,{minimumFractionDigits:0,maximumFractionDigits:0})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[r.count," invoice",r.count!==1?"s":""]})]},r.label))}),n&&e.jsxs("div",{children:[e.jsx("h4",{className:"mb-2 text-sm font-medium",children:"Most overdue"}),e.jsx("div",{className:"max-h-[200px] overflow-hidden overflow-y-auto rounded-md border",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"sticky top-0 bg-muted/30 backdrop-blur-sm",children:e.jsxs("tr",{className:"hover:bg-transparent",children:[e.jsx("th",{className:"h-10 px-3 text-left text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Invoice"}),e.jsx("th",{className:"h-10 px-3 text-left text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Member"}),e.jsx("th",{className:"h-10 px-3 text-right text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Amount"}),e.jsx("th",{className:"h-10 px-3 text-right text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Days overdue"})]})}),e.jsx("tbody",{children:t.overdue_invoices.slice(0,10).map(r=>e.jsxs("tr",{className:"border-t hover:bg-brand-navy/[0.04] dark:hover:bg-brand-navy/10",children:[e.jsx("td",{className:"px-3 py-2",children:e.jsx(je,{to:"/invoices",className:"text-blue-600 hover:underline dark:text-blue-400",children:r.invoice_number})}),e.jsx("td",{className:"px-3 py-2 text-muted-foreground",children:r.member_name}),e.jsxs("td",{className:"px-3 py-2 text-right font-medium",children:["$",r.amount.toLocaleString(void 0,{minimumFractionDigits:2})]}),e.jsx("td",{className:"px-3 py-2 text-right",children:e.jsx("span",{className:r.days_overdue>90?"font-medium text-red-600 dark:text-red-400":r.days_overdue>30?"text-amber-600 dark:text-amber-400":"",children:r.days_overdue})})]},r.id))})]})})]})]})})]})}function of({user:t}){const{resend:s,revoke:a,reset:n}=R0();return t.invitation?e.jsxs(e.Fragment,{children:[e.jsxs(wt,{disabled:s.isPending,onClick:()=>s.mutate(t.id),children:[e.jsx(qb,{className:"mr-2 h-4 w-4","aria-hidden":"true"}),"Resend invitation"]}),t.invitation.state!=="revoked"&&e.jsxs(wt,{disabled:a.isPending,onClick:()=>a.mutate(t.id),children:[e.jsx(Sp,{className:"mr-2 h-4 w-4","aria-hidden":"true"}),"Revoke invitation"]})]}):t.is_active?e.jsxs(wt,{disabled:n.isPending,onClick:()=>n.mutate(t.id),children:[e.jsx(An,{className:"mr-2 h-4 w-4","aria-hidden":"true"}),"Send reset link"]}):null}function q1(t){const s=t.invitation;if(s){const a=s.delivery==="failed"?"Email not delivered":void 0;if(s.state==="pending"){const n=s.expires_at?Yp(Ct(s.expires_at)):null;return{label:n?`Invited · expires in ${n}`:"Invited",dot:"bg-sky-500",note:a}}
4return s.state==="expired"?{label:"Invitation expired",dot:"bg-amber-500",note:a}:{label:"Invitation revoked",dot:"bg-muted-foreground/60"}}return t.is_active?{label:"Active",dot:"bg-emerald-500"}:{label:"Inactive",dot:"bg-muted-foreground/60"}}function cf({user:t}){const s=q1(t);return e.jsxs("span",{className:"inline-flex flex-col gap-0.5",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5 whitespace-nowrap",children:[e.jsx("span",{className:me("h-1.5 w-1.5 shrink-0 rounded-full",s.dot),"aria-hidden":"true"}),e.jsx("span",{className:"text-xs font-medium",children:s.label})]}),s.note&&e.jsx("span",{className:"text-xs text-destructive",children:s.note})]})}const Ea={super_admin:"Super admin",society_admin:"Society admin",society_staff:"Staff"},I1={super_admin:"Everything, on every society: the platform, society settings and users, and each workspace.",society_admin:"Runs one society: members, events, payments, emails and settings, and invites its admins and staff.",society_staff:"Works in one societyâs workspace (members, events, orders) but canât manage users or society settings."},O1={super_admin:{label:Ea.super_admin,dot:"bg-red-500"},society_admin:{label:Ea.society_admin,dot:"bg-muted-foreground/60"},society_staff:{label:Ea.society_staff,dot:"bg-muted-foreground/60"}};function U1({users:t,onEdit:s}){return e.jsxs(Pt,{children:[e.jsx(At,{children:e.jsxs(Ue,{children:[e.jsx(H,{children:"Name"}),e.jsx(H,{children:"Email"}),e.jsx(H,{children:"Role"}),e.jsx(H,{children:"Status"}),e.jsx(H,{children:"Last Login"}),e.jsx(H,{className:"w-[100px]"})]})}),e.jsx(Et,{children:t.map(a=>{const n=O1[a.role]||{label:a.role,dot:"bg-muted-foreground/60"};return e.jsxs(Ue,{children:[e.jsxs(G,{className:"font-medium",children:[a.first_name," ",a.last_name]}),e.jsx(G,{children:a.email}),e.jsx(G,{children:e.jsxs("span",{className:"inline-flex items-center gap-1.5 whitespace-nowrap",children:[e.jsx("span",{className:`h-1.5 w-1.5 shrink-0 rounded-full ${n.dot}`}),e.jsx("span",{className:"text-xs font-medium",children:n.label})]})}),e.jsx(G,{children:e.jsx(cf,{user:a})}),e.jsx(G,{children:a.last_login_at?Be(Ct(a.last_login_at),"MMM d, yyyy h:mm a"):"â"}),e.jsx(G,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsxs(g,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>s(a),children:[e.jsx(Hs,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Edit"})]}),(a.invitation||a.is_active)&&e.jsxs(Ws,{children:[e.jsx(Vs,{asChild:!0,children:e.jsx(g,{variant:"ghost",size:"icon",className:"h-7 w-7","aria-label":`Access for ${a.first_name} ${a.last_name}`,children:e.jsx(An,{className:"h-4 w-4","aria-hidden":"true"})})}),e.jsx($s,{align:"end",children:e.jsx(of,{user:a})})]})]})})]},a.id)})})]})}function df({search:t,onSearchChange:s,role:a,onRoleChange:n}){const r=o.useId(),i=o.useId();return e.jsxs("div",{className:"flex flex-col gap-4 sm:flex-row sm:items-center",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(ya,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground","aria-hidden":"true"}),e.jsx(O,{placeholder:"Search usersâ¦","aria-label":"Search users",maxLength:200,value:t,onChange:l=>s(l.target.value),className:"pl-9"})]}),e.jsx("span",{id:r,className:"sr-only",children:"Role"}),e.jsxs(qe,{value:a,onValueChange:n,children:[e.jsx(Le,{id:i,"aria-labelledby":`${r} ${i}`,className:"w-full sm:w-[180px]",children:e.jsx(Ie,{placeholder:"All roles"})}),e.jsxs($e,{children:[e.jsx(q,{value:"all",children:"All roles"}),e.jsx(q,{value:"super_admin",children:"Super admin"}),e.jsx(q,{value:"society_admin",children:"Society admin"}),e.jsx(q,{value:"society_staff",children:"Staff"})]})]})]})}function mf({open:t,onOpenChange:s,onSubmit:a,isPending:n,error:r,mode:i,currentSocietyId:l,societies:m=[],initial:c}){const d=c?.role??"society_staff",u=c?.society_id??null,h=o.useMemo(()=>({email:"",first_name:"",last_name:"",role:d,society_id:u}),[d,u]),{register:p,handleSubmit:x,control:f,reset:b,watch:N,formState:{errors:j}}=Fr({defaultValues:h});o.useEffect(()=>{t||b(h)},[t,b,h]);const w=N("role"),v=i==="platform"&&w!=="super_admin",k=S=>{let _;i==="tenant"?_=l??null:S.role==="super_admin"?_=null:_=S.society_id??null,a({...S,society_id:_})};return e.jsx(Fe,{open:t,onOpenChange:s,children:e.jsxs(Te,{children:[e.jsxs(Ae,{children:[e.jsx(Ee,{children:"Invite user"}),e.jsx(tt,{children:"Theyâll get an email to choose their own password. The link works once and expires in 7 days."})]}),e.jsxs("form",{onSubmit:x(k),className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"add-first-name",children:"First name *"}),e.jsx(O,{id:"add-first-name",...p("first_name",{required:"First name is required"})}),j.first_name&&e.jsx("p",{className:"text-sm text-destructive",children:j.first_name.message})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"add-last-name",children:"Last name *"}),e.jsx(O,{id:"add-last-name",...p("last_name",{required:"Last name is required"})}),j.last_name&&e.jsx("p",{className:"text-sm text-destructive",children:j.last_name.message})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"add-email",children:"Email *"}),e.jsx(O,{id:"add-email",type:"email",autoComplete:"email",...p("email",{required:"Email is required",pattern:{value:/^[^\s@]+@[^\s@]+\.[^\s@]+$/,message:"Invalid email address"}})}),j.email&&e.jsx("p",{className:"text-sm text-destructive",children:j.email.message})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"add-role",children:"Role *"}),e.jsx(qa,{name:"role",control:f,rules:{required:"Role is required"},render:({field:S})=>e.jsxs(qe,{value:S.value,onValueChange:_=>_&&S.onChange(_),children:[e.jsx(Le,{id:"add-role","aria-describedby":"add-role-help",children:e.jsx(Ie,{placeholder:"Select role"})}),e.jsxs($e,{children:[i==="platform"&&e.jsx(q,{value:"super_admin",children:Ea.super_admin}),e.jsx(q,{value:"society_admin",children:Ea.society_admin}),e.jsx(q,{value:"society_staff",children:Ea.society_staff})]})]})}),w&&e.jsx("p",{id:"add-role-help",className:"text-sm text-muted-foreground",children:I1[w]}),j.role&&e.jsx("p",{className:"text-sm text-destructive",children:j.role.message})]}),v&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"add-society",children:"Society *"}),e.jsx(qa,{name:"society_id",control:f,rules:{validate:S=>v&&!S?"Society is required for this role":!0},render:({field:S})=>e.jsxs(qe,{value:S.value??"",onValueChange:_=>S.onChange(_||null),children:[e.jsx(Le,{id:"add-society",children:e.jsx(Ie,{placeholder:"Select society"})}),e.jsx($e,{children:m.map(_=>e.jsx(q,{value:_.id,children:_.name},_.id))})]})}),j.society_id&&e.jsx("p",{className:"text-sm text-destructive",children:j.society_id.message})]}),r&&e.jsx("p",{className:"text-sm text-destructive",children:r}),e.jsxs(Ge,{children:[e.jsx(g,{type:"button",variant:"outline",onClick:()=>s(!1),disabled:n,children:"Cancel"}),e.jsx(g,{type:"submit",disabled:n,children:n?"Sendingâ¦":"Send invitation"})]})]})]})})}function uf({user:t,open:s,onOpenChange:a,onSubmit:n,isPending:r,error:i,mode:l,societies:m=[]}){const{register:c,handleSubmit:d,reset:u,watch:h,setValue:p,control:x,formState:{errors:f}}=Fr({defaultValues:{email:"",first_name:"",last_name:"",role:"society_staff",society_id:"",is_active:"true"}});o.useEffect(()=>{t&&u({email:t.email,first_name:t.first_name,last_name:t.last_name,role:t.role,society_id:t.society_id??"",is_active:t.is_active?"true":"false"})},[t,u]);const b=h("role"),N=l==="platform"&&b!=="super_admin",j=w=>{if(!t)return;const v={email:w.email,first_name:w.first_name,last_name:w.last_name,role:w.role,is_active:w.is_active==="true"};l==="platform"&&(w.role==="super_admin"?v.society_id=null:v.society_id=w.society_id||null),n(t.id,v)};return e.jsx(Fe,{open:s,onOpenChange:a,children:e.jsxs(Te,{children:[e.jsxs(Ae,{children:[e.jsx(Ee,{children:"Edit user"}),e.jsx(tt,{children:"Update user account details."})]}),e.jsxs("form",{onSubmit:d(j),className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"edit-first-name",children:"First name *"}),e.jsx(O,{id:"edit-first-name",...c("first_name",{required:"First name is required"})}),f.first_name&&e.jsx("p",{className:"text-sm text-destructive",children:f.first_name.message})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"edit-last-name",children:"Last name *"}),e.jsx(O,{id:"edit-last-name",...c("last_name",{required:"Last name is required"})}),f.last_name&&e.jsx("p",{className:"text-sm text-destructive",children:f.last_name.message})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"edit-email",children:"Email *"}),e.jsx(O,{id:"edit-email",type:"email",autoComplete:"email",...c("email",{required:"Email is required",pattern:{value:/^[^\s@]+@[^\s@]+\.[^\s@]+$/,message:"Invalid email address"}})}),f.email&&e.jsx("p",{className:"text-sm text-destructive",children:f.email.message})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"edit-role",children:"Role"}),e.jsxs(qe,{value:h("role"),onValueChange:w=>w&&p("role",w),children:[e.jsx(Le,{id:"edit-role",children:e.jsx(Ie,{})}),e.jsxs($e,{children:[l==="platform"&&e.jsx(q,{value:"super_admin",children:"Super admin"}),e.jsx(q,{value:"society_admin",children:"Society admin"}),e.jsx(q,{value:"society_staff",children:"Staff"})]})]})]}),N&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"edit-society",children:"Society *"}),e.jsx(qa,{name:"society_id",control:x,rules:{validate:w=>N&&!w?"Society is required for this role":!0},render:({field:w})=>e.jsxs(qe,{value:w.value||"",onValueChange:v=>v&&w.onChange(v),children:[e.jsx(Le,{id:"edit-society",children:e.jsx(Ie,{placeholder:"Select society"})}),e.jsx($e,{children:m.map(v=>e.jsx(q,{value:v.id,children:v.name},v.id))})]})}),f.society_id&&e.jsx("p",{className:"text-sm text-destructive",children:f.society_id.message})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"edit-is-active",children:"Active status"}),e.jsxs(qe,{value:h("is_active"),onValueChange:w=>w&&p("is_active",w),children:[e.jsx(Le,{id:"edit-is-active",children:e.jsx(Ie,{})}),e.jsxs($e,{children:[e.jsx(q,{value:"true",children:"Active"}),e.jsx(q,{value:"false",children:"Inactive"})]})]})]}),i&&e.jsx("p",{className:"text-sm text-destructive",children:i}),e.jsxs(Ge,{children:[e.jsx(g,{type:"button",variant:"outline",onClick:()=>a(!1),disabled:r,children:"Cancel"}),e.jsx(g,{type:"submit",disabled:r,children:r?"Savingâ¦":"Save changes"})]})]})]})})}function hf(t,s=300){const a=t.trim(),[n,r]=o.useState(a);return o.useEffect(()=>{if(!a)return;const i=setTimeout(()=>r(a),s);return()=>clearTimeout(i)},[a,s]),!a&&n&&r(""),a?n:""}function pf(){const[t,s]=o.useState(1),[a,n]=o.useState(""),r=hf(a),[i,l]=o.useState(r);return i!==r&&(l(r),s(1)),{page:t,setPage:s,search:a,setSearch:n,appliedSearch:r,clampPage:c=>{c>0&&t>c&&s(c)}}}function Ms(t,s=""){const[a,n]=o.useState({key:s,error:null}),[r,i]=o.useState({key:s,active:!1}),l=t.isPlaceholderData?void 0:t.data;let m=a.key===s?a.error:null;a.key!==s?n({key:s,error:null}
4):l===void 0&&t.error&&t.error!==a.error?(m=t.error,n({key:s,error:t.error})):l!==void 0&&a.error&&(m=null,n({key:s,error:null}));const c=r.key===s&&r.active;r.key!==s&&i({key:s,active:!1});const d=t.fetchStatus==="paused",u=c||t.isFetching&&(l===void 0?m!=null:t.isError),h=t.error??m;let p;return l!==void 0?p="ready":d&&!t.isError?p="offline":t.isError||u?p="failed":t.data!==void 0?p="ready":p="loading",{state:p,data:t.data,readyData:p==="ready"&&l!==void 0?l:void 0,stale:l!==void 0&&(t.isError||d),staleReason:l===void 0?null:t.isError?"failed":d?"offline":null,updating:l===void 0&&t.data!==void 0&&p==="ready",error:h,retrying:u,retry:()=>{i({key:s,active:!0}),t.refetch().finally(()=>i(x=>x.key===s?{...x,active:!1}:x))},updatedAt:t.dataUpdatedAt}}function ja({title:t,error:s,onRetry:a,isRetrying:n,notFound:r,children:i}){const l=s?.response?.status;return r&&(l===404||l===422)?e.jsxs("div",{role:"alert",className:"flex flex-col items-center gap-3 px-6 py-10 text-center text-sm sm:py-12",children:[e.jsx(Dt,{className:"h-8 w-8 text-muted-foreground","aria-hidden":"true"}),e.jsx("p",{className:"font-medium text-foreground",children:l===404?r:"This link isnât valid."})]}):e.jsxs("div",{role:"alert",className:"flex flex-col items-center gap-3 px-6 py-10 text-center text-sm sm:py-12",children:[e.jsx(Dt,{className:"h-8 w-8 text-destructive","aria-hidden":"true"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-foreground",children:t}),e.jsx("p",{className:"mt-1 text-muted-foreground",children:vx(Xn(s,"Something went wrong on the server."))})]}),e.jsxs(g,{variant:"outline",onClick:a,disabled:n,children:[e.jsx(St,{className:`mr-2 h-4 w-4 ${n?"animate-spin":""}`}),n?"Trying againâ¦":"Try again"]}),i]})}function Ma({view:t,what:s}){if(!t.stale)return null;const{updatedAt:a,retry:n,retrying:r}=t,i=t.staleReason==="offline";return e.jsxs("div",{role:"status",className:"flex flex-col gap-2 rounded-lg border border-amber-500/40 bg-amber-50 px-4 py-3 text-sm text-amber-900 dark:bg-amber-950/30 dark:text-amber-200 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("p",{className:"flex items-start gap-2",children:[e.jsx(Dt,{className:"mt-0.5 h-4 w-4 shrink-0","aria-hidden":"true"}),e.jsxs("span",{children:[i?"Youâre offline":`Couldnât refresh ${s}`,". Showing what was loaded"," ",nd(a)?`at ${Be(a,"h:mm a")}`:`on ${Be(a,"MMM d")} at ${Be(a,"h:mm a")}`,"."]})]}),!i&&e.jsx(g,{size:"sm",variant:"outline",onClick:n,disabled:r,children:r?"Trying againâ¦":"Try again"})]})}function tn({title:t,description:s,action:a}){return e.jsxs("div",{className:"flex flex-col items-center gap-3 px-6 py-10 text-center text-sm sm:py-12",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-foreground",children:t}),s&&e.jsx("p",{className:"mt-1 text-muted-foreground",children:s})]}),a]})}function Wa({title:t}){return e.jsxs("div",{role:"status",className:"flex flex-col items-center gap-3 px-6 py-10 text-center text-sm sm:py-12",children:[e.jsx(Ib,{className:"h-8 w-8 text-muted-foreground","aria-hidden":"true"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-foreground",children:t}),e.jsx("p",{className:"mt-1 text-muted-foreground",children:"You appear to be offline. This will load when the connection returns."})]})]})}function zm(t){const s=t,a=s?.response?.data?.detail;return typeof a=="string"&&a.trim()?a:Array.isArray(a)&&a[0]?.msg?String(a[0].msg):s?.message||"An error occurred"}function z1(){const{user:t,selectedSocietyId:s}=V(),{page:a,setPage:n,search:r,setSearch:i,appliedSearch:l,clampPage:m}=pf(),[c,d]=o.useState("all"),[u,h]=o.useState(!1),[p,x]=o.useState(null),[f,b]=o.useState(""),N=o.useMemo(()=>({page:a,size:20,search:l||void 0,role:c!=="all"?c:void 0}),[a,l,c]),j=Ms(F0(N),JSON.stringify({society:s,...N})),w=j.data,v=Hx(),k=M0(),S=async P=>{try{b(""),await v.mutateAsync(P),h(!1)}catch(A){b(zm(A))}},_=async(P,A)=>{try{b(""),await k.mutateAsync({id:P,data:A}),x(null)}catch(E){b(zm(E))}},y=l||c!=="all";j.state==="ready"&&!j.updating&&w&&m(w.pages);const C=j.state==="ready"&&!j.updating&&!!w&&w.items.length===0;return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-brand-navy
4/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(Lt,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:"Users"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Manage admin user accounts"})]})]}),e.jsxs(g,{onClick:()=>h(!0),children:[e.jsx(Rt,{className:"mr-2 h-4 w-4"}),"Invite user"]})]}),e.jsx(df,{search:r,onSearchChange:P=>{i(P)},role:c,onRoleChange:P=>{d(P),n(1)}}),e.jsx(Ma,{view:j,what:"users"}),j.updating&&e.jsx("p",{role:"status",className:"text-sm text-muted-foreground",children:"Updating resultsâ¦"}),e.jsx(L,{className:"min-w-0 overflow-hidden",children:e.jsx($,{className:"p-0",children:j.state==="offline"?e.jsx(Wa,{title:"Users canât be loaded right now."}):j.state==="failed"?e.jsx(ja,{title:"Users couldnât be loaded.",error:j.error,onRetry:j.retry,isRetrying:j.retrying,children:a>1&&e.jsx(g,{variant:"ghost",onClick:()=>n(1),children:"Back to the first page"})}):j.state==="loading"||j.updating&&!w?.items?.length?e.jsx("div",{className:"space-y-3 p-6",children:Array.from({length:5}).map((P,A)=>e.jsx(Y,{className:"h-12 w-full"},A))}):C?e.jsx("div",{className:"py-12 text-center",children:e.jsx("p",{className:"text-muted-foreground",children:y?"No users match your filters.":"No users yet."})}):e.jsx("div",{"aria-busy":j.updating,inert:j.updating,className:j.updating?"opacity-60 transition-opacity":void 0,children:e.jsx(U1,{users:w?.items||[],onEdit:x})})})}),j.state==="ready"&&w&&w.pages>1&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:!j.updating&&e.jsxs(e.Fragment,{children:["Showing ",(a-1)*20+1," to ",Math.min(a*20,w.total)," of ",w.total," ","users"]})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(g,{variant:"outline",size:"sm",onClick:()=>n(a-1),disabled:a===1||j.updating,children:[e.jsx(Gs,{className:"h-4 w-4"}),"Previous"]}),e.jsxs("span",{className:"text-sm",children:["Page ",a," of ",w.pages]}),e.jsxs(g,{variant:"outline",size:"sm",onClick:()=>n(a+1),disabled:a===w.pages||j.updating,children:["Next",e.jsx(ts,{className:"h-4 w-4"})]})]})]}),e.jsx(mf,{open:u,onOpenChange:P=>{h(P),P||b("")},onSubmit:S,isPending:v.isPending,error:f,mode:"tenant",currentSocietyId:s??t?.society_id??null}),e.jsx(uf,{user:p,open:!!p,onOpenChange:P=>{P||(x(null),b(""))},onSubmit:_,isPending:k.isPending,error:f,mode:"tenant"})]})}const B1=["Membership lifecycle","Renewals","Payments & billing","Sign-in & security","Support"],K1={welcome:"Membership lifecycle",pending_approval_member:"Membership lifecycle",pending_approval_admin:"Membership lifecycle",application_approved:"Membership lifecycle",application_rejected:"Membership lifecycle",membership_expired:"Membership lifecycle",fellowship_expiring:"Membership lifecycle",membership_offer_welcome:"Membership lifecycle",faculty_welcome:"Membership lifecycle",renewal_reminder:"Renewals",renewal_final:"Renewals",renewal_sequence:"Renewals",renewal_confirmation:"Renewals",payment_receipt:"Payments & billing",invoice:"Payments & billing",payment_method_missing:"Payments & billing",payment_method_missing_reminder:"Payments & billing",payment_failed_1:"Payments & billing",payment_failed_2:"Payments & billing",payment_failed_3:"Payments & billing",payment_reminder:"Payments & billing",order_confirmation:"Payments & billing",refund_notification:"Payments & billing",dues_comp_notice:"Payments & billing",password_reset:"Sign-in & security",magic_link:"Sign-in & security",portal_access:"Sign-in & security",member_link_verification:"Sign-in & security",support_reply:"Support"},Sc="Other";function Q1(t){return K1[t??""]??Sc}const xf={welcome:"Welcome",payment_receipt:"Payment receipt",renewal_reminder:"Renewal reminder",renewal_final:"Final renewal",membership_expired:"Membership expired",fellowship_expiring:"Fellowship expiring",password_reset:"Password reset",pending_approval_member:"Pending (member)",pending_approval_admin:"Pending (admin)",application_approved:"Approved",application_rejected:"Rejected",payment_method_missing:"Payment method needed",payment_method_missing_reminder:"Payment method reminder",payment_failed_1:"Payment failed â 1st notice",payment_failed_2:"Payment failed â 2nd notice",payment_failed_3:"Payment failed â final notice",payment_reminder:"Payment reminder",invoice:"Invoice",refund_notification:"Refund notification",order_confirmation:"Order confirmation",renew
4al_confirmation:"Renewal confirmation",renewal_sequence:"Renewal sequence",magic_link:"Magic link sign-in",portal_access:"Portal access",member_link_verification:"Account link verification",membership_offer_welcome:"Membership offer welcome",support_reply:"Support reply",dues_comp_notice:"Dues comp notice",faculty_welcome:"Faculty welcome",custom:"Custom"};function W1(t){const s=t.filter(i=>i.template_type==="custom"),a=new Map;for(const i of t){if(i.template_type==="custom")continue;const l=Q1(i.template_type),m=a.get(l)??[];m.push(i),a.set(l,m)}const n=[];for(const i of B1){const l=a.get(i);l?.length&&n.push({category:i,templates:l})}const r=a.get(Sc);return r?.length&&n.push({category:Sc,templates:r}),{custom:s,sections:n}}const V1={welcome:"bg-emerald-500",payment_receipt:"bg-orange-500",renewal_reminder:"bg-amber-500",renewal_final:"bg-amber-500",membership_expired:"bg-muted-foreground/60",fellowship_expiring:"bg-muted-foreground/60",password_reset:"bg-muted-foreground/60",pending_approval_member:"bg-amber-500",pending_approval_admin:"bg-amber-500",application_approved:"bg-emerald-500",application_rejected:"bg-red-500",payment_failed:"bg-red-500",payment_method_missing:"bg-amber-500",payment_method_missing_reminder:"bg-amber-500",order_confirmation:"bg-emerald-500",renewal_confirmation:"bg-emerald-500",dues_comp_notice:"bg-emerald-500",faculty_welcome:"bg-emerald-500",custom:"bg-muted-foreground/60"};function G1({type:t}){const s=V1[t]||"bg-muted-foreground/60",a=xf[t]||t;return e.jsxs("span",{className:"inline-flex items-center gap-1.5 whitespace-nowrap",children:[e.jsx("span",{className:`h-1.5 w-1.5 shrink-0 rounded-full ${s}`}),e.jsx("span",{className:"text-xs font-medium",children:a})]})}function Bm({templates:t,onToggleActive:s,onDelete:a}){return e.jsxs(Pt,{children:[e.jsx(At,{children:e.jsxs(Ue,{children:[e.jsx(H,{children:"Name"}),e.jsx(H,{children:"Type"}),e.jsx(H,{children:"Subject"}),e.jsx(H,{children:"Active"}),e.jsx(H,{className:"w-[80px]"})]})}),e.jsx(Et,{children:t.map(n=>e.jsxs(Ue,{children:[e.jsx(G,{children:e.jsx(je,{to:`/emails/templates/${n.id}`,className:"font-medium hover:underline",children:n.name})}),e.jsx(G,{children:e.jsx(G1,{type:n.template_type})}),e.jsx(G,{className:"max-w-[300px] truncate",children:n.subject}),e.jsx(G,{children:e.jsxs("button",{onClick:()=>s(n),className:"inline-flex cursor-pointer items-center gap-1.5 whitespace-nowrap",children:[e.jsx("span",{className:`h-1.5 w-1.5 shrink-0 rounded-full ${n.is_active?"bg-emerald-500":"bg-muted-foreground/60"}`}),e.jsx("span",{className:"text-xs font-medium",children:n.is_active?"Active":"Inactive"})]})}),e.jsx(G,{children:e.jsxs(Ws,{children:[e.jsx(Vs,{asChild:!0,children:e.jsxs(g,{variant:"ghost",size:"icon",className:"h-7 w-7",children:[e.jsx(Pn,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Open menu"})]})}),e.jsxs($s,{align:"end",children:[e.jsx(wt,{asChild:!0,children:e.jsxs(je,{to:`/emails/templates/${n.id}`,children:[e.jsx(Hs,{className:"mr-2 h-4 w-4"}),"Edit"]})}),e.jsxs(wt,{className:"text-destructive",onClick:()=>a(n),children:[e.jsx(Ft,{className:"mr-2 h-4 w-4"}),"Delete"]})]})]})})]},n.id))})]})}function Y1({templateType:t,onInsert:s,extraVariables:a}){const{data:n,isLoading:r}=L0(t);if(r)return e.jsxs("div",{className:"space-y-2",children:[e.jsx(Y,{className:"h-6 w-32"}),e.jsx(Y,{className:"h-6 w-24"}),e.jsx(Y,{className:"h-6 w-28"})]});const i=[...new Set([...n?.variables??[],...a??[]])];return i.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No variables available for this template type."}):e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium",children:"Available Variables"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Click to insert at cursor position"}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:i.map(l=>e.jsx("button",{type:"button",onClick:()=>s(l),className:"inline-flex items-center rounded-md border bg-muted px-2 py-1 font-mono text-xs transition-colors hover:bg-accent",children:`{{${l}}}`},l))})]})}function H1({html:t}){return e.jsx("div",{className:"rounded-lg border bg-white",children:e.jsx("iframe",{srcDoc:t,sandbox:"",title:"Email Preview",className:"min-h-[400px] w-full rounded-lg",style:{border:"none"}})})}function J1({templateId:t,open:s,onOpenChange:a}){const[n,r]=o.useState(""),[i,l]=o.useState(null),m=I0(),c=async()=>
4{l(null);try{const d=await m.mutateAsync({template_id:t,to_email:n});d.status==="sent"||d.status==="pending"?l({type:"success",message:`Test email sent! (${d.status})`}):l({type:"error",message:d.error||`Status: ${d.status}`})}catch{l({type:"error",message:"Failed to send test email."})}};return e.jsx(Fe,{open:s,onOpenChange:d=>{d||(l(null),r("")),a(d)},children:e.jsxs(Te,{children:[e.jsxs(Ae,{children:[e.jsx(Ee,{children:"Send Test Email"}),e.jsx(tt,{children:"Send a test version of this template to an email address."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"test-email",children:"Recipient email"}),e.jsx(O,{id:"test-email",type:"email",placeholder:"[email protected]",value:n,onChange:d=>r(d.target.value)})]}),i&&e.jsx("p",{className:`text-sm ${i.type==="success"?"text-green-600":"text-destructive"}`,children:i.message})]}),e.jsxs(Ge,{children:[e.jsx(g,{variant:"outline",onClick:()=>a(!1),disabled:m.isPending,children:"Cancel"}),e.jsx(g,{onClick:c,disabled:!n||m.isPending,children:m.isPending?"Sending...":"Send Test"})]})]})})}function Z1({template:t,open:s,onOpenChange:a,onConfirm:n,isDeleting:r}){return e.jsx(Fe,{open:s,onOpenChange:a,children:e.jsxs(Te,{children:[e.jsxs(Ae,{children:[e.jsx(Ee,{children:"Delete Template"}),e.jsxs(tt,{children:["Are you sure you want to delete ",e.jsx("strong",{children:t?.name}),"? This action cannot be undone."]})]}),e.jsxs(Ge,{children:[e.jsx(g,{variant:"outline",onClick:()=>a(!1),disabled:r,children:"Cancel"}),e.jsx(g,{variant:"destructive",onClick:n,disabled:r,children:r?"Deleting...":"Delete"})]})]})})}const X1={pending:"bg-orange-500",sent:"bg-muted-foreground/60",delivered:"bg-emerald-500",failed:"bg-red-500",bounced:"bg-amber-500",complained:"bg-amber-500"},eC={pending:"Pending",sent:"Sent",delivered:"Delivered",failed:"Failed",bounced:"Bounced",complained:"Complained"},tC={welcome:"bg-emerald-500",renewal_reminder:"bg-amber-500",renew
4al_final:"bg-amber-500",payment_receipt:"bg-orange-500",payment_failed:"bg-red-500",payment_method_missing:"bg-amber-500",payment_method_missing_reminder:"bg-amber-500",membership_expired:"bg-muted-foreground/60",fellowship_expiring:"bg-muted-foreground/60",password_reset:"bg-muted-foreground/60",pending_approval_member:"bg-amber-500",pending_approval_admin:"bg-amber-500",application_approved:"bg-emerald-500",application_rejected:"bg-red-500",magic_link:"bg-muted-foreground/60",portal_access:"bg-muted-foreground/60",order_confirmation:"bg-emerald-500",renewal_confirmation:"bg-emerald-500",refund_notification:"bg-orange-500",dues_comp_notice:"bg-emerald-500",faculty_welcome:"bg-emerald-500",custom:"bg-muted-foreground/60"},sC={welcome:"Welcome",renewal_reminder:"Renewal",renewal_final:"Final renewal",payment_receipt:"Receipt",payment_failed:"Failed payment",payment_method_missing:"Payment method needed",payment_method_missing_reminder:"Payment method reminder",membership_expired:"Expired",fellowship_expiring:"Fellowship",password_reset:"Password reset",pending_approval_member:"Pending (member)",pending_approval_admin:"Pending (admin)",application_approved:"Approved",application_rejected:"Rejected",magic_link:"Magic link",portal_access:"Portal access",order_confirmation:"Order confirmation",renewal_confirmation:"Renewal confirmation",refund_notification:"Refund",dues_comp_notice:"Dues comp notice",faculty_welcome:"Faculty welcome",custom:"Custom"};function aC({status:t}){const s=X1[t]||"bg-muted-foreground/60",a=eC[t]||t;return e.jsxs("span",{className:"inline-flex items-center gap-1.5 whitespace-nowrap",children:[e.jsx("span",{className:`h-1.5 w-1.5 shrink-0 rounded-full ${s}`}),e.jsx("span",{className:"text-xs font-medium",children:a})]})}function nC({type:t}){const s=tC[t]||"bg-muted-foreground/60",a=sC[t]||t;return e.jsxs("span",{className:"inline-flex items-center gap-1.5 whitespace-nowrap",children:[e.jsx("span",{className:`h-1.5 w-1.5 shrink-0 rounded-full ${s}`}),e.jsx("span",{className:"text-xs font-medium",children:a})]})}const rC={marketing:"bg-amber-500",operational:"bg-muted-foreground/60"},iC={marketing:"Marketing",operational:"Operational"};function lC({emailClass:t}){const s=rC[t]||"bg-muted-foreground/60",a=iC[t]||t;return e.jsxs("span",{className:"inline-flex items-center gap-1.5 whitespace-nowrap",children:[e.jsx("span",{className:`h-1.5 w-1.5 shrink-0 rounded-full ${s}`}),e.jsx("span",{className:"text-xs font-medium",children:a})]})}function oC({logs:t}){return e.jsxs(Pt,{children:[e.jsx(At,{children:e.jsxs(Ue,{children:[e.jsx(H,{children:"Date"}),e.jsx(H,{children:"Recipient"}),e.jsx(H,{children:"Subject"}),e.jsx(H,{children:"Type"}),e.jsx(H,{children:"Class"}),e.jsx(H,{children:"Status"})]})}),e.jsx(Et,{children:t.map(s=>e.jsxs(Ue,{children:[e.jsx(G,{className:"whitespace-nowrap",children:Be(Ct(s.created_at),"MMM d, yyyy h:mm a")}),e.jsx(G,{children:e.jsxs("div",{children:[s.to_name&&e.jsx("span",{className:"block font-medium",children:s.to_name}),e.jsx("span",{className:"text-sm text-muted-foreground",children:s.to_email})]})}),e.jsx(G,{className:"max-w-[250px] truncate",children:s.subject}),e.jsx(G,{children:s.template_type&&e.jsx(nC,{type:s.template_type})}),e.jsx(G,{children:s.email_class?e.jsx(lC,{emailClass:s.email_class}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"â"})}),e.jsx(G,{children:e.jsx(aC,{status:s.status})})]},s.id))})]})}function cC({status:t,onStatusChange:s,templateType:a,onTemplateTypeChange:n,dateFrom:r,onDateFromChange:i,dateTo:l,onDateToChange:m}){return e.jsxs("div",{className:"flex flex-col gap-4 sm:flex-row sm:items-end",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(T,{className:"text-xs",children:"Status"}),e.jsxs(qe,{value:t,onValueChange:s,children:[e.jsx(Le,{className:"w-full sm:w-[140px]",children:e.jsx(Ie,{placeholder:"All statuses"})}),e.jsxs($e,{children:[e.jsx(q,{value:"all",children:"All statuses"}),e.jsx(q,{value:"pending",children:"Pending"}),e.jsx(q,{value:"sent",children:"Sent"}),e.jsx(q,{value:"delivered",children:"Delivered"}),e.jsx(q,{value:"failed",children:"Failed"}),e.jsx(q,{value:"bounced",children:"Bounced"}),e.jsx(q,{value:"complained",children:"Complained"})]})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(T,{className:"text-xs",children:"Type"}),e.jsxs(qe,{value:a,onValueChange:n,children:[e.jsx(Le,{className:"w-full sm:w-[200px]",children:e.jsx(Ie,{placeholder:"All types"})}),e.jsxs($e,{children:[e.jsx(q,{value:"all",children:"All types"}),e.jsx(q,{value:"welcome",children:"Welcome"}),e.jsx(q,{value:"payment_receipt",children:"Payment Receipt"}),e.jsx(q,{value:"renewal_reminder",children:"Renewal Reminder"}),e.jsx(q,{value:"renewal_final",children:"Final Renewal"}),e.jsx(q,{value:"membership_expired",children:"Membership Expired"}),e.jsx(q,{value:"fellowship_expiring",children:"Fellowship Expiring"}),e.jsx(q,{value:"password_reset",children:"Password Reset"}),e.jsx(q,{value:"pending_approval_member",children:"Pending (Member)"}),e.jsx(q,{value:"pending_approval_admin",children:"Pending (Admin)"}),e.jsx(q,{value:"application_approved",children:"Approved"}),e.jsx(q,{value:"application_rejected",children:"Rejected"}),e.jsx(q,{value:"custom",children:"Custom"})]})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(T,{htmlFor:"email-date-from",className:"text-xs",children:"From"}),e.jsx(O,{id:"email-date-from",name:"email-date-from",type:"date",value:r,onChange:c=>i(c.target.value),className:"w-full sm:w-[150px]",autoComplete:"off"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(T,{htmlFor:"email-date-to",className:"text-xs",children:"To"}),e.jsx(O,{id:"email-date-to",name:"email-date-to",type:"date",value:l,onCh
4ange:c=>m(c.target.value),className:"w-full sm:w-[150px]",autoComplete:"off"})]})]})}function dC({open:t,onOpenChange:s,onConfirm:a,isPending:n}){return e.jsx(Fe,{open:t,onOpenChange:s,children:e.jsxs(Te,{children:[e.jsxs(Ae,{children:[e.jsx(Ee,{children:"Send Renewal Reminders"}),e.jsx(tt,{children:"This will send renewal reminder emails to all members whose memberships are expiring soon, based on your configured reminder templates and trigger days."})]}),e.jsxs(Ge,{children:[e.jsx(g,{variant:"outline",onClick:()=>s(!1),disabled:n,children:"Cancel"}),e.jsx(g,{onClick:a,disabled:n,children:n?"Sending...":"Send Reminders"})]})]})})}function mC(t,s){const[a,n]=o.useState(t);return o.useEffect(()=>{const r=setTimeout(()=>n(t),s);return()=>clearTimeout(r)},[t,s]),a}const uC=[{value:"active",label:"Active"},{value:"pending",label:"Pending"},{value:"lapsed",label:"Lapsed"},{value:"expired",label:"Expired"},{value:"grace",label:"Grace"},{value:"cancelled",label:"Cancelled"},{value:"suspended",label:"Suspended"},{value:"archived",label:"Archived"},{value:"rejected",label:"Rejected"}];function hC({onSubmit:t,onCancel:s,initialValues:a,isEditing:n}){const{selectedSocietyId:r}=V(),{data:i}=tr(r??void 0),{data:l}=sr(r??void 0),{data:m}=oa(),c=!!i?.mailchimp_connected,d=!!l?.mailerlite_connected,[u,h]=o.useState(a?.name??""),[p,x]=o.useState(a?.platform??""),[f,b]=o.useState(a?.destination_id??""),[N,j]=o.useState(!1),[w,v]=o.useState(""),[k,S]=o.useState(a?.filters?.statuses??[]),[_,y]=o.useState(a?.filters?.membership_type_ids??[]),[C,P]=o.useState(a?.filters?.tags?.join(", ")??"");o.useEffect(()=>{p||(c&&!d?x("mailchimp"):d&&!c&&x("mailerlite"))},[c,d,p]);const A=p||null,{data:E,isLoading:Q}=Zg(A),U=o.useMemo(()=>({statuses:k.length>0?k:void 0,membership_type_ids:_.length>0?_:void 0,tags:C.trim()?C.split(",").map(se=>se.trim()).filter(Boolean):void 0}),[k,_,C]),D=mC(U,500),K=!!(D.statuses?.length||D.membership_type_ids?.length||D.tags?.length),{data:xe,isFetching:z}=_S(D,K),ae=se=>{S(le=>le.includes(se)?le.filter(oe=>oe!==se):[...le,se])},ue=se=>{y(le=>le.includes(se)?le.filter(oe=>oe!==se):[...le,se])},_e=se=>{if(se.preventDefault(),!u.trim()||!p)return;const le={name:u.trim(),platform:p,filters:U};if(N&&w.trim())le.create_new_group=!0,le.new_group_name=w.trim();else if(f){le.destination_id=f;const oe=E?.find(Pe=>Pe.id===f);oe&&(le.destination_name=oe.name)}t(le)},ee=u.trim()&&p&&(f||N&&w.trim());return e.jsxs(L,{children:[e.jsx(ne,{children:e.jsx(ie,{children:n?"Edit Sync Rule":"Create Sync Rule"})}),e.jsx($,{children:e.jsxs("form",{onSubmit:_e,className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"rule-name",children:"Name"}),e.jsx(O,{id:"rule-name",placeholder:"e.g. Active Members to Newsletter",value:u,onChange:se=>h(se.target.value),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"rule-platform",children:"Platform"}),e.jsxs(qe,{value:p,onValueChange:se=>{x(se),b(""),j(!1),v("")},children:[e.jsx(Le,{id:"rule-platform",children:e.jsx(Ie,{placeholder:"Select platform"})}),e.jsxs($e,{children:[c&&e.jsx(q,{value:"mailchimp",children:"Mailchimp"}),d&&e.jsx(q,{value:"mailerlite",children:"MailerLite"})]})]})]}),p&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(T,{htmlFor:"rule-destination",children:["Destination ",p==="mailchimp"?"(Interest/Group)":"(Group)"]}),Q?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(He,{className:"h-4 w-4 animate-spin"}),"Loading destinations..."]}):e.jsxs(e.Fragment,{children:[e.jsxs(qe,{value:N?"__create_new__":f,onValueChange:se=>{se==="__create_new__"?(j(!0),b("")):(j(!1),b(se),v(""))},children:[e.jsx(Le,{id:"rule-destination",children:e.jsx(Ie,{placeholder:"Select destination"})}),e.jsxs($e,{children:[E?.map(se=>e.jsx(q,{value:se.id,children:se.name},se.id)),e.jsx(q,{value:"__create_new__",children:"+ Create new"})]})]}),N&&e.jsx(O,{placeholder:"New group name",value:w,onChange:se=>v(se.target.value),className:"mt-2"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{children:"Status filters"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Only sync members with these statuses. Leave empty to include all."}),e.jsx("div",{className:"mt-1 flex flex-wrap gap-3",children:uC.map(se=>e.jsxs("label",{className:"flex cursor-pointer items-center gap-1.5 text-sm",children:[e.jsx(ot,{checked:k.includes(se.value),onCheckedChange:()=>ae(se.value)}),se.label]},se.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{children:"Membership type filter"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Only sync members of these types. Leave empty to include all."}),m&&m.length>0?e.jsx("div",{className:"mt-1 flex flex-wrap gap-3",children:m.map(se=>e.jsxs("label",{className:"flex cursor-pointer items-center gap-1.5 text-sm",children:[e.jsx(ot,{checked:_.includes(se.id),onCheckedChange:()=>ue(se.id)}),se.name]},se.id))}):e.jsx("p",{className:"text-sm italic text-muted-foreground",children:"No membership types defined."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"rule-tags",children:"Tags filter"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Comma-separated tags. Only sync members with at least one of these tags. Leave empty to include all."}),e.jsx(O,{id:"rule-tags",placeholder:"e.g. board, committee, vip",value:C,onChange:se=>P(se.target.value)})]}),K&&e.jsx("div",{className:"rounded-md border px-4 py-3 text-sm",children:z?e.jsxs("span",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(He,{className:"h-4 w-4 animate-spin"}),"Counting matching members..."]}):xe?e.jsxs("span",{children:[e.jsx(Ts,{variant:"secondary",className:"mr-2",children:xe.count}),xe.count===1?"member matches":"members match"," these filters"]}):null}),e.jsxs("div",{className:"flex items-center gap-3 pt-2",children:[e.jsx(g,{type:"submit",disabled:!ee,children:n?"Save Changes":"Create Rule"}),e.jsx(g,{type:"button",variant:"outline",onClick:s,children:"Cancel"})]})]})})]})}const pC=[{label:"Overview",to:"/emails",end:!0},{label:"Templates",to:"/emails/templates"},{label:"Campaigns",to:"/emails/campaigns"},{label:"Renewals",to:"/emails/renewals"},{label:"Logs",to:"/emails/logs"},{label:"Suppressions",to:"/emails/suppressions"},{label:"Sync rules",to:"/emails/sync-rules"},{label:"Sending",to:"/emails/sending"}];function Tn(){return e.jsx("div",{className:"border-b border-border mb-6 overflow-x-auto",children:e.jsx("nav",{className:"flex gap-1",children:pC.map(t=>e.jsx(_a,{to:t.to,end:t.end,className:({isActive:s})=>me("whitespace-nowrap px-4 py-2.5 text-sm border-b-2 -mb-px transition-colors",s?"border-primary text-primary font-medium":"border-transparent text-muted-foreground hover:text-foreground"),children:t.label},t.to))})})}
4const xC={pass:"bg-green-500",info:"bg-muted-foreground/60",warn:"bg-amber-500",fail:"bg-red-500"},gC={ses_identity:"Domain verified in SES",dkim:"DKIM signing",dkim_alignment:"DKIM alignment (DMARC)",dmarc:"DMARC policy",spf_alignment:"SPF alignment",one_click:"One-click unsubscribe"};function fC({societyId:t}){const{data:s,isLoading:a,isError:n,refresh:r,isRefreshing:i}=Xx(t);return a?e.jsx(Y,{className:"h-64 w-full"}):n||!s?e.jsxs(L,{children:[e.jsx(ne,{children:e.jsx(ie,{className:"text-sm font-semibold",children:"Sending domain health"})}),e.jsxs($,{className:"flex flex-col items-start gap-3",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Couldn't check domain health. The check may have timed out or the service may be temporarily unavailable."}),e.jsxs(g,{variant:"outline",size:"sm",onClick:r,disabled:i,children:[e.jsx(St,{className:me("h-3.5 w-3.5 mr-1.5",i&&"animate-spin")}),"Retry"]})]})]}):e.jsxs(L,{children:[e.jsxs(ne,{className:"flex flex-row items-center justify-between space-y-0",children:[e.jsxs("div",{children:[e.jsxs(ie,{className:"text-sm font-semibold",children:["Sending domain health â ",s.domain||"no domain configured"]}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Checked ",Ct(s.checked_at).toLocaleString()]})]}),e.jsxs(g,{variant:"outline",size:"sm",onClick:r,disabled:i,children:[e.jsx(St,{className:me("h-3.5 w-3.5 mr-1.5",i&&"animate-spin")}),"Re-check"]})]}),e.jsx($,{className:"divide-y divide-border",children:s.checks.map(l=>e.jsx(yC,{check:l},l.key))})]})}function yC({check:t}){const[s,a]=o.useState(!1);return e.jsxs("div",{className:"py-2.5 flex items-start gap-2.5",children:[e.jsx("span",{className:me("mt-1.5 h-2 w-2 rounded-full shrink-0",xC[t.status])}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("p",{className:"text-sm",children:[e.jsx("span",{className:"font-medium",children:gC[t.key]??t.key}),e.jsxs("span",{className:"text-muted-foreground",children:[" · ",t.summary]})]}),t.fix&&e.jsxs("div",{className:"mt-2 rounded-md border border-amber-200 bg-amber-50 dark:border-amber-900 dark:bg-amber-950/40 p-2.5 text-xs",children:[e.jsx("p",{className:"text-amber-800 dark:text-amber-300 mb-1.5",children:"Add this DNS record at your domain registrar:"}),e.jsxs("div",{className:"flex items-center justify-between gap-2 rounded bg-zinc-900 px-2 py-1.5 font-mono text-[11px] text-zinc-200 overflow-x-auto",children:[e.jsxs("span",{children:[t.fix.record_name," ",t.fix.record_type," ",t.fix.record_value]}
4),e.jsx(g,{variant:"ghost",size:"sm","aria-label":"Copy DNS record",className:"h-6 px-1.5 text-blue-300 hover:text-blue-200",onClick:()=>{navigator.clipboard.writeText(`${t.fix.record_name} ${t.fix.record_type} ${t.fix.record_value}`),a(!0),setTimeout(()=>a(!1),1500)},children:s?e.jsx(Xt,{className:"h-3 w-3"}):e.jsx(za,{className:"h-3 w-3"})})]})]})]})]})}function gf({societyId:t,linkTo:s}){const{data:a,isError:n}=Xx(t);let r;if(n)r=e.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1.5 whitespace-nowrap rounded-full border border-border bg-muted px-2.5 py-1 text-xs font-medium text-muted-foreground",children:[e.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-muted-foreground/60"}),"Domain health: unavailable"]});else if(a){const i=a.checks.filter(m=>m.status==="warn"||m.status==="fail").length,l=a.checks.some(m=>m.status==="fail");i===0?r=e.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1.5 whitespace-nowrap rounded-full border border-green-200 bg-green-50 px-2.5 py-1 text-xs font-medium text-green-800 dark:border-green-900 dark:bg-green-950/40 dark:text-green-400",children:[e.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-green-500"}),"Domain health: all clear"]}):r=e.jsxs("span",{className:l?"inline-flex shrink-0 items-center gap-1.5 whitespace-nowrap rounded-full border border-red-200 bg-red-50 px-2.5 py-1 text-xs font-medium text-red-800 dark:border-red-900 dark:bg-red-950/40 dark:text-red-400":"inline-flex shrink-0 items-center gap-1.5 whitespace-nowrap rounded-full border border-amber-200 bg-amber-50 px-2.5 py-1 text-xs font-medium text-amber-800 dark:border-amber-900 dark:bg-amber-950/40 dark:text-amber-300",children:[e.jsx("span",{className:`h-1.5 w-1.5 shrink-0 rounded-full ${l?"bg-red-500":"bg-amber-500"}`}),"Domain health: ",i," issue",i===1?"":"s"]})}else return null;return s?e.jsx(je,{to:s,className:"transition-opacity hover:opacity-80",children:r}):r}const bC={ses:"Amazon SES",smtp:"Custom SMTP"};function jC({societyId:t}){const{data:s,isLoading:a}=Or(t);return e.jsxs(L,{children:[e.jsxs(ne,{className:"pb-3",children:[e.jsx(ie,{className:"text-sm font-semibold",children:"Sending identity"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Managed on the Sending tab"})]}),e.jsx($,{className:"space-y-0 divide-y divide-border",children:a?e.jsx(Y,{className:"h-16 w-full"}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 py-2 text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"From"}),e.jsx("span",{className:"min-w-0 truncate text-right font-medium",children:s?.from_address?s.from_name?`${s.from_name} <${s.from_address}>`:s.from_address:"Not configured"})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2 py-2 text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Reply-to"}),e.jsx("span",{className:"min-w-0 truncate text-right font-medium",children:s?.reply_to_email||"â"})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2 py-2 text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Provider"}),e.jsx("span",{className:"font-medium",children:s?.provider?bC[s.provider]??s.provider:"None"})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2 py-2 text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Status"}),e.jsxs("span",{className:"inline-flex items-center gap-1.5 font-medium",children:[e.jsx("span",{className:`h-1.5 w-1.5 shrink-0 rounded-full ${s?.connected?"bg-green-500":"bg-muted-foreground/60"}`}),s?.connected?"Connected":"Not connected"]})]})]})})]})}function vC(){const{data:t,isLoading:s}=G0();if(s)return e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(Y,{className:"h-20 w-full"}),e.jsx(Y,{className:"h-20 w-full"}),e.jsx(Y,{className:"h-20 w-full"}),e.jsx(Y,{className:"h-20 w-full"})]});const n=[{label:`Sent · last ${t?.window_days??30} days`,value:t?t.sent.toLocaleString():"â"},{label:"Delivered",value:t&&t.sent>0?`${t.delivered_pct}%`:"â",className:t&&t.sent>0?"text-green-600 dark:text-green-400":void 0}
4,{label:"Blocked (suppressed)",value:t?t.blocked.toLocaleString():"â",className:"text-amber-600 dark:text-amber-400"},{label:"Failed",value:t?t.failed.toLocaleString():"â",className:"text-red-600 dark:text-red-400"}];return e.jsx("div",{className:"grid grid-cols-2 gap-3",children:n.map(r=>e.jsx(L,{children:e.jsxs($,{className:"p-3.5",children:[e.jsx("div",{className:`text-xl font-bold ${r.className??""}`,children:r.value}),e.jsx("div",{className:"mt-0.5 text-xs text-muted-foreground",children:r.label})]})},r.label))})}function wC(){const{selectedSocietyId:t}=V();return e.jsxs("div",{className:"space-y-6",children:[e.jsx(Tn,{}),e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx($t,{className:"h-5 w-5"})}),e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:"Email overview"})]}),e.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"Domain health, sending identity, and 30-day activity"})]}),t&&e.jsx(gf,{societyId:t})]}),t?e.jsxs("div",{className:"grid gap-4 lg:grid-cols-[1.4fr_1fr]",children:[e.jsx(fC,{societyId:t}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(jC,{societyId:t}),e.jsx(vC,{})]})]}):e.jsx(L,{children:e.jsx($,{className:"p-6 text-sm text-muted-foreground",children:"Select a society to view its email overview"})})]})}function NC(t){return t>0?`${t} days before`:t===0?"Day of expiry":`${Math.abs(t)} days after`}function kC(){const[t,s]=o.useState(null),[a,n]=o.useState(!1),[r,i]=o.useState(!1),[l,m]=o.useState(!1),[c,d]=o.useState(new Set),[u,h]=o.useState(""),[p,x]=o.useState(new Set),f=oe=>x(Pe=>{const M=new Set(Pe);return M.has(oe)?M.delete(oe):M.add(oe),M}),{data:b,isLoading:N}=Jx(),j=Zx(),w=q0(),{data:v}=U0(),k=z0(),{data:S}=tg(),_=gw(),y=async oe=>{await j.mutateAsync({id:oe.id,data:{is_active:!oe.is_active}})},C=async()=>{t&&(await w.mutateAsync(t.id),s(null))},P=async()=>{await k.mutateAsync(!0)},A=async()=>{await k.mutateAsync(!1),n(!1)},E=()=>{d(new Set),i(!0)},Q=oe=>{d(Pe=>{const M=new Set(Pe);return M.has(oe)?M.delete(oe):M.add(oe),M})},U=()=>{S&&(c.size===S.length?d(new Set):d(new Set(S.map(oe=>oe.id))))},D=()=>{i(!1),m(!0)},K=async()=>{c.size!==0&&(await _.mutateAsync(Array.from(c)),m(!1))},xe=S&&S.length>0,z=!N&&(!b||b.length===0),ae=u.trim().toLowerCase(),ue=oe=>!ae||oe.name?.toLowerCase().includes(ae)||oe.subject?.toLowerCase().includes(ae)||(xf[oe.template_type??""]??oe.template_type??"").toLowerCase().includes(ae),{custom:_e,sections:ee}=W1(b||[]),se=_e.filter(ue),le=ee.map(oe=>({...oe,visible:oe.templates.filter(ue)})).filter(oe=>ae?oe.visible.length>0:!0);return e.jsx(nr,{tourIds:["email-templates"],children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Tn,{}),e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx($t,{className:"h-5 w-5"})}),e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:"Email templates"})]}),e.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"Manage email templates for your society"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("div",{className:"relative sm:w-56",children:[e.jsx(ya,{className:"pointer-events-none absolute left-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(O,{value:u,onChange:oe=>h(oe.target.value),placeholder:"Search templatesâ¦",className:"pl-8 sm:w-56"})]}),xe&&e.jsxs(g,{variant:"outline",onClick:E,children:[e.jsx(fi,{className:"mr-2 h-4 w-4"}),"Restore defaults"]}),v?e.jsxs(g,{variant:"outline",className:"border-emerald-600 text-emerald-700 hover:bg-emerald-50 hover:text-emerald-800 dark:border-emerald-500 dark:text-emerald-400 dark:hover:bg-emerald-950/30",onClick:()=>n(!0),disabled:k.isPending,children:[e.jsx(Cp,{className:"mr-2 h-4 w-4"}),"Resume emails"]}):e.jsxs(g,{variant:"destructive",onClick:P,disabled:k.isPending,children:[e.jsx(im,{className:"mr-2 h-4 w-4"}),k.isPending?"Stoppingâ¦":"Stop all emails"]}),e.jsx(g,{asChild:!0,children:e.jsxs(je,{to:"/emails/templates/new",children:[e.jsx(Rt,{className:"mr-2 h-4 w-4"}),"New template"]})})]})]}),v&&e.jsx("div",{className:"rounded-lg border-2 border-red-500 bg-red-50 p-4 dark:bg-red-950/30",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(im,{className:"h-6 w-6 shrink-0 text-red-600 dark:text-red-400"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-red-800 dark:text-red-300",children:"All email sending is paused"}),e.jsx("p",{className:"mt-0.5 text-sm text-red-700 dark:text-red-400",children:'No emails will be sent â including welcome emails, renewal reminders, payment receipts, invoices, and cron notifications. Click "Resume emails" to re-enable.'})]})]})}),N?e.jsx(L,{className:"min-w-0 overflow-hidden",children:e.jsx($,{className:"p-0",children:e.jsx("div",{className:"space-y-3 p-6",children:Array.from({length:5}).map((oe,Pe)=>e.jsx(Y,{className:"h-12 w-full"},Pe))})})}):z?e.jsx(L,{className:"min-w-0 overflow-hidden",children:e.jsx($,{className:"p-0",children:e.jsxs("div",{className:"py-12 text-center",children:[e.jsx("p",{className:"text-muted-foreground",children:"No email templates yet."}),e.jsx(g,{asChild:!0,className:"mt-4",children:e.jsx(je,{to:"/emails/templates/new",children:"Create your first template"})})]})})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("section",{children:[e.jsx("h2",{className:"mb-2 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground
4/80",children:"Your templates"}),e.jsx(L,{className:"min-w-0 overflow-hidden",children:e.jsx($,{className:"p-0",children:se.length>0?e.jsx(Bm,{templates:se,onToggleActive:y,onDelete:s}):e.jsx("div",{className:"py-8 text-center text-sm text-muted-foreground",children:ae?"No custom templates match your search.":e.jsxs(e.Fragment,{children:["No custom templates yet."," ",e.jsx(je,{to:"/emails/templates/new",className:"text-primary underline-offset-2 hover:underline",children:"Create one"})]})})})})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"mb-2 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"System templates"}),e.jsxs("div",{className:"space-y-2","data-tour":"templates-list",children:[le.map(oe=>{const Pe=ae?!0:p.has(oe.category),M=ae?oe.visible:oe.templates;return e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsxs("div",{className:"flex items-center",children:[e.jsxs("button",{type:"button","aria-expanded":Pe,"aria-disabled":!!ae,onClick:()=>!ae&&f(oe.category),"data-tour":"template-section",className:"flex flex-1 items-center gap-2.5 px-4 py-3 text-left hover:bg-muted/50",children:[e.jsx(ts,{className:me("h-4 w-4 shrink-0 text-muted-foreground transition-transform",Pe&&"rotate-90")}),e.jsx("span",{className:"text-sm font-semibold",children:oe.category}),e.jsx("span",{className:"rounded-full bg-muted px-2 py-0.5 text-xs text-muted-foreground",children:ae?`${oe.visible.length} of ${oe.templates.length} match`:oe.templates.length})]}),oe.category==="Renewals"&&e.jsx(je,{to:"/emails/renewals",className:"mr-4 shrink-0 text-xs text-primary hover:underline",children:"Manage sequence â"})]}),Pe&&M.length>0&&e.jsx($,{className:"border-t p-0",children:e.jsx(Bm,{templates:M,onToggleActive:y,onDelete:s})})]},oe.category)}),ae&&le.length===0&&e.jsx(L,{className:"min-w-0 overflow-hidden",children:e.jsx($,{className:"py-8 text-center text-sm text-muted-foreground",children:"No system templates match your search."})})]})]})]}),e.jsx(Z1,{template:t,open:!!t,onOpenChange:oe=>!oe&&s(null),onConfirm:C,isDeleting:w.isPending}),e.jsx(Fe,{open:a,onOpenChange:n,children:e.jsxs(Te,{children:[e.jsxs(Ae,{children:[e.jsx(Ee,{children:"Resume email sending?"}),e.jsx(tt,{children:"This will re-enable all email sending for your society, including automated cron emails, renewal reminders, and transactional emails."})]}),e.jsxs(Ge,{children:[e.jsx(g,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsx(g,{onClick:A,disabled:k.isPending,children:k.isPending?"Resumingâ¦":"Resume emails"})]})]})}),e.jsx(Fe,{open:r,onOpenChange:i,children:e.jsxs(Te,{children:[e.jsxs(Ae,{children:[e.jsx(Ee,{children:"Restore default templates"}),e.jsx(tt,{children:"Select which renewal sequence templates to reset back to their original content."})]}),e.jsxs("div",{className:"space-y-3 py-4",children:[e.jsxs("div",{className:"flex items-center gap-2 border-b pb-2",children:[e.jsx(ot,{id:"select-all",checked:!!S?.length&&c.size===S.length,onCheckedChange:U}),e.jsx(T,{htmlFor:"select-all",className:"cursor-pointer text-sm font-medium",children:"Select all"})]}),e.jsx("div",{className:"max-h-64 space-y-2 overflow-y-auto",children:S?.map(oe=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ot,{id:`restore-${oe.id}`,checked:c.has(oe.id),onCheckedChange:()=>Q(oe.id)}),e.jsxs(T,{htmlFor:`restore-${oe.id}`,className:"flex-1 cursor-pointer text-sm",children:[oe.template_name||"Unnamed template"," ",e.jsxs("span",{className:"text-muted-foreground",children:["(",NC(oe.days_offset),")"]})]})]},oe.id))})]}),e.jsxs(Ge,{children:[e.jsx(g,{variant:"outline",onClick:()=>i(!1),children:"Cancel"}),e.jsx(g,{variant:"destructive",onClick:D,disabled:c.size===0,children:"Restore selected"})]})]})}),e.jsx(Fe,{open:l,onOpenChange:m,children:e.jsxs(Te,{children:[e.jsxs(Ae,{children:[e.jsx(Ee,{children:"Are you sure?"}),e.jsxs(tt,{children:["This will overwrite the subject and body of ",c.size," ",c.size===1?"template":"templates"," with the original default content. Any edits you have made to"," ",c.size===1?"this template":"these templates"," will be permanently lost."]})]}),e.jsxs(Ge,{children:[e.jsx(g,{variant:"outline",onClick:()=>m(!1),children:"Cancel"}),e.jsx(g,{variant:"destructive",onClick:K,disabled:_.isPending,children:_.isPending?"Restoringâ¦":"Yes, restore defaults"})]})]})})]})})}const _C=Nj.create({name:"templateVariable",group:"inline",inline:!0,atom:!0,selectable:!0,draggable:!1,addOptions(){return{HTMLAttributes:{}}},addAttributes(){return{name:{default:null,parseHTML:t=>t.getAttribute("data-variable"),renderHTML:t=>({"data-variable":t.name})}}},parseHTML(){return[{tag:"span[data-variable]"}]},renderHTML({node:t,HTMLAttributes:s}){return["span",kj(this.options.HTMLAttributes,s,{"data-variable":t.attrs.name,class:"template-variable",contenteditable:"false"}),`{{ ${t.attrs.name} }}`]},addCommands(){return{insertVariable:t=>({commands:s})=>s.insertContent({type:this.name,attrs:{name:t}})}}});function Os({onClick:t,active:s,disabled:a,tooltip:n,children:r}){return e.jsx($r,{delayDuration:300,children:e.jsxs(fs,{children:[e.jsx(ys,{asChild:!0,children:e.jsx("button",{type:"button",onClick:t,disabled:a,className:`rounded p-1.5 transition-colors hover:bg-accent disabled:opacity-40 ${s?"bg-accent text-accent-foreground":"text-muted-foreground"}`,children:r})}),e.jsx(hs,{side:"bottom",className:"text-xs",children:n})]})})}function Yr(){return e.jsx("div",{className:"mx-0.5 h-5 w-px bg-border"})}function Km({editor:t,onToggleSource:s,isSourceMode:a}){const n=()=>
4{if(t.isActive("link")){t.chain().focus().unsetLink().run();return}const i=window.prompt("Enter URL:");i&&t.chain().focus().setLink({href:i}).run()};return e.jsxs("div",{className:"flex flex-wrap items-center gap-0.5 border-b bg-muted/30 px-2 py-1.5",children:[e.jsx(Os,{onClick:()=>t.chain().focus().toggleBold().run(),active:t.isActive("bold"),tooltip:"Bold",children:e.jsx(Pp,{size:16})}),e.jsx(Os,{onClick:()=>t.chain().focus().toggleItalic().run(),active:t.isActive("italic"),tooltip:"Italic",children:e.jsx(Ap,{size:16})}),e.jsx(Os,{onClick:()=>t.chain().focus().toggleUnderline().run(),active:t.isActive("underline"),tooltip:"Underline",children:e.jsx(Ep,{size:16})}),e.jsx(Os,{onClick:()=>t.chain().focus().toggleStrike().run(),active:t.isActive("strike"),tooltip:"Strikethrough",children:e.jsx(Ob,{size:16})}),e.jsx(Yr,{}),e.jsx(Os,{onClick:()=>t.chain().focus().toggleHeading({level:1}).run(),active:t.isActive("heading",{level:1}),tooltip:"Heading 1",children:e.jsx(Tp,{size:16})}),e.jsx(Os,{onClick:()=>t.chain().focus().toggleHeading({level:2}).run(),active:t.isActive("heading",{level:2}),tooltip:"Heading 2",children:e.jsx(Fp,{size:16})}),e.jsx(Os,{onClick:()=>t.chain().focus().toggleHeading({level:3}).run(),active:t.isActive("heading",{level:3}),tooltip:"Heading 3",children:e.jsx(Rp,{size:16})}),e.jsx(Yr,{}),e.jsx(Os,{onClick:n,active:t.isActive("link"),tooltip:"Link",children:e.jsx(Mp,{size:16})}),e.jsx(Yr,{}),e.jsx(Os,{onClick:()=>t.chain().focus().toggleBulletList().run(),active:t.isActive("bulletList"),tooltip:"Bullet List",children:e.jsx(td,{size:16})}),e.jsx(Os,{onClick:()=>t.chain().focus().toggleOrderedList().run(),active:t.isActive("orderedList"),tooltip:"Ordered List",children:e.jsx(Dp,{size:16})}),e.jsx(Yr,{}),e.jsx(Os,{onClick:()=>t.chain().focus().setTextAlign("left").run(),active:t.isActive({textAlign:"left"}),tooltip:"Align Left",children:e.jsx(Lp,{size:16})}),e.jsx(Os,{onClick:()=>t.chain().focus().setTextAlign("center").run(),active:t.isActive({textAlign:"center"}),tooltip:"Align Center",children:e.jsx($p,{size:16})}),e.jsx(Os,{onClick:()=>t.chain().focus().setTextAlign("right").run(),active:t.isActive({textAlign:"right"}),tooltip:"Align Right",children:e.jsx(qp,{size:16})}),e.jsx(Yr,{}),e.jsx(Os,{onClick:()=>t.chain().focus().undo().run(),disabled:!t.can().undo(),tooltip:"Undo",children:e.jsx(Ip,{size:16})}),e.jsx(Os,{onClick:()=>t.chain().focus().redo().run(),disabled:!t.can().redo(),tooltip:"Redo",children:e.jsx(Op,{size:16})}),e.jsx("div",{className:"flex-1"}),e.jsx(Os,{onClick:s,active:a,tooltip:"HTML Source",children:e.jsx(Ub,{size:16})})]})}function Do(t){const s=new DOMParser().parseFromString("<body>"+t+"</body>","text/html"),a=s.createTreeWalker(s.body,NodeFilter.SHOW_TEXT),n=[];for(let r=a.nextNode();r;r=a.nextNode())n.push(r);for(const r of n){const i=r.textContent??"";if(!/\{\{\s*\w+\s*\}\}/.test(i))continue;const l=s.createDocumentFragment();let m=0;for(const c of i.matchAll(/\{\{\s*(\w+)\s*\}\}/g)){const d=c.index??0;d>m&&l.appendChild(s.createTextNode(i.slice(m,d)));const u=s.createElement("span");u.setAttribute("data-variable",c[1]),u.textContent=`{{ ${c[1]} }}`,l.appendChild(u),m=d+c[0].length}m<i.length&&l.appendChild(s.createTextNode(i.slice(m))),r.parentNode?.replaceChild(l,r)}return s.body.innerHTML}function SC(t){return t.replace(/<span[^>]*data-variable="(\w+)"[^>]*>.*?<\/span>/g,"{{ $1 }}")}function Ki(t){const s=t.toLowerCase();return s.includes("<!doctype")||s.includes("<style")||s.includes("<img")||s.includes("<table")||s.includes("style=")}const CC=o.forwardRef(function({value:s,onChange:a},n){const[r,i]=o.useState(()=>Ki(s)),[l,m]=o.useState(s),c=o.useRef(!1),d=o.useRef(s),u=Xp({extensions:[tx.configure({heading:{levels:[1,2,3]}}),sx.configure({openOnClick:!1,HTMLAttributes:{target:"_blank",rel:"noopener noreferrer"}}),ex,ax.configure({types:["heading","paragraph"],alignments:["left","center","right"]}),nx.configure({placeholder:"Start writing your email..."}),_C],content:r?"":Do(s),onUpdate:({editor:x})=>{if(c.current)return;const f=SC(x.getHTML());d.current=f,a(f)}});o.useEffect(()=>{if(s!==d.current){if(Ki(s)){d.current=s,m(s),i(!0);return}
4if(r){d.current=s,m(s);return}u&&(d.current=s,c.current=!0,u.commands.setContent(Do(s)),c.current=!1)}},[s,u,r]);const h=o.useCallback(()=>{if(r){if(Ki(l))return;d.current=l,a(l),u&&(c.current=!0,u.commands.setContent(Do(l)),c.current=!1),i(!1)}else m(s),i(!0)},[r,l,u,a,s]),p=o.useCallback(x=>{m(x),d.current=x,a(x)},[a]);return o.useImperativeHandle(n,()=>({insertVariable(x){if(r){const f=`{{ ${x} }}`;p(l+f)}else u&&u.chain().focus().insertVariable(x).run()}}),[u,r,l,p]),r?e.jsxs("div",{className:"tiptap-editor overflow-hidden rounded-md border",children:[u&&e.jsx(Km,{editor:u,onToggleSource:h,isSourceMode:!0}),Ki(l)&&e.jsx("p",{className:"border-b bg-muted/50 px-3 py-1.5 text-xs text-muted-foreground",children:"This template contains raw email HTML (a full document, images, tables, or inline styles) the visual editor can't preserve â edit it here in source."}),e.jsx(It,{value:l,onChange:x=>p(x.target.value),rows:20,className:"resize-y rounded-none border-0 font-mono text-sm focus-visible:ring-0 focus-visible:ring-offset-0",placeholder:"<html>...</html>"})]}):e.jsxs("div",{className:"tiptap-editor overflow-hidden rounded-md border",children:[u&&e.jsx(Km,{editor:u,onToggleSource:h,isSourceMode:!1}),e.jsx(rx,{editor:u})]})});function Lo(){const t=kt(),{id:s}=Ds(),a=!!s,{data:n,isLoading:r}=D0(s),i=$0(),l=Zx(),[m,c]=o.useState("edit"),[d,u]=o.useState(!1),h=o.useRef(null),{register:p,handleSubmit:x,reset:f,watch:b,control:N,formState:{errors:j,isSubmitting:w}}=Fr({defaultValues:{name:"",subject:"",body_html:"",template_type:"custom",is_active:!0,trigger_days_before:""}});o.useEffect(()=>{n&&f({name:n.name,subject:n.subject,body_html:n.body_html,template_type:n.template_type,is_active:n.is_active,trigger_days_before:n.trigger_days_before!=null?String(n.trigger_days_before):""})},[n,f]);const v=b("template_type"),k=b("body_html"),S=v==="renewal_reminder"||v==="renewal_final",_=C=>{h.current?.insertVariable(C)},y=async C=>{try{if(a&&s){const P={name:C.name,subject:C.subject,body_html:C.body_html,is_active:C.is_active,trigger_days_before:C.trigger_days_before?parseInt(C.trigger_days_before):null};await l.mutateAsync({id:s,data:P})}else{const P={template_type:C.template_type,name:C.name,subject:C.subject,body_html:C.body_html,trigger_days_before:C.trigger_days_before?parseInt(C.trigger_days_before):null};await i.mutateAsync(P)}t("/emails/templates")}
4catch(P){console.error("Failed to save template:",P);const A=P?.response;if(A?.status===422){const E=A.data?.detail;Ut.error(typeof E=="string"?E:"Template failed validation.")}}};return a&&r?e.jsxs("div",{className:"space-y-6",children:[e.jsx(Y,{className:"h-8 w-48"}),e.jsx(Y,{className:"h-96 w-full"})]}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[e.jsx(g,{variant:"ghost",size:"icon",onClick:()=>t("/emails/templates"),children:e.jsx(es,{className:"h-4 w-4"})}),e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(Hs,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:a?"Edit template":"New template"}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:a?"Update email template":"Create a new email template"})]})]}),a&&s&&e.jsxs(g,{variant:"outline",onClick:()=>u(!0),children:[e.jsx(Pr,{className:"mr-2 h-4 w-4"}),"Send test"]})]}),e.jsxs("form",{onSubmit:x(y),className:"space-y-6",children:[e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(cs,{className:"h-4 w-4"})}),"Template details"]})}),e.jsxs($,{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"name",children:"Template name *"}),e.jsx(O,{id:"name",...p("name",{required:"Name is required"}),placeholder:"Welcome Email"}),j.name&&e.jsx("p",{className:"text-sm text-destructive",children:j.name.message})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{children:"Type *"}),e.jsx(qa,{name:"template_type",control:N,render:({field:C})=>e.jsxs(qe,{value:C.value,onValueChange:P=>P&&C.onChange(P),children:[e.jsx(Le,{children:e.jsx(Ie,{placeholder:"Select type"})}),e.jsxs($e,{children:[e.jsx(q,{value:"welcome",children:"Welcome"}),e.jsx(q,{value:"payment_receipt",children:"Payment receipt"}),e.jsx(q,{value:"invoice",children:"Invoice"}),e.jsx(q,{value:"renewal_reminder",children:"Renewal reminder"}),e.jsx(q,{value:"renewal_final",children:"Final renewal"}),e.jsx(q,{value:"renewal_sequence",children:"Renewal sequence"}),e.jsx(q,{value:"membership_expired",children:"Membership expired"}),e.jsx(q,{value:"fellowship_expiring",children:"Fellowship expiring"}),e.jsx(q,{value:"password_reset",children:"Password reset"}),e.jsx(q,{value:"pending_approval_member",children:"Pending approval (member)"}),e.jsx(q,{value:"pending_approval_admin",children:"Pending approval (admin)"}),e.jsx(q,{value:"application_approved",children:"Application approved"}),e.jsx(q,{value:"application_rejected",children:"Application rejected"}),e.jsx(q,{value:"dues_comp_notice",children:"Dues comp notice"}),e.jsx(q,{value:"custom",children:"Custom"})]})]})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"subject",children:"Subject *"}),e.jsx(O,{id:"subject",...p("subject",{required:"Subject is required"}),placeholder:"Welcome to {{society_name}}"}),j.subject&&e.jsx("p",{className:"text-sm text-destructive",children:j.subject.message})]}),S&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"trigger_days_before",children:"Trigger days before expiry"}),e.jsx(O,{id:"trigger_days_before",type:"number",min:1,...p("trigger_days_before"),placeholder:"30",className:"w-48"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Number of days before membership expiry to send this reminder"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(T,{children:"Status"}),e.jsx(qa,{name:"is_active",control:N,render:({field:C}
4)=>e.jsxs(qe,{value:C.value?"true":"false",onValueChange:P=>P&&C.onChange(P==="true"),children:[e.jsx(Le,{className:"w-32",children:e.jsx(Ie,{})}),e.jsxs($e,{children:[e.jsx(q,{value:"true",children:"Active"}),e.jsx(q,{value:"false",children:"Inactive"})]})]})})]})]})]}),e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx($t,{className:"h-4 w-4"})}),"Email body"]}),e.jsxs("div",{className:"flex gap-1 rounded-md border p-0.5",children:[e.jsx("button",{type:"button",className:`rounded px-3 py-1 text-sm ${m==="edit"?"bg-primary text-primary-foreground":"hover:bg-muted"}`,onClick:()=>c("edit"),children:"Edit"}),e.jsx("button",{type:"button",className:`rounded px-3 py-1 text-sm ${m==="preview"?"bg-primary text-primary-foreground":"hover:bg-muted"}`,onClick:()=>c("preview"),children:"Preview"})]})]})}),e.jsx($,{className:"space-y-4",children:m==="edit"?e.jsxs(e.Fragment,{children:[e.jsx(Y1,{templateType:v,onInsert:_,extraVariables:n?.available_variables}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{children:"Email body *"}),e.jsx(qa,{name:"body_html",control:N,rules:{required:"Body is required"},render:({field:C})=>e.jsx(CC,{ref:h,value:C.value,onChange:C.onChange})}),j.body_html&&e.jsx("p",{className:"text-sm text-destructive",children:j.body_html.message})]})]}):e.jsx(H1,{html:k})})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(g,{type:"button",variant:"outline",onClick:()=>t("/emails/templates"),children:"Cancel"}),e.jsx(g,{type:"submit",disabled:w||i.isPending||l.isPending,children:w||i.isPending||l.isPending?"Savingâ¦":a?"Update template":"Create template"})]})]}),a&&s&&e.jsx(J1,{templateId:s,open:d,onOpenChange:u})]})}const ff={list:async(t={})=>(await F.get("/member-campaigns/",{params:t})).data,stepsSummary:async(t,s)=>(await F.get(`/member-campaigns/${t}/steps-summary`,{params:s?{society_id:s}:{}})).data};function PC(){const{selectedSocietyId:t}=V();return re({queryKey:["member-campaign-runs",t],queryFn:()=>ff.list({society_id:t||void 0})})}function AC(t,s){const{selectedSocietyId:a}=V();return re({queryKey:["campaign-steps-summary",t,a],queryFn:()=>ff.stepsSummary(t,a||void 0),enabled:s})}const EC={active:{label:"Active",pill:"bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400",dot:"bg-green-500"},completed:{label:"Completed",pill:"bg-muted text-muted-foreground",dot:"bg-muted-foreground/60"},draft:{label:"Draft",pill:"bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400",dot:"bg-blue-500"},paused:{label:"Paused",pill:"bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400",dot:"bg-amber-500"},cancelled:{label:"Cancelled",pill:"bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400",dot:"bg-red-500"}};function TC(t){return t?Ct(t).toLocaleDateString("en-US",{month:"short",day:"numeric"}):null}function El(t,s){return s<=0?"â":`${Math.round(t/s*100)}%`}function FC({runId:t}){const{data:s,isLoading:a,isError:n,refetch:r,isFetching:i}=AC(t,!0);return a?e.jsx("div",{className:"space-y-2 p-4",children:Array.from({length:2}).map((l,m)=>e.jsx(Y,{className:"h-8 w-full"},m))}):n||!s?e.jsxs("div",{className:"flex flex-col items-center gap-2 p-6 text-center",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Couldn't load the step breakdown for this campaign."}),e.jsxs(g,{variant:"outline",size:"sm",onClick:()=>{r()},disabled:i,children:[e.jsx(sd,{className:me("mr-2 h-3.5 w-3.5",i&&"animate-spin")}),i?"Retryingâ¦":"Retry"]})]}):s.steps.length===0?e.jsx("div",{className:"p-6 text-center text-sm text-muted-foreground",children:"No steps recorded for this campaign."}):e.jsx("div",{className:"p-3",children:e.jsxs(Pt,{children:[e.jsx(At,{children:e.jsxs(Ue,{className:"hover:bg-transparent",children:[e.jsx(H,{className:"h-9 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground
4/80",children:"Step"}),e.jsx(H,{className:"h-9 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Sent"}),e.jsx(H,{className:"h-9 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Blocked"}),e.jsx(H,{className:"h-9 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Opens"}),e.jsx(H,{className:"h-9 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Clicks"}),e.jsx(H,{className:"h-9 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Unsubs"})]})}),e.jsx(Et,{children:s.steps.map(l=>e.jsxs(Ue,{className:"hover:bg-transparent",children:[e.jsxs(G,{className:"font-medium",children:[l.step_key,e.jsxs("span",{className:"ml-2 font-normal text-muted-foreground",children:["day ",l.delay_days]})]}),e.jsx(G,{children:l.sent}),e.jsx(G,{children:l.blocked}),e.jsxs(G,{children:[l.opens," ",e.jsxs("span",{className:"text-muted-foreground",children:["(",El(l.opens,l.sent),")"]})]}),e.jsxs(G,{children:[l.clicks," ",e.jsxs("span",{className:"text-muted-foreground",children:["(",El(l.clicks,l.sent),")"]})]}),e.jsx(G,{children:l.unsubscribes})]},l.step_key))})]})})}function RC({run:t}){const[s,a]=o.useState(!1),n=EC[t.status]||{label:t.status,pill:"bg-muted text-muted-foreground",dot:"bg-muted-foreground/60"},r=TC(t.started_at),i=()=>a(l=>!l);return e.jsxs(e.Fragment,{children:[e.jsxs(Ue,{className:"cursor-pointer hover:bg-brand-navy/[0.04] dark:hover:bg-brand-navy/10",onClick:i,onKeyDown:l=>{(l.key==="Enter"||l.key===" ")&&(l.preventDefault(),i())},role:"button",tabIndex:0,"aria-expanded":s,children:[e.jsx(G,{className:"font-medium",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ts,{className:me("h-4 w-4 shrink-0 text-muted-foreground transition-transform",s&&"rotate-90"),"aria-hidden":"true"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{children:t.name}),e.jsxs("div",{className:"text-[11px] text-muted-foreground",children:[t.steps," ",t.steps===1?"step":"steps",r?` · started ${r}`:""]})]})]})}),e.jsx(G,{children:e.jsxs("span",{className:me("inline-flex items-center gap-1.5 rounded-full px-2.5 py-0.5 text-[11px] font-medium",n.pill),children:[e.jsx("span",{className:me("h-1.5 w-1.5 rounded-full",n.dot),"aria-hidden":"true"}),n.label]})}),e.jsx(G,{children:t.recipient_count}),e.jsx(G,{children:t.sent_count}),e.jsxs(G,{children:[t.open_count," ",e.jsxs("span",{className:"text-muted-foreground",children:["(",El(t.open_count,t.sent_count),")"]})]}),e.jsxs(G,{children:[t.click_count," ",e.jsxs("span",{className:"text-muted-foreground",children:["(",El(t.click_count,t.sent_count),")"]})]}),e.jsx(G,{children:t.unsubscribe_count})]}),s&&e.jsx(Ue,{className:"hover:bg-transparent",children:e.jsx(G,{colSpan:7,className:"bg-muted/20 p-0",children:e.jsx(FC,{runId:t.id})})})]})}function MC(){const{data:t,isLoading:s,isError:a,refetch:n,isFetching:r}=PC(),i=!s&&!a&&(!t?.items||t.items.length===0);return e.jsxs("div",{className:"space-y-6",children:[e.jsx(Tn,{}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(Vn,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:"Campaigns"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Multi-step member email campaigns and their funnel performance"})]})]}),e.jsx(L,{className:"min-w-0 overflow-hidden",children:e.jsx($,{className:"p-0",children:s?e.jsx("div",{className:"space-y-3 p-6",children:Array.from({length:3}).map((l,m)=>e.jsx(Y,{className:"h-12 w-full"},m))}):a?e.jsxs("div",{className:"flex flex-col items-center gap-3 py-12 text-center",children:[e.jsx("p",{className:"text-muted-foreground",children:"Couldn't load campaigns."}),e.jsxs(g,{variant:"outline",size:"sm",onClick:()=>{n()},disabled:r,children:[e.jsx(sd,{className:me("mr-2 h-3.5 w-3.5",r&&"animate-spin")}),r?"Retryingâ¦":"Retry"]})]}):i?e.jsxs("div",{className:"py-12 text-center",children:[e.jsx("div",{className:"mx-auto mb-4 flex h-10 w-10 items-center justify-center rounded-lg bg-brand-navy
4/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(Vn,{className:"h-5 w-5"})}),e.jsx("p",{className:"font-medium",children:"No campaigns yet"}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"Campaigns will appear here when a member email campaign is prepared."})]}):e.jsxs(Pt,{children:[e.jsx(At,{className:"bg-muted/30",children:e.jsxs(Ue,{className:"hover:bg-transparent",children:[e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Campaign"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Status"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Recipients"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Sent"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Opens"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Clicks"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Unsubs"})]})}),e.jsx(Et,{children:t?.items.map(l=>e.jsx(RC,{run:l},l.id))})]})})}),!s&&!a&&t?.items&&t.items.length>0&&e.jsx("p",{className:"text-[11.5px] text-muted-foreground",children:"Campaign creation from this screen arrives with the campaign builder."})]})}function DC(){const[t,s]=o.useState(1),[a,n]=o.useState("all"),[r,i]=o.useState("all"),[l,m]=o.useState(""),[c,d]=o.useState(""),[u,h]=o.useState(!1),p=o.useMemo(()=>({page:t,size:20,status:a!=="all"?a:void 0,templateType:r!=="all"?r:void 0,dateFrom:l||void 0,dateTo:c||void 0}),[t,a,r,l,c]),{data:x,isLoading:f}=O0(p),b=B0(),N=async()=>{await b.mutateAsync(),h(!1)},j=!f&&(!x?.items||x.items.length===0);return e.jsxs("div",{className:"space-y-6",children:[e.jsx(Tn,{}),e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx($t,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:"Email logs"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"View sent emails and delivery status"})]})]}),e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:e.jsxs(g,{onClick:()=>h(!0),children:[e.jsx(Up,{className:"mr-2 h-4 w-4"}),"Send renewal reminders"]})})]}),e.jsx(cC,{status:a,onStatusChange:w=>{n(w),s(1)},templateType:r,onTemplateTypeChange:w=>{i(w),s(1)},dateFrom:l,onDateFromChange:w=>{m(w),s(1)},dateTo:c,onDateToChange:w=>{d(w),s(1)}}),e.jsx(L,{className:"min-w-0 overflow-hidden",children:e.jsx($,{className:"p-0",children:f?e.jsx("div",{className:"space-y-3 p-6",children:Array.from({length:5}).map((w,v)=>e.jsx(Y,{className:"h-12 w-full"},v))}):j?e.jsx("div",{className:"py-12 text-center",children:e.jsx("p",{className:"text-muted-foreground",children:"No email logs found."})}):e.jsx(oC,{logs:x?.items||[]})})}),x&&x.pages>1&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Showing ",(t-1)*20+1," to ",Math.min(t*20,x.total)," of ",x.total," logs"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(g,{variant:"outline",size:"sm",onClick:()=>s(t-1),disabled:t===1,children:[e.jsx(Gs,{className:"h-4 w-4"})," Previous"]}),e.jsxs("span",{className:"text-sm",children:["Page ",t," of ",x.pages]}),e.jsxs(g,{variant:"outline",size:"sm",onClick:()=>s(t+1),disabled:t===x.pages,children:["Next ",e.jsx(ts,{className:"h-4 w-4"})]})]})]}),e.jsx(dC,{open:u,onOpenChange:h,onConfirm:N,isPending:b.isPending})]})}const LC={hard_bounce:{label:"Hard bounce",pill:"bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400",dot:"bg-red-500"}
4,soft_bounce:{label:"Soft bounce",pill:"bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400",dot:"bg-amber-500"},complaint:{label:"Complaint",pill:"bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400",dot:"bg-red-500"},manual:{label:"Manual",pill:"bg-muted text-muted-foreground",dot:"bg-muted-foreground/60"},unsubscribe:{label:"Unsubscribed",pill:"bg-muted text-muted-foreground",dot:"bg-muted-foreground/60"}},$C={all:{label:"All email",pill:"bg-muted text-muted-foreground",dot:"bg-red-500"},marketing:{label:"Marketing only",pill:"bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400",dot:"bg-amber-500"},record_only:{label:"Record only",pill:"bg-muted text-muted-foreground",dot:"bg-muted-foreground/60"}};function qC(t){return t.reason==="unsubscribe"?t.source==="footer_link"?"Unsubscribed via email footer":t.source==="one_click"?"Unsubscribed via one-click":"Unsubscribed":t.bounce_type&&t.bounce_subtype?`${t.bounce_type} / ${t.bounce_subtype}`:t.bounce_type||"â"}function IC(){const[t,s]=o.useState(1),[a,n]=o.useState("all"),[r,i]=o.useState("any"),[l,m]=o.useState(null),[c,d]=o.useState(!1),[u,h]=o.useState(""),[p,x]=o.useState("all"),f=o.useMemo(()=>({page:t,size:20,reason:a!=="all"?a:void 0,scope:r!=="any"?r:void 0}),[t,a,r]),{data:b,isLoading:N}=K0(f),j=W0(),w=V0(),v=async()=>{l&&(await j.mutateAsync(l.id),m(null))},k=async()=>{const _=u.trim();if(_)try{await w.mutateAsync({email:_,scope:p}),d(!1),h(""),x("all")}catch{Ut.error("Couldn't suppress that address. Please try again.")}},S=!N&&(!b?.items||b.items.length===0);return e.jsxs("div",{className:"space-y-6",children:[e.jsx(Tn,{}),e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(Sp,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:"Email suppressions"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Addresses blocked from receiving emails due to bounces or complaints"})]})]}),e.jsxs(g,{variant:"outline",size:"sm",onClick:()=>d(!0),children:[e.jsx(zb,{className:"mr-2 h-4 w-4"}),"Suppress address"]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-4",children:[e.jsxs(qe,{value:a,onValueChange:_=>{n(_),s(1)},children:[e.jsx(Le,{className:"w-44",children:e.jsx(Ie,{placeholder:"Reason"})}),e.jsxs($e,{children:[e.jsx(q,{value:"all",children:"All reasons"}),e.jsx(q,{value:"hard_bounce",children:"Hard bounce"}),e.jsx(q,{value:"soft_bounce",children:"Soft bounce"}),e.jsx(q,{value:"complaint",children:"Complaint"}),e.jsx(q,{value:"manual",children:"Manual"}),e.jsx(q,{value:"unsubscribe",children:"Unsubscribed"})]})]}),e.jsxs(qe,{value:r,onValueChange:_=>{i(_),s(1)},children:[e.jsx(Le,{className:"w-44",children:e.jsx(Ie,{placeholder:"Blocks"})}),e.jsxs($e,{children:[e.jsx(q,{value:"any",children:"All blocks"}),e.jsx(q,{value:"all",children:"All email"}),e.jsx(q,{value:"marketing",children:"Marketing only"}),e.jsx(q,{value:"record_only",children:"Record only"})]})]}),b&&e.jsxs("span",{className:"text-sm text-muted-foreground",children:[b.total," ",b.total===1?"suppression":"suppressions"]})]}),e.jsx(L,{className:"min-w-0 overflow-hidden",children:e.jsx($,{className:"p-0",children:N?e.jsx("div",{className:"space-y-3 p-6",children:Array.from({length:5}).map((_,y)=>e.jsx(Y,{className:"h-12 w-full"},y))}):S?e.jsx("div",{className:"py-12 text-center",children:e.jsx("p",{className:"text-muted-foreground",children:"No suppressed addresses found."})}):e.jsxs(Pt,{children:[e.jsx(At,{className:"bg-muted/30",children:e.jsxs(Ue,{className:"hover:bg-transparent",children:[e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Email"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground
4/80",children:"Reason"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Blocks"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Details"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Source"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Date"}),e.jsx(H,{className:"h-10 w-16"})]})}),e.jsx(Et,{children:b?.items.map(_=>{const y=LC[_.reason]||{label:_.reason,pill:"bg-muted text-muted-foreground",dot:"bg-muted-foreground/60"},C=$C[_.scope]||{label:_.scope,pill:"bg-muted text-muted-foreground",dot:"bg-muted-foreground/60"};return e.jsxs(Ue,{className:"hover:bg-brand-navy/[0.04] dark:hover:bg-brand-navy/10",children:[e.jsx(G,{className:"font-medium",children:_.email}),e.jsx(G,{children:e.jsxs("span",{className:me("inline-flex items-center gap-1.5 rounded-full px-2.5 py-0.5 text-[11px] font-medium",y.pill),children:[e.jsx("span",{className:me("h-1.5 w-1.5 rounded-full",y.dot),"aria-hidden":"true"}),y.label]})}),e.jsx(G,{children:e.jsxs("span",{className:me("inline-flex items-center gap-1.5 rounded-full px-2.5 py-0.5 text-[11px] font-medium",C.pill),children:[e.jsx("span",{className:me("h-1.5 w-1.5 rounded-full",C.dot),"aria-hidden":"true"}),C.label]})}),e.jsx(G,{className:"text-sm text-muted-foreground",children:qC(_)}),e.jsx(G,{className:"text-sm text-muted-foreground",children:_.source||"â"}),e.jsx(G,{className:"whitespace-nowrap text-sm text-muted-foreground",children:_.created_at?Ct(_.created_at).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):"â"}),e.jsx(G,{children:e.jsxs(g,{variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground hover:text-destructive",onClick:()=>m(_),children:[e.jsx(Ft,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Remove"})]})})]},_.id)})})]})})}),b&&b.pages>1&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Showing ",(t-1)*20+1," to ",Math.min(t*20,b.total)," of ",b.total," ","suppressions"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(g,{variant:"outline",size:"sm",onClick:()=>s(t-1),disabled:t===1,children:[e.jsx(Gs,{className:"h-4 w-4"})," Previous"]}),e.jsxs("span",{className:"text-sm",children:["Page ",t," of ",b.pages]}),e.jsxs(g,{variant:"outline",size:"sm",onClick:()=>s(t+1),disabled:t===b.pages,children:["Next ",e.jsx(ts,{className:"h-4 w-4"})]})]})]}),e.jsx(Fe,{open:!!l,onOpenChange:_=>!_&&m(null),children:e.jsxs(Te,{children:[e.jsxs(Ae,{children:[e.jsx(Ee,{children:"Remove suppression"}),e.jsx(tt,{children:l?.reason==="unsubscribe"?e.jsxs(e.Fragment,{children:["This member opted out themselves on"," ",e.jsx("strong",{children:l?.created_at?Ct(l.created_at).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):"an earlier date"}),"."," ",l?.scope==="all"?"Removing this will re-enable ALL email to this address, including receipts and renewal notices. Only proceed with their explicit consent.":"Only re-enable marketing email with their explicit consent."]}):e.jsxs(e.Fragment,{children:["Are you sure you want to un-suppress ",e.jsx("strong",{children:l?.email}),"? This address will be able to receive emails again. Only do this if you're confident the underlying issue (bounced address or spam complaint) has been resolved."]})})]}),e.jsxs(Ge,{children:[e.jsx(g,{variant:"outline",onClick:()=>m(null),children:"Cancel"}),e.jsx(g,{variant:"destructive",onClick:v,disabled:j.isPending,children:j.isPending?"Removingâ¦":"Remove suppression"})]})]})}),e.jsx(Fe,{open:c,onOpenChange:_=>{_||(h(""),x("all")),d(_)},children:e.jsxs(Te,{children:[e.jsxs(Ae,{children:[e.jsx(Ee,{children:"Suppress address"}),e.jsx(tt,{children:"Manually block an email address from receiving future emails."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"suppress-email",children:"Email address"}),e.jsx(O,{id:"suppress-email",type:"email",placeholder:"[email protected]",value:u,onChange:_=>h(_.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{children:"Scope"}),e.jsxs(Cn,{value:p,onValueChange:_=>x(_),children:[e.jsxs("label",{htmlFor:"suppress-scope-all",className:"flex min-h-[44px] curs
4or-pointer flex-col gap-0.5 rounded-md border p-3 text-sm has-[[data-state=checked]]:border-brand-navy",children:[e.jsxs("span",{className:"flex items-center gap-2 font-medium",children:[e.jsx(la,{id:"suppress-scope-all",value:"all"}),"All email"]}),e.jsx("span",{className:"pl-6 text-xs text-muted-foreground",children:"Blocks every email including receipts and renewal notices"})]}),e.jsxs("label",{htmlFor:"suppress-scope-marketing",className:"flex min-h-[44px] cursor-pointer flex-col gap-0.5 rounded-md border p-3 text-sm has-[[data-state=checked]]:border-brand-navy",children:[e.jsxs("span",{className:"flex items-center gap-2 font-medium",children:[e.jsx(la,{id:"suppress-scope-marketing",value:"marketing"}),"Marketing only"]}),e.jsx("span",{className:"pl-6 text-xs text-muted-foreground",children:"Blocks campaigns and broadcasts; account email still delivers"})]})]})]})]}),e.jsxs(Ge,{children:[e.jsx(g,{variant:"outline",onClick:()=>d(!1),children:"Cancel"}),e.jsx(g,{onClick:k,disabled:!u.trim()||w.isPending,children:w.isPending?"Suppressingâ¦":"Suppress address"})]})]})})]})}const OC={ses:"Amazon SES",smtp:"Custom SMTP"};function UC({societyId:t}){const{data:s,isLoading:a}=Or(t);return e.jsxs(L,{children:[e.jsx(ne,{className:"pb-3",children:e.jsx(ie,{className:"text-sm font-semibold",children:"Sending identity"})}),e.jsxs($,{className:"space-y-0 divide-y divide-border",children:[a?e.jsx(Y,{className:"h-24 w-full"}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 py-2 text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"From"}),e.jsx("span",{className:"min-w-0 truncate text-right font-medium",children:s?.from_address?s.from_name?`${s.from_name} <${s.from_address}>`:s.from_address:"Not configured"})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2 py-2 text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Reply-to"}),e.jsx("span",{className:"min-w-0 truncate text-right font-medium",children:s?.reply_to_email||"â"})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2 py-2 text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Provider"}),e.jsx("span",{className:"font-medium",children:s?.provider?OC[s.provider]??s.provider:"None"})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2 py-2 text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Status"}),e.jsxs("span",{className:"inline-flex items-center gap-1.5 font-medium",children:[e.jsx("span",{className:`h-1.5 w-1.5 shrink-0 rounded-full ${s?.connected?"bg-green-500":"bg-muted-foreground/60"}`}),s?.connected?"Connected":"Not connected"]})]})]}),e.jsx("p",{className:"pt-3 text-xs text-muted-foreground",children:"Credentials are managed by your Korevera administrator."})]})]})}function zC({societyId:t,disabled:s}){const{user:a}=V(),n=Qx(),r=async()=>{try{const i=await n.mutateAsync(t);i.success?Ut.success("Test email sent successfully"):Ut.error(i.error||"Test email failed")}catch{Ut.error("An unexpected error occurred")}};return e.jsxs(L,{children:[e.jsxs(ne,{className:"pb-3",children:[e.jsx(ie,{className:"text-sm font-semibold",children:"Send a test email"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Sends a test message through your configured provider to confirm delivery"})]}),e.jsxs($,{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(T,{htmlFor:"test-email-to",children:"Sends to"}),e.jsx(O,{id:"test-email-to",type:"email",value:a?.email??"",disabled:!0,readOnly:!0})]}),e.jsx(g,{onClick:()=>{r()},disabled:s||n.isPending,children:n.isPending?"Sendingâ¦":"Send test email"})]})]})}function BC(){const{selectedSocietyId:t}=V(),{data:s}=Or(t??void 0);return e.jsxs("div",{className:"space-y-6",children:[e.jsx(Tn,{}),e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-brand-navy
4/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(Pr,{className:"h-5 w-5"})}),e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:"Sending"})]}),e.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"Sending identity, credential ownership, and test delivery"})]}),t&&e.jsx(gf,{societyId:t,linkTo:"/emails"})]}),t?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[e.jsx(UC,{societyId:t}),e.jsx(zC,{societyId:t,disabled:!s?.provider})]}),e.jsxs(L,{children:[e.jsx(ne,{className:"pb-3",children:e.jsx(ie,{className:"text-sm font-semibold",children:"Email platform sync rules"})}),e.jsx($,{children:e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Automatically sync member segments to Mailchimp or MailerLite based on status, membership type, or tags."," ",e.jsx(je,{to:"/emails/sync-rules",className:"text-primary underline hover:no-underline",children:"Manage sync rules"})]})})]})]}):e.jsx(L,{children:e.jsx($,{className:"p-6 text-sm text-muted-foreground",children:"Select a society to manage sending"})})]})}const KC={first_name:"First Name",last_name:"Last Name",email:"Email",phone:"Phone",status:"Status",is_active:"Active",membership_type_id:"Membership Type",membership_start_date:"Membership Start",membership_end_date:"Membership End",auto_renew:"Auto Renew",name:"Name",description:"Description",subject:"Subject",body_html:"Body",template_type:"Template Type",role:"Role",hashed_password:"Password",amount:"Amount",reason:"Reason",extended_days:"Extended Days"};function Qm(t){return KC[t]||t.replace(/_/g," ").replace(/\b\w/g,s=>s.toUpperCase())}function $o(t,s){return s==null?"â":t==="hashed_password"?"â¢â¢â¢â¢â¢â¢â¢â¢":t==="amount"&&typeof s=="number"?`$${s.toFixed(2)}`:String(s)}function QC({changes:t}){return e.jsxs("div",{className:"border-t bg-muted/30 px-8 py-3",children:[e.jsx("p",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"Changes"}),e.jsx("div",{className:"space-y-1",children:Object.entries(t).map(([s,a])=>{if(s==="reason")return e.jsxs("div",{className:"text-xs text-muted-foreground",children:[e.jsx("span",{className:"font-medium",children:"Reason:"})," ",String(a)]},s);if(s==="extended_days")return e.jsxs("div",{className:"text-xs text-muted-foreground",children:[e.jsx("span",{className:"font-medium",children:"Extended by:"})," ",String(a)," days"]},s);const n=a;return n&&typeof n=="object"&&"old"in n&&"new"in n?e.jsxs("div",{className:"text-xs text-muted-foreground",children:[e.jsxs("span",{className:"font-medium",children:[Qm(s),":"]})," ",e.jsx("span",{className:"line-through",children:$o(s,n.old)})," ",e.jsx("span",{className:"text-foreground",children:$o(s,n.new)})]},s):e.jsxs("div",{className:"text-xs text-muted-foreground",children:[e.jsxs("span",{className:"font-medium",children:[Qm(s),":"]})," ",$o(s,a)]},s)})})]})}const cr={create:"bg-emerald-500",update:"bg-amber-500",delete:"bg-red-500",payment:"bg-orange-500",payment_completed:"bg-orange-500",payment_failed:"bg-red-500",refund_issued:"bg-amber-500",login:"bg-muted-foreground/60",logout:"bg-muted-foreground/60",member_login:"bg-muted-foreground/60",password_change:"bg-muted-foreground/60",status_override:"bg-red-500",status_auto_change:"bg-amber-500",email_sent:"bg-muted-foreground/60",subscription_created:"bg-emerald-500",subscription_cancelled:"bg-red-500",subscription_renewed:"bg-emerald-500",profile_self_update:"bg-muted-foreground/60",member_approved:"bg-emerald-500",member_rejected:"bg-red-500",member_impersonated:"bg-red-500",invoice_created:"bg-orange-500",invoice_sent:"bg-orange-500",invoice_paid:"bg-emerald-500",invoice_voided:"bg-red-500",invoice_batch_created:"bg-orange-500",payment_method_updated:"bg-muted-foreground/60",order_created:"bg-orange-500",order_paid:"bg-emerald-500",event_registration:"bg-emerald-500",event_app_push_success:"bg-emerald-500",event_app_push_failed:"bg-red-500",member_password_changed:"bg-muted-foreground/60",member_email_changed:"bg-muted-foreground/60",dispute_created:"bg-amber-500",dispute_won:"bg-emerald-500",dispute_lost:"bg-red-500",export:"bg-muted-foreground
4/60",import:"bg-muted-foreground/60"},WC={create:"Create",update:"Update",delete:"Delete",login:"Login",logout:"Logout",member_login:"Member login",password_change:"Password",payment:"Payment",payment_completed:"Payment",payment_failed:"Payment failed",refund_issued:"Refund",export:"Export",import:"Import",status_override:"Status override",status_auto_change:"Auto status",email_sent:"Email",subscription_created:"Subscribed",subscription_cancelled:"Unsubscribed",subscription_renewed:"Renewed",profile_self_update:"Profile edit",member_approved:"Approved",member_rejected:"Rejected",member_impersonated:"Impersonated",invoice_created:"Invoice",invoice_sent:"Invoice sent",invoice_paid:"Invoice paid",invoice_voided:"Invoice voided",invoice_batch_created:"Batch invoice",payment_method_updated:"Card updated",order_created:"Order",order_paid:"Order paid",event_registration:"Registration",event_app_push_success:"Event push",event_app_push_failed:"Push failed",member_password_changed:"Password",member_email_changed:"Email changed",dispute_created:"Dispute",dispute_won:"Dispute won",dispute_lost:"Dispute lost"};function yf(t){return WC[t]||t.replace(/_/g," ")}function VC(t){return cr[t]?cr[t]:t.startsWith("create")||t.includes("approve")?cr.create:t.startsWith("update")||t.includes("edit")?cr.update:t.startsWith("delete")||t.includes("reject")?cr.delete:t.includes("payment")||t.includes("charge")?cr.payment:"bg-muted-foreground/60"}function GC({action:t}){return e.jsxs("span",{className:"inline-flex items-center gap-1.5 whitespace-nowrap",children:[e.jsx("span",{className:`h-1.5 w-1.5 shrink-0 rounded-full ${VC(t)}`}),e.jsx("span",{className:"text-xs font-medium",children:yf(t)})]})}function YC({logs:t,expandedIds:s,onToggleExpand:a}){return e.jsxs(Pt,{children:[e.jsx(At,{children:e.jsxs(Ue,{children:[e.jsx(H,{className:"w-[30px]"}),e.jsx(H,{children:"Timestamp"}),e.jsx(H,{children:"Action"}),e.jsx(H,{children:"Resource"}),e.jsx(H,{children:"Description"}),e.jsx(H,{children:"User"}),e.jsx(H,{children:"IP Address"})]})}),e.jsx(Et,{children:t.map(n=>{const r=n.changes&&Object.keys(n.changes).length>0,i=s.has(n.id);return e.jsxs(o.Fragment,{children:[e.jsxs(Ue,{className:r?"cursor-pointer hover:bg-muted/50":"",onClick:()=>r&&a(n.id),children:[e.jsx(G,{className:"pr-0",children:r&&(i?e.jsx(ps,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(ts,{className:"h-4 w-4 text-muted-foreground"}))}),e.jsx(G,{className:"whitespace-nowrap text-sm",children:Be(Ct(n.created_at),"MMM d, yyyy h:mm a")}),e.jsx(G,{children:e.jsx(GC,{action:n.action})}),e.jsx(G,{className:"text-sm",children:n.resource_type}),e.jsx(G,{className:"max-w-[300px] truncate text-sm",children:n.description}),e.jsx(G,{className:"text-sm text-muted-foreground",children:n.user_name||n.user_email||n.user_id||"â"}),e.jsx(G,{className:"font-mono text-sm text-muted-foreground",children:n.ip_address||"â"})]}),i&&r&&e.jsx(Ue,{children:e.jsx(G,{colSpan:7,className:"p-0",children:e.jsx(QC,{changes:n.changes})})})]},n.id)})})]})}function HC({actor:t,onActorChange:s,action:a,onActionChange:n,resourceType:r,onResourceTypeChange:i,dateFrom:l,onDateFromChange:m,dateTo:c,onDateToChange:d}){const{data:u}=J0(),{data:h}=Z0(),{data:p}=H0();return e.jsxs("div",{className:"flex flex-col gap-4 sm:flex-row sm:items-end",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(T,{className:"text-xs",children:"User"}),e.jsxs(qe,{value:t,onValueChange:s,children:[e.jsx(Le,{className:"w-full sm:w-[200px]",children:e.jsx(Ie,{placeholder:"All users"})}),e.jsxs($e,{children:[e.jsx(q,{value:"all",children:"All users"}),p?.map(x=>e.jsxs(q,{value:x.user_ids.join(","),children:[x.name,x.email?e.jsxs("span",{className:"text-muted-foreground",children:[" · ",x.email]}):null]},x.user_ids.join(","))),e.jsx(q,{value:"system",children:"System (automated)"})]})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(T,{className:"text-xs",children:"Action"}),e.jsxs(qe,{value:a,onValueChange:n,children:[e.jsx(Le,{className:"w-full sm:w-[180px]",children:e.jsx(Ie,{placeholder:"All actions"})}),e.jsxs($e,{children:[e.jsx(q,{value:"all",children:"All actions"}),u?.map(x=>e.jsx(q,{value:x,children:yf(x)},x))]})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(T,{className:"text-xs",children:"Resource type"}),e.jsxs(qe,{value:r,onValueChange:i,children:[e.jsx(Le,{className:"w-full sm:w-[180px]",children:e.jsx(Ie,{placeholder:"All types"})}),e.jsxs($e,{children:[e.jsx(q,{value:"all",children:"All types"}),h?.map(x=>e.jsx(q,{value:x,children:x.replace(/_/g," ")},x))]})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(T,{htmlFor:"audit-date-from",className:"text-xs",children:"From"}),e.jsx(O,{id:"audit-date-from",name:"audit-date-from",type:"date",value:l,onCh
4ange:x=>m(x.target.value),className:"w-full sm:w-[150px]",autoComplete:"off"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(T,{htmlFor:"audit-date-to",className:"text-xs",children:"To"}),e.jsx(O,{id:"audit-date-to",name:"audit-date-to",type:"date",value:c,onChange:x=>d(x.target.value),className:"w-full sm:w-[150px]",autoComplete:"off"})]})]})}function JC(){const[t,s]=o.useState(1),[a,n]=o.useState("all"),[r,i]=o.useState("all"),[l,m]=o.useState("all"),[c,d]=o.useState(""),[u,h]=o.useState(""),[p,x]=o.useState(new Set),f=o.useMemo(()=>({page:t,size:50,userId:a!=="all"&&a!=="system"?a.split(","):void 0,systemOnly:a==="system",action:r!=="all"?r:void 0,resourceType:l!=="all"?l:void 0,dateFrom:c||void 0,dateTo:u||void 0}),[t,a,r,l,c,u]),{data:b,isLoading:N}=Y0(f),j=k=>{x(S=>{const _=new Set(S);return _.has(k)?_.delete(k):_.add(k),_})},w=!N&&(!b?.items||b.items.length===0),v=a!=="all"||r!=="all"||l!=="all"||c||u;return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(vr,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:"Audit log"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"View all system activity and changes"})]})]}),e.jsx(HC,{actor:a,onActorChange:k=>{n(k),s(1)},action:r,onActionChange:k=>{i(k),s(1)},resourceType:l,onResourceTypeChange:k=>{m(k),s(1)},dateFrom:c,onDateFromChange:k=>{d(k),s(1)},dateTo:u,onDateToChange:k=>{h(k),s(1)}}),e.jsx(L,{className:"min-w-0 overflow-hidden",children:e.jsx($,{className:"p-0",children:N?e.jsx("div",{className:"space-y-3 p-6",children:Array.from({length:10}).map((k,S)=>e.jsx(Y,{className:"h-12 w-full"},S))}):w?e.jsx("div",{className:"py-12 text-center",children:e.jsx("p",{className:"text-muted-foreground",children:v?"No audit logs match your filters.":"No audit logs yet."})}):e.jsx(YC,{logs:b?.items||[],expandedIds:p,onToggleExpand:j})})}),b&&b.pages>1&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Showing ",(t-1)*50+1," to ",Math.min(t*50,b.total)," of ",b.total," ","entries"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(g,{variant:"outline",size:"sm",onClick:()=>s(t-1),disabled:t===1,children:[e.jsx(Gs,{className:"h-4 w-4"})," Previous"]}),e.jsxs("span",{className:"text-sm",children:["Page ",t," of ",b.pages]}),e.jsxs(g,{variant:"outline",size:"sm",onClick:()=>s(t+1),disabled:t===b.pages,children:["Next ",e.jsx(ts,{className:"h-4 w-4"})]})]})]})]})}const ZC={draft:"bg-muted-foreground/60",sent:"bg-amber-500",paid:"bg-emerald-500",void:"bg-red-500"},XC={draft:"Draft",sent:"Sent",paid:"Paid",void:"Void"};function e2({invoices:t,onDownloadPdf:s,onForwardEmail:a,onMarkPaid:n,onVoid:r}){return e.jsxs("div",{className:"overflow-x-auto",children:[e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-border",children:[e.jsx("th",{className:"px-4 py-2 text-left text-[11px] font-medium uppercase tracking-wider text-muted-foreground/80",children:"Invoice #"}),e.jsx("th",{className:"px-4 py-2 text-left text-[11px] font-medium uppercase tracking-wider text-muted-foreground/80",children:"Member"}),e.jsx("th",{className:"px-4 py-2 text-right text-[11px] font-medium uppercase tracking-wider text-muted-foreground/80",children:"Amount"}),e.jsx("th",{className:"px-4 py-2 text-left text-[11px] font-medium uppercase tracking-wider text-muted-foreground/80",children:"Due date"}),e.jsx("th",{className:"px-4 py-2 text-left text-[11px] font-medium uppercase tracking-wider text-muted-foreground/80",children:"Status"}),e.jsx("th",{className:"px-4 py-2 text-left text-[11px] font-medium uppercase tracking-wider text-muted-foreground/80",children:"Delivery"}),e.jsx("th",{className:"px-4 py-2 text-right text-[11px] font-medium uppercase tracking-wider text-muted-foreground
4/80",children:"Actions"})]})}),e.jsx("tbody",{children:t.map(i=>e.jsxs("tr",{className:"border-b border-border hover:bg-muted/50",children:[e.jsx("td",{className:"px-4 py-3 font-mono text-xs",children:i.invoice_number}),e.jsx("td",{className:"px-4 py-3",children:e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:i.member_name||"â"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:i.member_email})]})}),e.jsx("td",{className:"px-4 py-3 text-right font-medium",children:Number(i.amount).toLocaleString("en-US",{style:"currency",currency:"USD"})}),e.jsx("td",{className:"px-4 py-3",children:Be(Ps(i.due_date),"MMM d, yyyy")}),e.jsx("td",{className:"px-4 py-3",children:e.jsxs("span",{className:"inline-flex items-center gap-1.5 whitespace-nowrap",children:[e.jsx("span",{className:`h-1.5 w-1.5 shrink-0 rounded-full ${ZC[i.status]||"bg-muted-foreground/60"}`}),e.jsx("span",{className:"text-xs font-medium",children:XC[i.status]||i.status})]})}),e.jsx("td",{className:"px-4 py-3",children:e.jsx("span",{className:"text-xs capitalize text-muted-foreground",children:i.delivery_method})}),e.jsx("td",{className:"px-4 py-3 text-right",children:e.jsxs(Ws,{children:[e.jsx(Vs,{asChild:!0,children:e.jsx(g,{variant:"ghost",size:"icon",className:"h-8 w-8",children:e.jsx(Pn,{className:"h-4 w-4"})})}),e.jsxs($s,{align:"end",children:[i.pdf_path&&e.jsxs(wt,{onClick:()=>s(i),children:[e.jsx(vs,{className:"mr-2 h-4 w-4"}),"Download PDF"]}),i.status!=="void"&&e.jsxs(wt,{onClick:()=>a(i),children:[e.jsx($t,{className:"mr-2 h-4 w-4"}),"Send / Forward Email"]}),i.status!=="paid"&&i.status!=="void"&&e.jsxs(wt,{onClick:()=>n(i),children:[e.jsx(vn,{className:"mr-2 h-4 w-4"}),"Mark Paid"]}),i.status!=="paid"&&i.status!=="void"&&e.jsxs(wt,{onClick:()=>r(i),className:"text-destructive",children:[e.jsx(Ca,{className:"mr-2 h-4 w-4"}),"Void"]})]})]})})]},i.id))})]}),t.length===0&&e.jsx("div",{className:"py-8 text-center text-muted-foreground",children:"No invoices found."})]})}function t2({status:t,onStatusChange:s,search:a,onSearchChange:n}){return e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(ya,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(O,{placeholder:"Search invoicesâ¦",value:a,onChange:r=>n(r.target.value),className:"pl-9"})]}),e.jsxs(qe,{value:t,onValueChange:s,children:[e.jsx(Le,{className:"w-full sm:w-[160px]",children:e.jsx(Ie,{placeholder:"All statuses"})}),e.jsxs($e,{children:[e.jsx(q,{value:"all",children:"All Statuses"}),e.jsx(q,{value:"draft",children:"Draft"}),e.jsx(q,{value:"sent",children:"Sent"}),e.jsx(q,{value:"paid",children:"Paid"}),e.jsx(q,{value:"void",children:"Void"})]})]})]})}function s2({invoice:t,open:s,onOpenChange:a}){const[n,r]=o.useState("check"),[i,l]=o.useState(""),[m,c]=o.useState(""),d=sw(),u=async()=>{if(t)try{await d.mutateAsync({id:t.id,data:{payment_method:n,reference_number:i||null,notes:m||null}}),a(!1),r("check"),l(""),c("")}catch{}};return e.jsx(Fe,{open:s,onOpenChange:a,children:e.jsxs(Te,{children:[e.jsx(Ae,{children:e.jsx(Ee,{children:"Mark Invoice as Paid"})}),t&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-md bg-muted p-3 text-sm",children:[e.jsx("div",{className:"font-medium",children:t.invoice_number}),e.jsxs("div",{className:"text-muted-foreground",children:[t.member_name," â $",Number(t.amount).toFixed(2)]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{children:"Payment method"}),e.jsxs(qe,{value:n,onValueChange:r,children:[e.jsx(Le,{children:e.jsx(Ie,{})}),e.jsxs($e,{children:[e.jsx(q,{value:"check",children:"Check"}),e.jsx(q,{value:"cash",children:"Cash"}),e.jsx(q,{value:"wire",children:"Wire Transfer"}),e.jsx(q,{value:"other",children:"Other"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{children:"Reference number"}),e.jsx(O,{placeholder:"Check #, transaction ID, etc.",value:i,onChange:h=>l(h.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{children:"Notes"}),e.jsx(It,{placeholder:"Optional notesâ¦",value:m,onChange:h=>c(h.target.value),rows:2})]})]}),e.jsxs(Ge,{children:[e.jsx(g,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(g,{onClick:u,disabled:d.isPending,children:d.isPending?"Saving...":"Mark as Paid"})]})]})})}function a2({invoice:t,open:s,onOpenChange:a}){const[n,r]=o.useState(""),i=aw(),l=async()=>
4{if(!(!t||!n.trim()))try{await i.mutateAsync({id:t.id,data:{reason:n.trim()}}),a(!1),r("")}catch{}};return e.jsx(Fe,{open:s,onOpenChange:a,children:e.jsxs(Te,{children:[e.jsxs(Ae,{children:[e.jsx(Ee,{children:"Void Invoice"}),e.jsx(tt,{children:"This action cannot be undone. The invoice will be permanently marked as void."})]}),t&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-md bg-muted p-3 text-sm",children:[e.jsx("div",{className:"font-medium",children:t.invoice_number}),e.jsxs("div",{className:"text-muted-foreground",children:[t.member_name," â $",Number(t.amount).toFixed(2)]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{children:"Reason for voiding *"}),e.jsx(It,{placeholder:"Enter reasonâ¦",value:n,onChange:m=>r(m.target.value),rows:3})]})]}),e.jsxs(Ge,{children:[e.jsx(g,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(g,{variant:"destructive",onClick:l,disabled:i.isPending||!n.trim(),children:i.isPending?"Voiding...":"Void Invoice"})]})]})})}function n2({open:t,onOpenChange:s}){const[a,n]=o.useState(null),r=lw(),{data:i}=iw(),l=i?.count??0,m=async()=>{try{const d=await r.mutateAsync();n(d)}catch{}},c=d=>{d||n(null),s(d)};return e.jsx(Fe,{open:t,onOpenChange:c,children:e.jsxs(Te,{children:[e.jsx(Ae,{children:e.jsx(Ee,{children:"Send Payment Reminders"})}),a?e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-sm",children:"Payment reminders have been processed:"}),e.jsxs("div",{className:"space-y-1 rounded-md bg-muted p-3 text-sm",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{children:"Sent:"}),e.jsx("span",{className:"font-medium",children:a.sent})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{children:"Failed:"}),e.jsx("span",{className:"font-medium",children:a.failed})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{children:"Skipped (no template):"}),e.jsx("span",{className:"font-medium",children:a.skipped})]}),e.jsxs("div",{className:"flex justify-between border-t border-border pt-1",children:[e.jsx("span",{children:"Total invoices:"}),e.jsx("span",{className:"font-medium",children:a.total})]})]}),a.skipped>0&&a.sent===0&&e.jsx("p",{className:"text-xs text-amber-600 dark:text-amber-400",children:"All reminders were skipped. Make sure you've created a PAYMENT_REMINDER email template on the Email Templates page."})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-sm",children:"This will send payment reminder emails to members with outstanding invoices."}),e.jsxs("div",{className:"rounded-md bg-muted p-3 text-sm",children:[e.jsx("span",{className:"font-medium",children:l})," outstanding invoice",l!==1?"s":""," found."]}),l===0&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"There are no outstanding invoices to send reminders for."})]}),e.jsx(Ge,{children:a?e.jsx(g,{onClick:()=>c(!1),children:"Close"}):e.jsxs(e.Fragment,{children:[e.jsx(g,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsx(g,{onClick:m,disabled:r.isPending||l===0,children:r.isPending?"Sending...":"Send Reminders"})]})})]})})}function r2(){const[t,s]=o.useState(1),[a,n]=o.useState("all"),[r,i]=o.useState(""),[l,m]=o.useState(null),[c,d]=o.useState(null),[u,h]=o.useState(null),[p,x]=o.useState(!1),{data:f,isLoading:b}=X0({page:t,status:a!=="all"?a:void 0,search:r||void 0}),N=async j=>{try{const w=await Bs.downloadPdf(j.id),v=window.URL.createObjectURL(w),k=document.createElement("a");k.href=v,k.download=`${j.invoice_number}.pdf`,k.click(),window.URL.revokeObjectURL(v)}catch{}};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(cs,{className:"h-5 w-5"})}),e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:"Invoices"})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(g,{variant:"outline",onClick:()=>x(!0),children:[e.jsx(Up,{className:"mr-2 h-4 w-4"}),"Send reminders"]}),e.jsx(g,{asChild:!0,children:e.jsxs(je,{to:"/invoices/new-batch",children:[e.jsx(Rt,{className:"mr-2 h-4 w-4"}),"New batch"]})})]})]}),e.jsx(t2,{status:a,onStatusChange:j=>{n(j),s(1)},search:r,onSearchChange:j=>{i(j),s(1)}}),e.jsx(L,{className:"min-w-0 overflow-hidden",children:e.jsx($,{className:"p-0",children:b?e.jsx("div",{className:"space-y-3 p-6",children:Array.from({length:5}).map((j,w)=>e.jsx(Y,{className:"h-12 w-full"},w))}
4):e.jsx(e2,{invoices:f?.items||[],onDownloadPdf:N,onForwardEmail:h,onMarkPaid:m,onVoid:d})})}),f&&f.pages>1&&e.jsxs("div",{className:"flex justify-center gap-2",children:[e.jsx(g,{variant:"outline",size:"sm",disabled:t<=1,onClick:()=>s(t-1),children:"Previous"}),e.jsxs("span",{className:"px-3 py-2 text-sm text-muted-foreground",children:["Page ",t," of ",f.pages]}),e.jsx(g,{variant:"outline",size:"sm",disabled:t>=f.pages,onClick:()=>s(t+1),children:"Next"})]}),e.jsx(s2,{invoice:l,open:!!l,onOpenChange:j=>!j&&m(null)}),e.jsx(a2,{invoice:c,open:!!c,onOpenChange:j=>!j&&d(null)}),e.jsx(rf,{invoice:u,open:!!u,onOpenChange:j=>!j&&h(null)}),e.jsx(n2,{open:p,onOpenChange:x})]})}function i2(){const t=kt(),{data:s}=oa(),a=ew(),n=tw(),r=nw(),[i,l]=o.useState(1),[m,c]=o.useState(""),[d,u]=o.useState(""),[h,p]=o.useState(""),[x,f]=o.useState(""),[b,N]=o.useState(""),[j,w]=o.useState(""),[v,k]=o.useState([]),[S,_]=o.useState(["active"]),[y,C]=o.useState(""),[P,A]=o.useState(!0),[E,Q]=o.useState(null),[U,D]=o.useState(null),[K,xe]=o.useState(0),z=["active","pending","grace","lapsed","expired"],ae=()=>({name:m,description:d||void 0,due_date:h,amount:parseFloat(x),membership_type_ids:v.length>0?v:void 0,member_statuses:S.length>0?S:void 0,expiring_within_days:y?parseInt(y):void 0,exclude_members_with_open_invoices:P,period_start:b||void 0,period_end:j||void 0}),ue=async()=>{try{const M=await a.mutateAsync(ae());Q(M),l(3)}catch{}},_e=async()=>{try{const M=await n.mutateAsync(ae());D(M.id),xe(M.invoice_count),l(4)}catch{}},ee=async()=>{if(U)try{const M=await Bs.downloadBatch(U),I=window.URL.createObjectURL(M),R=document.createElement("a");R.href=I,R.download=`${m.replace(/\s+/g,"_")}.zip`,R.click(),window.URL.revokeObjectURL(I)}catch{}},se=async()=>{if(U)try{await r.mutateAsync(U)}catch{}},le=m&&h&&x&&parseFloat(x)>0,oe=M=>{k(I=>I.includes(M)?I.filter(R=>R!==M):[...I,M])},Pe=M=>{_(I=>I.includes(M)?I.filter(R=>R!==M):[...I,M])};return e.jsxs("div",{className:"mx-auto max-w-3xl space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(g,{variant:"ghost",size:"icon",onClick:()=>t("/invoices"),children:e.jsx(es,{className:"h-4 w-4"})}),e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(cs,{className:"h-5 w-5"})}),e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:"New invoice batch"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[[1,2,3,4].map(M=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:`flex h-8 w-8 items-center justify-center rounded-full text-sm font-medium ${M===i?"bg-primary text-primary-foreground":M<i?"bg-primary/20 text-primary":"bg-muted text-muted-foreground"}`,children:M<i?e.jsx(Xt,{className:"h-4 w-4"}):M}),M<4&&e.jsx("div",{className:`h-0.5 w-8 ${M<i?"bg-primary/40":"bg-muted"}`})]},M)),e.jsxs("span",{className:"ml-2 text-sm text-muted-foreground",children:[i===1&&"Details",i===2&&"Criteria",i===3&&"Preview",i===4&&"Done"]})]}),i===1&&e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(cs,{className:"h-4 w-4"})}),"Invoice details"]})}),e.jsxs($,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{children:"Batch name *"}),e.jsx(O,{placeholder:"e.g. 2026 Annual Dues",value:m,onChange:M=>c(M.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{children:"Description"}),e.jsx(It,{placeholder:"Optional descriptionâ¦",value:d,onChange:M=>u(M.target.value),rows:2})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{children:"Due date *"}),e.jsx(O,{type:"date",value:h,onChange:M=>p(M.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{children:"Amount per invoice *"}),e.jsx(O,{type:"number",step:"0.01",min:"0",placeholder:"0.00",value:x,onChange:M=>f(M.target.value)})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{children:"Period start"}),e.jsx(O,{type:"date",value:b,onChange:M=>N(M.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{children:"Period end"}),e.jsx(O,{type:"date",value:j,onChange:M=>w(M.target.value)})]})]}),e.jsx("div",{className:"flex justify-end",children:e.jsxs(g,{onClick:()=>l(2),disabled:!le,children:["Next ",e.jsx(as,{className:"ml-2 h-4 w-4"})]})})]})]}),i===2&&e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy
4/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(cn,{className:"h-4 w-4"})}),"Select recipients"]})}),e.jsxs($,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(T,{children:"Membership types"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:s?.map(M=>e.jsx(g,{variant:v.includes(M.id)?"default":"outline",size:"sm",onClick:()=>oe(M.id),children:M.name},M.id))}),v.length===0&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"No types selected = all types"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(T,{children:"Member statuses"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:z.map(M=>e.jsx(g,{variant:S.includes(M)?"default":"outline",size:"sm",onClick:()=>Pe(M),children:M},M))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{children:"Expiring within N days"}),e.jsx(O,{type:"number",min:"0",placeholder:"Leave blank for no filter",value:y,onChange:M=>C(M.target.value),className:"max-w-[200px]"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ot,{id:"exclude-open",checked:P,onCheckedChange:M=>A(!!M)}),e.jsx(T,{htmlFor:"exclude-open",className:"font-normal",children:"Exclude members with open invoices"})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsxs(g,{variant:"outline",onClick:()=>l(1),children:[e.jsx(es,{className:"mr-2 h-4 w-4"})," Back"]}),e.jsx(g,{onClick:ue,disabled:a.isPending,children:a.isPending?e.jsxs(e.Fragment,{children:[e.jsx(He,{className:"mr-2 h-4 w-4 animate-spin"})," Loadingâ¦"]}):e.jsxs(e.Fragment,{children:["Preview ",e.jsx(as,{className:"ml-2 h-4 w-4"})]})})]})]})]}),i===3&&E&&e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(ca,{className:"h-4 w-4"})}),"Preview"]})}),e.jsxs($,{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"rounded-lg bg-muted p-4 text-center",children:[e.jsx("div",{className:"text-2xl font-semibold tracking-tight",children:E.total_members}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Members"})]}),e.jsxs("div",{className:"rounded-lg bg-muted p-4 text-center",children:[e.jsxs("div",{className:"text-2xl font-semibold tracking-tight",children:["$",Number(E.total_amount).toFixed(2)]}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Total amount"})]})]}),E.skipped.length>0&&e.jsxs("div",{className:"rounded-lg border border-amber-200 bg-amber-50 p-3 dark:border-amber-800 dark:bg-amber-950/20",children:[e.jsxs("p",{className:"mb-2 text-sm font-medium text-amber-800 dark:text-amber-200",children:[E.skipped.length," member(s) skipped"]}),e.jsx("div",{className:"space-y-1",children:E.skipped.map(M=>e.jsxs("div",{className:"text-xs text-amber-700 dark:text-amber-300",children:[M.first_name," ",M.last_name," â ",M.reason]},M.id))})]}),e.jsx("div",{className:"max-h-64 overflow-y-auto rounded-lg border",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"sticky top-0 bg-muted/30",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-3 py-2 text-left text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Name"}),e.jsx("th",{className:"px-3 py-2 text-left text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Email"}),e.jsx("th",{className:"px-3 py-2 text-left text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Type"}),e.jsx("th",{className:"px-3 py-2 text-left text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Status"})]})}),e.jsx("tbody",{children:E.members.map(M=>e.jsxs("tr",{className:"border-t hover:bg-brand-navy/[0.04] dark:hover:bg-brand-navy/10",children:[e.jsxs("td",{className:"px-3 py-2",children:[M.first_name," ",M.last_name]}),e.jsx("td",{className:"px-3 py-2 text-muted-foreground",children:M.email}),e.jsx("td",{className:"px-3 py-2",children:M.membership_type_name||"â"}),e.jsx("td",{className:"px-3 py-2",children:e.jsxs("span",{className:"inline-flex items-center gap-1.5 whitespace-nowrap capitalize",children:[e.jsx("span",{className:`h-1.5 w-1.5 shrink-0 rounded-full ${M.status==="active"?"bg-emerald-500":M.status==="pending"?"bg-amber-500":M.status==="grace"?"bg-orange-500":M.status==="lapsed"||M.status==="expired"?"bg-red-500":"bg-muted-foreground
4/60"}`}),e.jsx("span",{className:"text-xs font-medium",children:M.status})]})})]},M.id))})]})}),e.jsxs("div",{className:"flex justify-between",children:[e.jsxs(g,{variant:"outline",onClick:()=>l(2),children:[e.jsx(es,{className:"mr-2 h-4 w-4"})," Back"]}),e.jsx(g,{onClick:_e,disabled:n.isPending||E.total_members===0,children:n.isPending?e.jsxs(e.Fragment,{children:[e.jsx(He,{className:"mr-2 h-4 w-4 animate-spin"})," Creatingâ¦"]}):e.jsxs(e.Fragment,{children:["Create ",E.total_members," invoices"]})})]})]})]}),i===4&&e.jsx(L,{className:"min-w-0 overflow-hidden",children:e.jsxs($,{className:"space-y-6 py-12 text-center",children:[e.jsx("div",{className:"inline-flex h-16 w-16 items-center justify-center rounded-full bg-emerald-100 dark:bg-emerald-900/30",children:e.jsx(Xt,{className:"h-8 w-8 text-emerald-600 dark:text-emerald-400"})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-semibold tracking-tight",children:"Batch created"}),e.jsxs("p",{className:"mt-1 text-muted-foreground",children:[K," invoices generated with PDFs"]})]}),e.jsxs("div",{className:"flex justify-center gap-3",children:[e.jsxs(g,{variant:"outline",onClick:ee,children:[e.jsx(vs,{className:"mr-2 h-4 w-4"}),"Download all (ZIP)"]}),e.jsx(g,{onClick:se,disabled:r.isPending,children:r.isPending?e.jsxs(e.Fragment,{children:[e.jsx(He,{className:"mr-2 h-4 w-4 animate-spin"})," Sendingâ¦"]}):e.jsxs(e.Fragment,{children:[e.jsx($t,{className:"mr-2 h-4 w-4"})," Email all"]})})]}),e.jsx(g,{variant:"link",onClick:()=>t("/invoices"),children:"Go to invoices"})]})})]})}function l2(){return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(en,{className:"h-5 w-5"})}),e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:"Import / export"})]}),e.jsxs(Ur,{defaultValue:"import",children:[e.jsxs(ir,{children:[e.jsxs(bs,{value:"import",children:[e.jsx(en,{className:"mr-2 h-4 w-4"}),"Import"]}),e.jsxs(bs,{value:"export",children:[e.jsx(vs,{className:"mr-2 h-4 w-4"}),"Export"]}),e.jsx(bs,{value:"memberclicks",children:"MemberClicks"})]}),e.jsx(js,{value:"import",children:e.jsx(o2,{})}),e.jsx(js,{value:"export",children:e.jsx(u2,{})}),e.jsx(js,{value:"memberclicks",children:e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(en,{className:"h-4 w-4"})}),"MemberClicks import"]})}),e.jsxs($,{className:"space-y-2",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"MemberClicks import is now managed from the Platform Admin."}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Go to"," ",e.jsx("span",{className:"font-medium text-foreground",children:"Platform Admin â Societies â Edit â Integrations"})," ","tab to connect MemberClicks, configure mappings, and run imports."]})]})]})})]})]})}function o2(){const[t,s]=o.useState("upload"),[a,n]=o.useState(null),[r,i]=o.useState(!1),[l,m]=o.useState(!1),[c,d]=o.useState(null),[u,h]=o.useState(null),[p,x]=o.useState(!1),[f,b]=o.useState(null),[N,j]=o.useState("active"),w=ow(),v=cw(),k=()=>{a&&w.mutate({file:a,updateExisting:r,allowBlankEmail:l},{onSuccess:y=>{d(y),s("preview")}})},S=()=>{a&&v.mutate({file:a,options:{update_existing:r,send_welcome_emails:p,default_membership_type_id:f??void 0,default_status:N,allow_blank_email:l}},{onSuccess:y=>{h(y),s("results")}})},_=()=>{s("upload"),n(null),d(null),h(null),i(!1),m(!1),x(!1),b(null),j("active"),w.reset(),v.reset()};return t==="results"&&u?e.jsx(m2,{result:u,onReset:_}):t==="preview"&&c?e.jsx(d2,{preview:c,sendWelcomeEmails:p,setSendWelcomeEmails:x,defaultMembershipTypeId:f,setDefaultMembershipTypeId:b,defaultStatus:N,setDefaultStatus:j,onImport:S,onBack:()=>s("upload"),isImporting:v.isPending,importError:v.error}):e.jsx(c2,{file:a,setFile:n,updateExisting:r,setUpdateExisting:i,allowBlankEmail
4:l,setAllowBlankEmail:m,onPreview:k,isPreviewing:w.isPending,previewError:w.error})}function c2({file:t,setFile:s,updateExisting:a,setUpdateExisting:n,allowBlankEmail:r,setAllowBlankEmail:i,onPreview:l,isPreviewing:m,previewError:c}){const d=o.useRef(null),[u,h]=o.useState(!1),p=f=>{if(f.size>10*1024*1024){alert("File must be under 10MB");return}if(!f.name.endsWith(".csv")){alert("Only CSV files are supported");return}s(f)},x=o.useCallback(f=>{f.preventDefault(),h(!1);const b=f.dataTransfer.files[0];b&&p(b)},[s]);return e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(Lt,{className:"h-4 w-4"})}),"Import members"]})}),e.jsxs($,{className:"space-y-6",children:[e.jsxs("div",{className:`cursor-pointer rounded-lg border-2 border-dashed p-8 text-center transition-colors ${u?"border-primary bg-primary/5":t?"border-emerald-500 bg-emerald-50 dark:bg-emerald-950/20":"border-border hover:border-primary/50"}`,onDragOver:f=>{f.preventDefault(),h(!0)},onDragLeave:()=>h(!1),onDrop:x,onClick:()=>d.current?.click(),children:[e.jsx("input",{ref:d,type:"file",accept:".csv",className:"hidden",onChange:f=>{const b=f.target.files?.[0];b&&p(b)}}),t?e.jsxs("div",{className:"space-y-2",children:[e.jsx(Kt,{className:"mx-auto h-8 w-8 text-emerald-500"}),e.jsx("p",{className:"font-medium",children:t.name}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[(t.size/1024).toFixed(1)," KB â Click or drop to replace"]})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(en,{className:"mx-auto h-8 w-8 text-muted-foreground"}),e.jsx("p",{className:"font-medium",children:"Drop a CSV file here, or click to browse"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"CSV only, max 10MB"})]})]}),e.jsxs("button",{type:"button",className:"inline-flex items-center gap-1 text-sm text-primary hover:underline",onClick:()=>$a.downloadTemplate(),children:[e.jsx(Bb,{className:"h-4 w-4"}),"Download CSV template"]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(ot,{id:"update-existing",checked:a,onCheckedChange:f=>n(f===!0)}),e.jsx(T,{htmlFor:"update-existing",children:"Update existing members by email"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(ot,{id:"allow-blank-email",checked:r,onCheckedChange:f=>i(f===!0)}),e.jsxs("div",{children:[e.jsx(T,{htmlFor:"allow-blank-email",children:"Allow members without email"}),e.jsx("p",{className:"mt-0.5 text-xs text-muted-foreground",children:"Members without an email will get a placeholder address and won't be able to log into the portal"})]})]}),c&&e.jsxs("div",{className:"flex items-start gap-2 rounded-md bg-destructive/10 p-3 text-sm text-destructive",children:[e.jsx(Dt,{className:"mt-0.5 h-4 w-4 shrink-0"}),c?.response?.data?.detail||c.message]}),e.jsx(g,{onClick:l,disabled:!t||m,children:m?"Analyzingâ¦":"Preview"})]})]})}function d2({preview:t,sendWelcomeEmails:s,setSendWelcomeEmails:a,defaultMembershipTypeId:n,setDefaultMembershipTypeId:r,defaultStatus:i,setDefaultStatus:l,onImport:m,onBack:c,isImporting:d,importError:u}){const{data:h}=oa(),[p,x]=o.useState(!1);return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4 md:grid-cols-4",children:[e.jsx(wn,{label:"Total Rows",value:t.total_rows}),e.jsx(wn,{label:"New Members",value:t.new_members,variant:"success"}),e.jsx(wn,{label:"Existing Members",value:t.existing_members,variant:"info"}),e.jsx(wn,{label:"Errors",value:t.error_rows,variant:t.error_rows>0?"danger":"default"})]}),t.errors.length>0&&e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"cursor-pointer pb-3",onClick:()=>x(!p),children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight text-destructive",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-red-100 text-red-600 dark:bg-red-900/30 dark:text-red-400",children:e.jsx(Bt,{className:"h-4 w-4"})}),t.errors.length," row",t.errors.length!==1?"s":""," with validation errors"]}),p?e.jsx(Gn,{className:"h-4 w-4"}):e.jsx(ps,{className:"h-4 w-4"})]})}),p&&e.jsx($,{children:e.jsxs(Pt,{children:[e.jsx(At,{className:"bg-muted/30",children:e.jsxs(Ue,{className:"hover:bg-transparent",children:[e.jsx(H,{className:"h-10 w-16 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground
4/80",children:"Row"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Row data"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Issues"})]})}),e.jsx(Et,{children:t.errors.map((f,b)=>{const N=f.data||{},j=f.errors||[],w=[N.email,N.first_name,N.last_name].filter(Boolean).join(", ");return e.jsxs(Ue,{className:"hover:bg-brand-navy/[0.04] dark:hover:bg-brand-navy/10",children:[e.jsx(G,{className:"font-mono text-xs",children:f.row}),e.jsx(G,{className:"text-sm",children:w||e.jsx("span",{className:"italic text-muted-foreground",children:"empty row"})}),e.jsx(G,{children:e.jsx("div",{className:"flex flex-col gap-1",children:j.map((v,k)=>e.jsxs("span",{className:"text-sm",children:[e.jsxs("span",{className:"mr-1.5 inline-flex items-center gap-1.5 whitespace-nowrap",children:[e.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-red-500"}),e.jsx("span",{className:"text-xs font-medium",children:v.field||"row"})]}),v.error]},k))})})]},b)})})]})})]}),t.sample_data.length>0&&e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(ca,{className:"h-4 w-4"})}),"Sample data (first ",t.sample_data.length," rows)"]})}),e.jsx($,{className:"overflow-x-auto",children:e.jsxs(Pt,{children:[e.jsx(At,{className:"bg-muted/30",children:e.jsx(Ue,{className:"hover:bg-transparent",children:Object.keys(t.sample_data[0]).map(f=>e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:f},f))})}),e.jsx(Et,{children:t.sample_data.map((f,b)=>e.jsx(Ue,{className:"hover:bg-brand-navy/[0.04] dark:hover:bg-brand-navy/10",children:Object.values(f).map((N,j)=>e.jsx(G,{children:N==null?"":typeof N=="object"?JSON.stringify(N):String(N)},j))},b))})]})})]}),e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(cn,{className:"h-4 w-4"})}),"Import options"]})}),e.jsxs($,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(ot,{id:"send-welcome",checked:s,onCheckedChange:f=>a(f===!0)}),e.jsx(T,{htmlFor:"send-welcome",children:"Send welcome emails to new members"})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-4 md:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{children:"Default membership type"}),e.jsx(Ss,{value:n,onChange:r,noneLabel:"None (use CSV value)",placeholder:"None (use CSV value)",children:(h||[]).map(f=>e.jsx(q,{value:f.id,children:f.name},f.id))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{children:"Default status"}),e.jsxs(qe,{value:i,onValueChange:l,children:[e.jsx(Le,{children:e.jsx(Ie,{})}),e.jsxs($e,{children:[e.jsx(q,{value:"active",children:"Active"}),e.jsx(q,{value:"pending",children:"Pending"}),e.jsx(q,{value:"grace",children:"Grace"})]})]})]})]})]})]}),u&&e.jsxs("div",{className:"flex items-start gap-2 rounded-md bg-destructive/10 p-3 text-sm text-destructive",children:[e.jsx(Dt,{className:"mt-0.5 h-4 w-4 shrink-0"}),u?.response?.data?.detail||u.message]}),e.jsxs("div",{className:"flex gap-3",children:[e.jsx(g,{variant:"outline",onClick:c,disabled:d,children:"Back"}),e.jsx(g,{onClick:m,disabled:d,children:d?"Importingâ¦":"Import"})]})]})}function wn({label:t,value:s,variant:a="default"}){const n={default:"text-foreground",success:"text-emerald-600 dark:text-emerald-400",info:"text-blue-600 dark:text-blue-400",danger:"text-destructive"};return e.jsx(L,{className:"min-w-0 overflow-hidden",children:e.jsxs($,{className:"pt-6",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:t}),e.jsx("p",{className:`text-2xl font-semibold tracking-tight ${n[a]}`,children:s})]})})}function m2({result:t,onReset:s}){return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-start gap-2 rounded-md bg-emerald-50 p-4 text-emerald-800 dark:bg-emerald-950/20 dark:text-emerald-200",children:[e.jsx(Kt,{className:"mt-0.5 h-5 w-5 shrink-0"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Import complete"}),e.jsxs("p",{className:"text-sm",children:[t.total_processed," rows processed"]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4 md:grid-cols-4",children:[e.jsx(wn,{label:"Created",value:t.created,variant:"success"}),e.jsx(wn,{label:"Updated",value:t.updated,variant:"info"}),e.jsx(wn,{label:"Skipped",value:t.skipped}),e.jsx(wn,{label:"Failed",value:t.failed,variant:t.failed>0?"danger":"default"})]}),t.errors.length>0&&e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight text-destructive",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-red-100 text-red-600 dark:bg-red-900/30 dark:text-red-400",children:e.jsx(Bt,{className:"h-4 w-4"})}),t.errors.length," failure",t.errors.length!==1?"s":""]})}),e.jsx($,{children:e.jsxs(Pt,{children:[e.jsx(At,{className:"bg-muted/30",children:e.jsxs(Ue,{className:"hover:bg-transparent",children:[e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground
4/80",children:"Row"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Email"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Error"})]})}),e.jsx(Et,{children:t.errors.map((a,n)=>e.jsxs(Ue,{className:"hover:bg-brand-navy/[0.04] dark:hover:bg-brand-navy/10",children:[e.jsx(G,{children:a.row}),e.jsx(G,{children:a.email}),e.jsx(G,{children:a.error})]},n))})]})})]}),e.jsx(g,{onClick:s,children:"Import another"})]})}function u2(){return e.jsxs("div",{className:"space-y-6",children:[e.jsx(h2,{}),e.jsx(p2,{})]})}function h2(){const[t,s]=o.useState("csv"),[a,n]=o.useState([]),[r,i]=o.useState(""),[l,m]=o.useState(!1),{data:c}=oa(),d=dw(),u=p=>{n(x=>x.includes(p)?x.filter(f=>f!==p):[...x,p])},h=()=>{d.mutate({format:t,status:a.length>0?a:void 0,membership_type_id:r||void 0,include_custom_fields:l||void 0})};return e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(Lt,{className:"h-4 w-4"})}),"Export members"]})}),e.jsxs($,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{children:"Format"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(g,{variant:t==="csv"?"default":"outline",size:"sm",onClick:()=>s("csv"),children:"CSV"}),e.jsx(g,{variant:t==="xlsx"?"default":"outline",size:"sm",onClick:()=>s("xlsx"),children:"XLSX"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{children:"Filter by status"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:["active","pending","grace","lapsed","cancelled"].map(p=>{const x=a.includes(p),f=p==="active"?"bg-emerald-500":p==="pending"?"bg-amber-500":p==="grace"?"bg-orange-500":p==="lapsed"?"bg-red-500":"bg-muted-foreground/60";return e.jsxs("button",{type:"button",onClick:()=>u(p),className:`inline-flex cursor-pointer items-center gap-1.5 whitespace-nowrap rounded-full border px-2.5 py-1 capitalize transition-colors ${x?"border-foreground
4/30 bg-muted":"border-border hover:bg-muted/50"}`,children:[e.jsx("span",{className:`h-1.5 w-1.5 shrink-0 rounded-full ${f}`}),e.jsx("span",{className:"text-xs font-medium",children:p})]},p)})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{children:"Membership type"}),e.jsxs(qe,{value:r,onValueChange:i,children:[e.jsx(Le,{children:e.jsx(Ie,{placeholder:"All types"})}),e.jsxs($e,{children:[e.jsx(q,{value:"all",children:"All types"}),(c||[]).map(p=>e.jsx(q,{value:p.id,children:p.name},p.id))]})]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(ot,{id:"include-custom-fields",checked:l,onCheckedChange:p=>m(p===!0)}),e.jsx(T,{htmlFor:"include-custom-fields",children:"Include custom fields"})]}),d.error&&e.jsxs("div",{className:"flex items-start gap-2 rounded-md bg-destructive/10 p-3 text-sm text-destructive",children:[e.jsx(Dt,{className:"mt-0.5 h-4 w-4 shrink-0"}),d.error?.response?.data?.detail||d.error.message]}),e.jsxs(g,{onClick:h,disabled:d.isPending,children:[e.jsx(vs,{className:"mr-2 h-4 w-4"}),d.isPending?"Exportingâ¦":"Export members"]})]})]})}function p2(){const[t,s]=o.useState("csv"),[a,n]=o.useState(""),[r,i]=o.useState(""),l=mw(),m=()=>{l.mutate({format:t,date_from:a||void 0,date_to:r||void 0})};return e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(Qt,{className:"h-4 w-4"})}),"Export payments"]})}),e.jsxs($,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{children:"Format"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(g,{variant:t==="csv"?"default":"outline",size:"sm",onClick:()=>s("csv"),children:"CSV"}),e.jsx(g,{variant:t==="xlsx"?"default":"outline",size:"sm",onClick:()=>s("xlsx"),children:"XLSX"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-4 md:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"date-from",children:"From"}),e.jsx(O,{id:"date-from",type:"date",value:a,onChange:c=>n(c.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"date-to",children:"To"}),e.jsx(O,{id:"date-to",type:"date",value:r,onChange:c=>i(c.target.value)})]})]}),l.error&&e.jsxs("div",{className:"flex items-start gap-2 rounded-md bg-destructive/10 p-3 text-sm text-destructive",children:[e.jsx(Dt,{className:"mt-0.5 h-4 w-4 shrink-0"}),l.error?.response?.data?.detail||l.error.message]}),e.jsxs(g,{onClick:m,disabled:l.isPending,children:[e.jsx(vs,{className:"mr-2 h-4 w-4"}),l.isPending?"Exportingâ¦":"Export payments"]})]})]})}function Cc(t){return t>0?`${t} days before`:t===0?"Day of expiry":`${Math.abs(t)} days after`}const x2={all:"All members",manual_renew:"Manual renew",auto_renew:"Auto renew",lapsed:"Lapsed only"},g2={all:"bg-muted-foreground/60",manual_renew:"bg-muted-foreground/60",auto_renew:"bg-emerald-500",lapsed:"bg-orange-500"},Wm={template_id:"",days_offset:30,direction:"before",send_to:"all",is_active:!0};function f2(){const[t,s]=o.useState(1),[a,n]=o.useState(!1),[r,i]=o.useState(null),[l,m]=o.useState(null),[c,d]=o.useState(Wm),{data:u,isLoading:h}=tg(),{data:p}=Jx({templateType:"renewal_sequence"}),{data:x,isLoading:f}=fw({page:t,size:10}),b=uw(),N=hw(),j=pw(),w=xw(),v=()=>{i(null),d(Wm),n(!0)},k=D=>{i(D),d({template_id:D.template_id,days_offset:Math.abs(D.days_offset),direction:D.days_offset>=0?"before":"after",send_to:D.send_to,is_active:D.is_active}),n(!0)},S=async()=>{const D=c.direction==="before"?c.days_offset:-c.days_offset;r?await N.mutateAsync({id:r.id,data:{template_id:c.template_id,days_offset:D,send_to:c.send_to,is_active:c.is_active}}):await b.mutateAsync({template_id:c.template_id,days_offset:D,send_to:c.send_to,is_active:c.is_active}),n(!1)},_=async D=>{await N.mutateAsync({id:D.id,data:{is_active:!D.is_active}})},y=async()=>{l&&(await j.mutateAsync(l.id),m(null))},C=async()=>{await w.mutateAsync()},P=u&&u.length>0,A=b.isPending||N.isPending,E=u?.filter(D=>D.days_offset>0)||[],Q=u?.filter(D=>D.days_offset===0)||[],U=u?.filter(D=>D.days_offset<0)||[];return e.jsx(nr,{tourIds:["renewal-sequence"],children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Tn,{}),e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-brand-navy
4/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(St,{className:"h-5 w-5"})}),e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:"Renewal sequence"})]}),e.jsx("p",{className:"mt-2 text-sm text-muted-foreground sm:text-base",children:"Configure automated email touchpoints before and after membership expiry"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[!P&&!h&&e.jsxs(g,{variant:"outline",onClick:C,disabled:w.isPending,children:[e.jsx(St,{className:"mr-2 h-4 w-4"}),w.isPending?"Applyingâ¦":"Apply defaults"]}),e.jsxs(g,{onClick:v,"data-tour":"renewal-add-step",children:[e.jsx(Rt,{className:"mr-2 h-4 w-4"}),"Add step"]})]})]}),e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(Yt,{className:"h-4 w-4"})}),"Sequence timeline"]})}),e.jsx($,{className:"p-0","data-tour":"renewal-steps",children:h?e.jsx("div",{className:"space-y-3 p-6",children:Array.from({length:5}).map((D,K)=>e.jsx(Y,{className:"h-12 w-full"},K))}):P?e.jsxs(Pt,{children:[e.jsx(At,{className:"bg-muted/30",children:e.jsxs(Ue,{className:"hover:bg-transparent",children:[e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Timing"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Template"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Audience"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Active"}),e.jsx(H,{className:"h-10 text-right text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Actions"})]})}),e.jsxs(Et,{children:[E.map(D=>e.jsx(qo,{step:D,onToggle:_,onEdit:k,onDelete:m},D.id)),E.length>0&&(Q.length>0||U.length>0)&&e.jsx(Ue,{children:e.jsx(G,{colSpan:5,className:"px-4 py-1",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex-1 border-t border-dashed border-muted-foreground/30"}),e.jsx("span",{className:"text-xs font-medium uppercase tracking-wider text-muted-foreground",children:"Expiry Date"}),e.jsx("div",{className:"flex-1 border-t border-dashed border-muted-foreground/30"})]})})}),Q.map(D=>e.jsx(qo,{step:D,onToggle:_,onEdit:k,onDelete:m},D.id)),U.map(D=>e.jsx(qo,{step:D,onToggle:_,onEdit:k,onDelete:m},D.id))]})]}):e.jsxs("div",{className:"py-12 text-center",children:[e.jsx("p",{className:"text-muted-foreground",children:"No renewal sequence steps configured."}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:'Click "Apply defaults" to create a recommended 9-step sequence, or add steps manually.'})]})})]}),e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx($t,{className:"h-4 w-4"})}),"Recent notifications"]})}),e.jsx($,{className:"p-0",children:f?e.jsx("div",{className:"space-y-3 p-6",children:Array.from({length:3}).map((D,K)=>e.jsx(Y,{className:"h-10 w-full"},K))}):!x||x.items.length===0?e.jsx("div",{className:"py-8 text-center",children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"No notifications sent yet."})}):e.jsxs(e.Fragment,{children:[e.jsxs(Pt,{children:[e.jsx(At,{className:"bg-muted/30",children:e.jsxs(Ue,{className:"hover:bg-transparent",children:[e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Sent at"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground
4/80",children:"Member"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Template"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Timing"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Email status"})]})}),e.jsx(Et,{children:x.items.map(D=>e.jsxs(Ue,{className:"hover:bg-brand-navy/[0.04] dark:hover:bg-brand-navy/10",children:[e.jsx(G,{className:"text-sm",children:Ct(D.sent_at).toLocaleDateString()}),e.jsxs(G,{children:[e.jsx("div",{className:"text-sm font-medium",children:D.member_name||"â"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:D.member_email})]}),e.jsx(G,{className:"text-sm",children:D.template_name||"â"}),e.jsx(G,{className:"text-sm",children:D.step_days_offset!=null?Cc(D.step_days_offset):"â"}),e.jsx(G,{children:D.email_status==="sent"?e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-emerald-500","aria-hidden":"true"}),e.jsx("span",{className:"text-xs font-medium capitalize text-foreground/85",children:D.email_status})]}):D.email_status==="failed"?e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-red-500","aria-hidden":"true"}),e.jsx("span",{className:"text-xs font-medium capitalize text-foreground/85",children:D.email_status})]}):e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-muted-foreground/60","aria-hidden":"true"}),e.jsx("span",{className:"text-xs font-medium capitalize text-foreground/85",children:D.email_status||"unknown"})]})})]},D.id))})]}),x.pages>1&&e.jsxs("div",{className:"flex items-center justify-between border-t px-4 py-3",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Page ",x.page," of ",x.pages," (",x.total," total)"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(g,{variant:"outline",size:"sm",disabled:t<=1,onClick:()=>s(D=>D-1),children:"Previous"}),e.jsx(g,{variant:"outline",size:"sm",disabled:t>=x.pages,onClick:()=>s(D=>D+1),children:"Next"})]})]})]})})]}),e.jsx(Fe,{open:a,onOpenChange:n,children:e.jsxs(Te,{children:[e.jsxs(Ae,{children:[e.jsx(Ee,{children:r?"Edit step":"Add step"}),e.jsx(tt,{children:r?"Update this renewal sequence step.":"Add a new email touchpoint to the renewal sequence."})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{children:"Days"}),e.jsx(O,{type:"number",min:0,max:365,value:c.days_offset,onChange:D=>d({...c,days_offset:parseInt(D.target.value)||0})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{children:"Direction"}),e.jsxs(qe,{value:c.direction,onValueChange:D=>d({...c,direction:D}),children:[e.jsx(Le,{children:e.jsx(Ie,{})}),e.jsxs($e,{children:[e.jsx(q,{value:"before",children:"Before expiry"}),e.jsx(q,{value:"after",children:"After expiry"})]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{children:"Template"}),e.jsxs(qe,{value:c.template_id,onValueChange:D=>d({...c,template_id:D}),children:[e.jsx(Le,{children:e.jsx(Ie,{placeholder:"Select a templateâ¦"})}),e.jsx($e,{children:p?.map(D=>e.jsx(q,{value:D.id,children:D.name},D.id))})]}),c.template_id&&e.jsx(je,{to:`/emails/templates/${c.template_id}`,className:"text-xs text-primary hover:underline",children:"Edit template"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{children:"Audience"}),e.jsxs(qe,{value:c.send_to,onValueChange:D=>d({...c,send_to:D}),children:[e.jsx(Le,{children:e.jsx(Ie,{})}),e.jsxs($e,{children:[e.jsx(q,{value:"all",children:"All members"}),e.jsx(q,{value:"manual_renew",children:"Manual renew only"}),e.jsx(q,{value:"auto_renew",children:"Auto renew only"}),e.jsx(q,{value:"lapsed",children:"Lapsed only"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ss,{checked:c.is_active,onCheckedChange:D=>d({...c,is_active:D})}),e.jsx(T,{children:"Active"})]})]}),e.jsxs(Ge,{children:[e.jsx(g,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsx(g,{onClick:S,disabled:!c.template_id||A,children:A?"Savingâ¦":r?"Update":"Create"})]})]})}),e.jsx(Fe,{open:!!l,onOpenChange:D=>!D&&m(null),children:e.jsxs(Te,{children:[e.jsxs(Ae,{children:[e.jsx(Ee,{children:"Delete step"}),e.jsxs(tt,{children:['Are you sure you want to delete the "',l?.template_name,'" step (',l?Cc(l.days_offset):"",")? This cannot be undone."]})]}),e.jsxs(Ge,{children:[e.jsx(g,{variant:"outline",onClick:()=>m(null),children:"Cancel"}),e.jsx(g,{variant:"destructive",onClick:y,disabled:j.isPending,children:j.isPending?"Deletingâ¦":"Delete"})]})]})})]})})}function qo({step:t,onToggle:s,onEdit:a,onDelete:n}){return e.jsxs(Ue,{className:t.is_active?"":"opacity-50",children:[e.jsx(G,{className:"font-medium",children:Cc(t.days_offset)}),e.jsx(G,{children:t.template_name?e.jsx(je,{to:`/emails/templates/${t.template_id}`,className:"text-sm text-primary hover:underline",children:t.template_name}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"No template"})}),e.jsx(G,{children:e.jsxs("span",{className:"inline-flex items-center gap-1.5 whitespace-nowrap",children:[e.jsx("span",{className:`h-1.5 w-1.5 shrink-0 rounded-full ${g2[t.send_to]}`}),e.jsx("span",{className:"text-xs font-medium",children:x2[t.send_to]})]})}),e.jsx(G,{children:e.jsx(ss,{checked:t.is_active,onCheckedChange:()=>s(t)})}),e.jsx(G,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-1",children:[e.jsx(g,{variant:"ghost",size:"sm",onClick:()=>a(t),children:e.jsx(Hs,{className:"h-4 w-4"})}),e.jsx(g,{variant:"ghost",size:"sm",onClick:()=>n(t),children:e.jsx(Ft,{className:"h-4 w-4 text-destructive"})})]})})]})}const po={list:async t=>(await F.get("/commerce/event-form-templates",{params:{society_id:t}})).data,create:async(t,s)=>(await F.post("/commerce/event-form-templates",t,{params:{society_id:s}})).data,update:async(t,s,a)=>(await F.patch(`/commerce/event-form-templates/${t}`,s,{params:{society_id:a}})).data,delete:async(t,s)=>{await F.delete(`/commerce/event-form-templates/${t}`,{params:{society_id:s}})}},bf={claim:async(t,s,a)=>(await F.post(`/commerce/events/${t}/registration-form/claim`,{template_id:s},{params:{society_id:a}})).data,unlink:async(t,s)=>(await F.post(`/commerce/events/${t}/registration-form/unlink`,void 0,{params:{society_id:s}})).data};function y2(){const{selectedSocietyId:t}=V(),s=J();return W({mutationFn:({eventId:a,templateId:n})=>bf.claim(a,n,t),onSuccess:(a,n)=>{s.invalidateQueries({queryKey:["admin","events"]}),s.invalidateQueries({queryKey:["admin","events",n.eventId,t]}),s.invalidateQueries({queryKey:["admin","event-form-templates"]})}})}function b2(){const{selectedSocietyId:t}=V(),s=J();return W({mutationFn:a=>bf.unlink(a,t),onSuccess:(a,n)=>{s.invalidateQueries({queryKey:["admin","events"]}),s.invalidateQueries({queryKey:["admin","events",n,t]}),s.invalidateQueries({queryKey:["admin","event-form-templates"]})}})}function jf(){const{selectedSocietyId:t}=V();return re({queryKey:["admin","event-form-templates",t],queryFn:()=>po.list(t),enabled:!!t})}function vf(){const{selectedSocietyId:t}=V(),s=J();return W({mutationFn:a=>po.create(a,t),onSuccess:()=>s.invalidateQueries({queryKey:["admin","event-form-templates"]})})}function j2(){const{selectedSocietyId:t}=V(),s=J();return W({mutationFn:({templateId:a,data:n})=>po.update(a,n,t),onSuccess:()=>s.invalidateQueries({queryKey:["admin","event-form-templates"]})})}function v2(){const{selectedSocietyId:t}=V(),s=J();return W({mutationFn:a=>po.delete(a,t),onSuccess:()=>s.invalidateQueries({queryKey:["admin","event-form-templates"]})})}const xo={list:async t=>(await F.get("/commerce/event-form-fields",{params:{society_id:t}})).data,create:async(t,s)=>(await F.post("/commerce/event-form-fields",t,{params:{society_id:s}})).data,update:async(t,s,a)=>(await F.patch(`/commerce/event-form-fields/${t}`,s,{params:{society_id:a}})).data,delete:async(t,s)=>{await F.delete(`/commerce/event-form-fields/${t}`,{params:{society_id:s}})}};function go(){const{selectedSocietyId:t}=V();return re({queryKey:["admin","event-form-fields",t],queryFn:()=>xo.list(t),enabled:!!t})}function w2(){const{selectedSocietyId:t}=V(),s=J();return W({mutationFn:a=>xo.create(a,t),onSuccess:()=>s.invalidateQueries({queryKey:["admin","event-form-fields"]})})}function wf(){const{selectedSocietyId:t}=V(),s=J();return W({mutationFn:({fieldId:a,data:n})=>xo.update(a,n,t),onSuccess:()=>s.invalidateQueries({queryKey:["admin","event-form-fields"]})})}function N2(){const{selectedSocietyId:t}=V(),s=J();return W({mutationFn:a=>xo.delete(a,t),onSuccess:()=>s.invalidateQueries({queryKey:["admin","event-form-fields"]})})}function Tl(t,s,a){return(t??[]).map(n=>{const r=n.source==="custom_field"?a?.find(i=>i.id===n.field_id):s?.find(i=>i.id===n.field_id);return r?{field_id:r.id,field_key:r.field_key,label:r.label,field_type:r.field_type,required:n.required,options:r.options??null,help_text:r.help_text??null,placeholder:r.placeholder??null,order:n.order,source:n.source??"form_field",section_id:n.section_id??null,conditional_logic:n.conditional_logic??null}:null}).filter(n=>n!==null).sort((n,r)=>n.order-r.order)}function k2({className:t,classNames:s,showOutsideDays:a=!0,...n}){return e.jsx(gj,{showOutsideDays:a,className:me("rounded-md bg-background p-3 text-foreground",t),classNames:{today:"rdp-today font-semibold underline",selected:"rdp-selected !bg-primary !text-primary-foreground hover:!bg-primary/90",...s},components:{Chevron:({orientation:r,className:i,...l})=>{const m=r==="right"?ts:Gs;return e.jsx(m,{className:me("size-4",i),...l})}},...n})}const Io=t=>{if(!t)return;const s=fj(t,"yyyy-MM-dd",new Date);return Number.isNaN(s.getTime())?void 0:s},_2=t=>Be(t,"yyyy-MM-dd");function Hr({value:t,onChange:s,min:a,max:n,placeholder:r="Pick a date",disabled:i,className:l,id:m}
4){const[c,d]=o.useState(!1),u=Io(t),h=Io(a),p=Io(n);return e.jsxs(kl,{open:c,onOpenChange:d,children:[e.jsx(_l,{asChild:!0,children:e.jsxs(g,{id:m,type:"button",variant:"outline",disabled:i,className:me("w-full justify-start text-left font-normal",!u&&"text-muted-foreground",l),children:[e.jsx(Yt,{className:"mr-2 size-4"}),u?Be(u,"PPP"):e.jsx("span",{children:r})]})}),e.jsx(hi,{className:"w-auto p-0",align:"start",children:e.jsx(k2,{mode:"single",selected:u,defaultMonth:u??h,onSelect:x=>{x&&s(_2(x)),d(!1)},disabled:x=>!!(h&&x<h||p&&x>p)})})]})}function Vm(t){return!!(t==null||typeof t=="string"&&t.trim()===""||Array.isArray(t)&&t.length===0)}function S2(t,s){if(!t)return!0;const a=s[t.field_key];let n;switch(t.operator){case"equals":n=a===t.value;break;case"not_equals":n=a!==t.value;break;case"contains":typeof a=="string"&&typeof t.value=="string"||Array.isArray(a)?n=a.includes(t.value):n=!1;break;case"is_empty":n=Vm(a);break;case"is_not_empty":n=!Vm(a);break;default:n=!1}return t.action==="show"?n:!n}function C2(t,s){let a=new Set(t.map(n=>n.field_key));for(let n=0;n<t.length;n++){const r={};for(const[l,m]of Object.entries(s))a.has(l)&&(r[l]=m);const i=new Set;for(const l of t)S2(l.conditional_logic,r)&&i.add(l.field_key);if(i.size===a.size&&[...i].every(l=>a.has(l)))return i;a=i}return a}const pi="border-amber-300 bg-amber-50 focus-visible:ring-amber-400 dark:border-amber-700/60 dark:bg-amber-950/30";function Nf(t,s){return!!(s==null||typeof s=="string"&&s.trim()===""||t.field_type==="multi_select"&&Array.isArray(s)&&s.length===0||t.field_type==="checkbox"&&s===!1)}function In(t,s){const a=C2(t,s);return t.filter(n=>a.has(n.field_key))}function On(t,s){const a=new Set;for(const n of t)n.required&&Nf(n,s[n.field_key])&&a.add(n.field_key);return a}function Pc(t,s){const a=new Set(t.map(r=>r.field_key)),n={};for(const[r,i]of Object.entries(s))a.has(r)&&(n[r]=i);return n}function kf({fields:t,sections:s,initial:a,renderActions:n,onStateChange:r}){const[i,l]=o.useState(a||{}),[m,c]=o.useState({}),d=o.useRef(a);o.useEffect(()=>{d.current!==a&&a&&(l(y=>{const C={...a};for(const[P,A]of Object.entries(y))A!=null&&A!==""&&(C[P]=A);return C}),d.current=a)},[a]);const u=(y,C)=>{l(P=>({...P,[y]:C})),c(P=>{const A={...P};return delete A[y],A})},h=o.useMemo(()=>In(t,i),[t,i]),p=o.useMemo(()=>{const y=[],C=[...s??[]].sort((A,E)=>A.order-E.order);for(const A of C){const E=h.filter(Q=>Q.section_id===A.id);E.length>0&&y.push({section:A,fields:E})}const P=h.filter(A=>!A.section_id);return P.length>0&&y.push({section:null,fields:P}),y},[s,h]),x=o.useMemo(()=>On(h,i),[h,i]),f=x.size===0,b=o.useMemo(()=>Pc(h,i),[i,h]),N=()=>b,j=x.size;o.useEffect(()=>{r?.({values:b,canSubmit:f,missingRequiredCount:j})},[b,f,j,r]);const w=(y,C)=>{const P=y.field_key,A=i[P],E=me("border-border bg-background text-foreground",C&&pi);switch(y.field_type){case"text":case"email":case"phone":case"url":return e.jsx(O,{type:y.field_type==="email"?"email":y.field_type==="phone"?"tel":y.field_type==="url"?"url":"text",value:A||"",onChange:Q=>u(P,Q.target.value),placeholder:y.placeholder||"",className:E});case"textarea":return e.jsx(It,{value:A||"",onChange:Q=>u(P,Q.target.value),placeholder:y.placeholder||"",className:E,rows:3});case"number":return e.jsx(O,{type:"number",value:A||"",onChange:Q=>u(P,Q.target.value),placeholder:y.placeholder||"",className:E});case"date":return e.jsx(O,{type:"date",value:A||"",onChange:Q=>u(P,Q.target.value),className:E});case"dropdown":return e.jsxs(qe,{value:A||"",onValueChange:Q=>u(P,Q),children:[e.jsx(Le,{className:E,children:e.jsx(Ie,{placeholder:y.placeholder||"Selectâ¦"})}),e.jsx($e,{className:"border-border bg-background",children:(y.options||[]).map(Q=>e.jsx(q,{value:Q,children:Q},Q))})]});case"multi_select":return e.jsx("div",{className:"space-y-2",children:(y.options||[]).map(Q=>{const U=Array.isArray(A)?A.includes(Q):!1;return e.jsxs("label",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(ot,{checked:U,onCheckedChange:D=>{const K=Array.isArray(A)?A:[];D?u(P,[...K,Q]):u(P,K.filter(xe=>xe!==Q))}}),Q]},Q)})});case"checkbox":return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ot,{checked:!!A,onCheckedChange:Q=>u(P,!!Q)}),e.jsx("span",{className:"text-sm text-muted-foreground",children:y.label})]});default:return e.jsx(O,{value:A||"",onChange:Q=>u(P,Q.target.value),placeholder:y.placeholder||"",className:E})}},v=y=>{const C=y.help_text&&y.help_text.trim().toLowerCase()!==(y.label||"").trim().toLowerCase(),P=x.has(y.field_key);return e.jsxs("div",{className:"space-y-1.5",children:[y.field_type!=="checkbox"&&e.jsxs(T,{className:"text-sm font-medium text-foreground",children:[y.label,y.required&&e.jsx("span",{className:"ml-0.5 text-red-500","aria-label":"required",title:"Required",children:"*"})]}),C&&e.jsx("p",{className:"text-xs leading-relaxed text-muted-foreground",children:y.help_text}),w(y,P),m[y.field_key]&&e.jsx("p",{className:"text-xs font-medium text-red-600 dark:text-red-400",children:m[y.field_key]})]},y.field_key)},k=f,S=()=>{const y={};for(const C of h)C.required&&Nf(C,i[C.field_key])&&(y[C.field_key]=`${C.label} is required`);return c(y),Object.keys(y).length===0},_=()=>(S(),N());return e.jsxs("div",{className:"space-y-6 py-2",children:[p.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No information collected."}),p.map((y,C)=>e.jsxs("div",{className:"space-y-4",children:[y.section&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("h3",{className:"text-base font-semibold tracking-tight text-foreground",children:y.section.name}),y.section.description&&e.jsx("p",{className:"text-sm text-muted-foreground",children:y.section.description})]}),e.jsx("div",{className:"space-y-4",children:y.fields.map(P=>v(P))})]},y.section?.id??`unsectioned-${C}`)),n({canSubmit:k,missingRequiredCount:x.size,getValues:_})]})}function _f({open:t,onOpenChange:s,fields:a,sections:n,eventName:r,initialValues:i,onSubmit:l}){return e.jsx(Fe,{open:t,onOpenChange:s,children:e.jsxs(Te,{className:"max-h-[90vh] overflow-y-auto border-border bg-background sm:max-w-lg",children:[e.jsxs(Ae,{children:[e.jsxs(Ee,{className:"border-border bg-background text-foreground",children:["Registration info â ",r]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Please fill out the following information to register."})]}),e.jsx(kf,{fields:a,sections:n,initial:i??{},renderActions:({canSubmit:m,getValues:c})=>e.jsxs(Ge,{children:[e.jsx(g,{variant:"outline",onClick:()=>s(!1),className:"border-border text-muted-foreground hover:bg-muted",children:"Cancel"}),m&&e.jsx(g,{onClick:()=>{l(c())},className:"bg-blue-600 font-medium text-white hover:bg-blue-700",children:"Confirm registration"})]})},t?"open":"closed")]})})}function Ac({count:t,capacity:s}){const a=s!=null&&s>0?t/s:0,n=s!=null&&t>=s?"bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400":a>=.8?"bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400":"bg-muted text-muted-foreground";return e.jsxs("span",{className:`inline-flex items-center gap-1 whitespace-nowrap rounded-full px-2 py-0.5 text-xs font-medium ${n}`,title:s!=null?`${t} of ${s} spots registered`:`${t} registered`,children:[e.jsx(Lt,{className:"h-3 w-3 shrink-0"}),t,s!=null&&e.jsxs("span",{className:"opacity-70",children:["/ ",s]}),e.jsx("span",{children:"registered"})]})}function P2(t){return{payment_method_id:t.id,brand:t.brand??"",last4:t.last4??"",exp_month:t.exp_month??0,exp_year:t.exp_year??0,is_default:!1}}
4class Sf extends Error{quote;constructor(s){super("Order requires requoting â prices or availability changed"),this.name="RequoteError",this.quote=s}}class Cf extends Error{quote;constructor(s){super("Order validation failed â review the reported issues"),this.name="InvalidBatchError",this.quote=s}}class Dn extends Error{orderId;constructor(s){super("Payment is still processing"),this.name="PaymentProcessingError",this.orderId=s}}class Pf extends Error{constructor(){super("Idempotency key was already used for a different order"),this.name="IdempotencyKeyReusedError"}}function Oo(t){if(Ta.isAxiosError(t)&&t.response){const s=t.response.data;if(s?.error_code==="requote_required"&&s.quote)throw new Sf(s.quote);if(s?.error_code==="invalid_batch"&&s.quote)throw new Cf(s.quote);if(s?.error_code==="payment_processing"&&s.order_id)throw new Dn(s.order_id);if(s?.error_code==="idempotency_key_reused")throw new Pf}throw t}const Ia={createWalkInMember:async(t,s)=>(await F.post("/commerce/admin/registration-orders/walk-in-member",t,{params:{society_id:s}})).data,getStripeConfig:async t=>(await F.get("/commerce/admin/stripe-config",{params:{society_id:t}})).data,getMemberPaymentMethods:async(t,s)=>(await F.get(`/commerce/admin/members/${t}/payment-methods`,{params:{society_id:s}})).data.map(P2),validateRegistrationOrder:async(t,s)=>(await F.post("/commerce/admin/registration-orders/validate",t,{params:{society_id:s}})).data,createRegistrationOrder:async(t,s)=>{try{return(await F.post("/commerce/admin/registration-orders",t,{params:{society_id:s}})).data}catch(a){Oo(a)}},getRegistrationOrder:async(t,s)=>(await F.get(`/commerce/admin/registration-orders/${t}`,{params:{society_id:s}})).data,findRegistrationOrderByKey:async(t,s)=>{try{return(await F.get("/commerce/admin/registration-orders",{params:{idempotency_key:t,society_id:s}})).data}catch(a){if(Ta.isAxiosError(a)&&a.response?.status===404)return null;throw a}},confirmRegistrationOrder:async(t,s)=>{try{return(await F.post(`/commerce/admin/registration-orders/${t}/confirm`,null,{params:{society_id:s}})).data}catch(a){Oo(a)}},resumeRegistrationOrder:async(t,s)=>{try{return(await F.post(`/commerce/admin/registration-orders/${t}/resume`,null,{params:{society_id:s}})).data}catch(a){Oo(a)}}};function Af(t){t.invalidateQueries({queryKey:["admin","event-registrations"]}),t.invalidateQueries({queryKey:["admin","events"]})}function Md(t,s){s.status==="paid"&&Af(t)}function A2(t){const{selectedSocietyId:s}=V();return re({queryKey:["admin","member-payment-methods",t,s],queryFn:()=>Ia.getMemberPaymentMethods(t,s),enabled:!!s&&!!t})}function E2(){const{selectedSocietyId:t}=V();return W({mutationFn:s=>Ia.validateRegistrationOrder(s,t)})}function T2(){const{selectedSocietyId:t}=V(),s=J();return W({mutationFn:a=>Ia.createRegistrationOrder(a,t),onSuccess:a=>Md(s,a),meta:{suppressErrorToast:!0}})}function F2(){const{selectedSocietyId:t}=V(),s=J();return W({mutationFn:a=>Ia.confirmRegistrationOrder(a,t),onSuccess:a=>Md(s,a)})}function R2(){const{selectedSocietyId:t}=V(),s=J();return W({mutationFn:a=>Ia.resumeRegistrationOrder(a,t),onSuccess:a=>Md(s,a)})}function M2(t){const{selectedSocietyId:s}=V();return re({queryKey:["admin","registration-order-status",t,s],queryFn:()=>Ia.getRegistrationOrder(t,s),enabled:!!s&&!!t,refetchInterval:a=>a.state.data?.status==="pending"?3e3:!1})}function D2(){const{selectedSocietyId:t}=V(),s=J();return W({mutationFn:a=>Ia.createWalkInMember(a,t),onSuccess:()=>{s.invalidateQueries({queryKey:["members"]})},meta:{suppressErrorToast:!0}})}function L2({onSelect:t}){const{selectedSocietyId:s}=V(),a=oa(),n=D2(),[r,i]=o.useState(!1),[l,m]=o.useState(!1),[c,d]=o.useState(null),[u,h]=o.useState(null),[p,x]=o.useState(""),[f,b]=o.useState(""),[N,j]=o.useState(""),[w,v]=o.useState(""),k=(a.data??[]).filter(y=>y.is_active&&y.eligible_as_non_member_role&&!y.is_non_member&&y.price>0);async function S(y){const C=await Gt.get(y.member.id,s||void 0);t(C)}async function _(){if(!l){m(!0),d(null);try{if(u)await S(u);else{const y=await n.mutateAsync({first_name:p.trim(),last_name:f.trim(),email:N.trim(),declared_role_type_id:w});h(y),y.existing||await S(y)}}catch(y){const C=Ta.isAxiosError(y)?y.response?.data?.detail:null;d(typeof C=="string"?C:"Could not load this person. Check the details and try again.")}finally{m(!1)}}}return e.jsx("div",{className:"space-y-4",children:r?e.jsxs("form",{className:"space-y-4",onSubmit:y=>{y.preventDefault(),_()},children:[u?e.jsxs("div",{className:"space-y-3 rounded-lg border border-border bg-muted/30 p-4",children:[e.jsx("p",{className:"font-medium",children:u.existing?"This email already belongs to a person":"Person added"}),e.jsxs("p",{className:"break-words text-sm",children:[u.member.first_name," ",u.member.last_name,e.jsx("br",{}),e.jsx("span",{className:"text-muted-foreground",children:u.member.email})]}),e.jsxs(g,{type:"submit",className:"min-h-[44px] w-full",disabled:l,children:[l&&e.jsx(He,{className:"mr-2 h-4 w-4 animate-spin"}),"Use this person"]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"walk-first",children:"First name"}),e.jsx(O,{autoFocus:!0,autoComplete:"off",id:"walk-first",maxLength:100,className:"min-h-[44px]",required:!0,value:p,onChange:y=>x(y.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"walk-last",children:"Last name"}),e.jsx(O,{autoComplete:"off",id:"walk-last",maxLength:100,className:"min-h-[44px]",required:!0,value:f,onChange:y=>b(y.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"walk-email",children:"Email"}),e.jsx(O,{autoComplete:"off",id:"walk-email",type:"email",className:"min-h-[44px]",required:!0,value:N,onChange:y=>j(y.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"walk-role",children:"Professional role"}),e.jsxs("select",{id:"walk-role",className:"min-h-[44px] w-full rounded-md border border-input bg-background px-3 text-sm text-foreground",required:!0,value:w,onChange:y=>v(y.target.value),disabled:!a.isSuccess,children:[e.jsx("option",{value:"",children:"Choose a role"}),k.map(y=>e.jsx("option",{value:y.id,children:y.name},y.id))]}),a.isPending&&e.jsx("p",{role:"status",className:"text-sm text-muted-foreground",children:"Loading rolesâ¦"}),a.isError&&e.jsxs("div",{role:"alert",className:"text-sm",children:[e.jsx("p",{children:"Could not load roles."}),e.jsx(g,{type:"button",className:"min-h-[44px]",variant:"outline",onClick:()=>{a.refetch()},children:"Retry roles"})]}),a.isSuccess&&k.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No roles are available for quick-add. Ask an administrator to configure professional roles, or search for an existing person."})]}),e.jsxs(g,{type:"submit",className:"min-h-[44px] w-full",disabled:l||k.length===0||!w||!p.trim()||!f.trim(),children:[l&&e.jsx(He,{className:"mr-2 h-4 w-4 animate-spin"}),l?"Adding personâ¦":"Add person and see rate"]})]}),c&&e.jsx("p",{role:"alert",className:"text-sm text-destructive",children:c}),e.jsx(g,{type:"button",variant:"ghost",className:"min-h-[44px] w-full",disabled:l,onClick:()=>{i(!1),d(null),h(null)},children:"Back to search"})]}):e.jsxs(e.Fragment,{children:[e.jsx(ho,{touch:!0,selectedMember:null,onSelectMember:t,onClearMember:()=>i(!1),label:"Find person",inputId:"walk-in-search"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Search by name or email. Select a person to see their rate."}),e.jsxs(g,{type:"button",variant:"outline",className:"min-h-[44px] w-full",onClick:()=>i(!0),children:[e.jsx(fa,{className:"mr-2 h-4 w-4"}),"Not in the system? Quick-add"]})]})})}const $2={first_name:"first_name",last_name:"last_name",email:"email",phone:"phone",city:"city",state:"state",county:"county",country:"country",organization:"organization",credentials:"credentials",license_number:"license_number",prefix:"prefix",suffix:"suffix",zip_code:"postal_code",postal_code:"postal_code",address:"address_line1",specialty:"sub_specialty"},fo=t=>t==null||typeof t=="string"&&t.trim()===""||Array.isArray(t)&&t.length===0;function yo(t){if(t.field_type==="checkbox"||t.field_type==="file")return null;if(t.source==="custom_field")return{kind:"custom",key:t.field_key};const s=$2[t.field_key];return s?{kind:"column",column:s}:{kind:"custom_heuristic",key:t.field_key}}function Ef(t,s){if(fo(s))return!1;switch(t.field_type){case"text":case"textarea":case"phone":case"email":case"url":return typeof s=="string";case"number":return typeof s=="number"?Number.isFinite(s):typeof s=="string"&&s.trim()!==""&&Number.isFinite(Number(s));case"date":return typeof s=="string"&&/^\d{4}-\d{2}-\d{2}$/.test(s);case"dropdown":return typeof s=="string"&&(t.options??[]).includes(s);case"multi_select":return Array.isArray(s)&&s.length>0&&s.every(a=>
4typeof a=="string"&&(t.options??[]).includes(a));default:return!1}}function q2(t,s){return s.kind==="column"?t[s.column]:t.custom_fields?.[s.key]}function I2(t,s){const a={};for(const n of s){if(n.source!=="custom_field"&&n.field_key==="badge_name"&&(n.field_type==="text"||n.field_type==="textarea")){const l=`${t.first_name} ${t.last_name}`.trim();l&&(a[n.field_key]=l);continue}const r=yo(n);if(!r)continue;const i=q2(t,r);Ef(n,i)&&(a[n.field_key]=i)}return a}function Gm(t,s){const a={},n={},r=[],i=new Set;for(const l of s)for(const m of l.fields){const c=yo(m);if(!c||c.kind==="custom_heuristic"||c.kind==="column"&&c.column==="email")continue;const d=c.kind==="column"?`col:${c.column}`:`cf:${c.key}`;if(i.has(d))continue;const u=l.cleanedValues[m.field_key];if(!Ef(m,u))continue;const h=c.kind==="column"?t[c.column]:t.custom_fields?.[c.key];fo(h)&&(i.add(d),c.kind==="column"?a[c.column]=u:n[c.key]=u,r.push({source:c,fieldKey:m.field_key,label:m.label,fieldType:m.field_type,options:m.options??null,value:u}))}return Object.keys(a).length===0&&Object.keys(n).length===0?null:{columns:a,customFieldDeltas:n,claims:r}}function O2(t){if(t.length===0)return null;const s=t.length;return`Couldn't update ${s} member record${s===1?"":"s"}: ${t.join(", ")}`}function Ym(t,s,a){let n=t;const r=[];for(const i of a){if(s.has(i.key))continue;const l=I2(i.member,i.fields);n={...n,[i.key]:{...l,...t[i.key]??{}}},r.push(i.key)}return{next:n,newlySeeded:r}}function Hm(t,s,a,n){return a===n?t:t.filter(r=>(s[r.id]??[]).includes(a))}function Jm(t,s){const a=new Set(t),n=i=>Object.fromEntries(Object.entries(i).filter(([l])=>!a.has(l))),r=new Set([...s.seeded].filter(i=>!a.has(i)));return{raw:n(s.raw),cleaned:n(s.cleaned),validity:n(s.validity),seeded:r}}function Tf(t){const s=yo(t);return!(!s||s.kind==="custom_heuristic"||s.kind==="column"&&s.column==="email")}function U2(t,s){const a=yo(t);if(!a||a.kind==="custom_heuristic")return!0;const n=a.kind==="column"?s[a.column]:s.custom_fields?.[a.key];return fo(n)}function Ff(t,s){return Tf(t)&&U2(t,s)}function Fn(t,s){return Ff(t,s)?"Missing â will save to profile":t.field_type==="dropdown"||t.field_type==="multi_select"?"Selectâ¦":t.field_type==="textarea"?"Add noteâ¦":t.placeholder||""}function Jr(t){return t==null?"":String(t)}const z2={text:"text",email:"email",phone:"tel",url:"url",number:"number"},Zm="flex h-10 w-full min-w-[10rem] max-w-[16rem] items-center truncate rounded-md border border-input bg-background px-3 py-2 text-left text-sm text-foreground ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2";function Xm(t,s,a,n,r,i=!1){const l=`${t.label} â ${s.first_name} ${s.last_name}`,m=me("border-border bg-background text-foreground",i&&"min-h-[44px]",n&&pi),c=d=>r(s.id,t.field_key,d);switch(t.field_type){case"text":case"email":case"phone":case"url":case"number":return e.jsx(O,{type:z2[t.field_type]??"text",value:Jr(a),onChange:d=>c(d.target.value),placeholder:Fn(t,s),"aria-label":l,className:m});case"date":{const d=Ff(t,s);return e.jsxs("div",{className:"space-y-1",children:[e.jsx(O,{type:"date",value:Jr(a),onChange:u=>c(u.target.value),"aria-label":l,className:m}),d&&e.jsx("p",{className:"text-[11px] text-amber-700 dark:text-amber-300",children:"Missing â will save to profile"})]})}case"dropdown":{const d=t.options??[];return i?e.jsxs("select",{"aria-label":l,className:me("w-full rounded-md border px-3 text-sm",m),value:typeof a=="string"?a:"",onChange:u=>c(u.target.value||null),children:[e.jsx("option",{value:"",children:t.required?"Selectâ¦":"No answer"}),d.map(u=>e.jsx("option",{value:u,children:u},u))]}):t.required?e.jsxs(qe,{value:typeof a=="string"?a:"",onValueChange:u=>c(u),children:[e.jsx(Le,{"aria-label":l,className:m,children:e.jsx(Ie,{placeholder:Fn(t,s)})}),e.jsx($e,{children:d.map(u=>e.jsx(q,{value:u,className:me(i&&"min-h-[44px]"),children:u},u))})]}):e.jsx(Ss,{value:typeof a=="string"?a:null,onChange:u=>c(u),noneLabel:"No answer",placeholder:Fn(t,s),ariaLabel:l,className:m,children:d.map(u=>e.jsx(q,{value:u,className:me(i&&"min-h-[44px]"),children:u},u))})}case"checkbox":return e.jsx(ot,{checked:!!a,onCheckedChange:d=>c(!!d),"aria-label":l,className:me(n&&pi,i&&"min-h-[44px] min-w-[44px]")});case"textarea":{if(i)return e.jsx(It,{"aria-label":l,value:Jr(a),onChange:u=>c(u.target.value),className:m});
4const d=typeof a=="string"?a:"";return e.jsxs(kl,{children:[e.jsx(_l,{asChild:!0,children:e.jsx("button",{type:"button","aria-label":l,className:me(Zm,!d&&"text-muted-foreground",m),children:d||Fn(t,s)})}),e.jsx(hi,{className:"w-72 p-2",children:e.jsx(It,{value:Jr(a),onChange:u=>c(u.target.value),placeholder:Fn(t,s),rows:3})})]})}case"multi_select":{const d=Array.isArray(a)?a:[],u=d.length>0?d.join(", "):"",h=t.options??[];return i?e.jsx("div",{className:"space-y-2",children:h.map(p=>e.jsxs("label",{className:"flex min-h-[44px] items-center gap-3 rounded-md border border-border px-3 text-sm",children:[e.jsx(ot,{checked:d.includes(p),onCheckedChange:x=>c(x?[...d,p]:d.filter(f=>f!==p))}),p]},p))}):e.jsxs(kl,{children:[e.jsx(_l,{asChild:!0,children:e.jsx("button",{type:"button","aria-label":l,className:me(Zm,!u&&"text-muted-foreground",m),children:u||Fn(t,s)})}),e.jsx(hi,{className:"w-64 space-y-2 p-3",children:h.map(p=>{const x=d.includes(p);return e.jsxs("label",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(ot,{checked:x,onCheckedChange:f=>{c(f?[...d,p]:d.filter(b=>b!==p))}}),p]},p)})})]})}default:return e.jsx(O,{type:"text",value:Jr(a),onChange:d=>c(d.target.value),placeholder:Fn(t,s),"aria-label":l,className:m})}}function Rf({layout:t="grid",form:s,registrants:a,rawValuesByMember:n,onChangeValue:r}){const i=a.reduce((l,m)=>l+On(In(s.fields,n[m.id]??{}),n[m.id]??{}).size,0);return t==="stacked"?e.jsxs("fieldset",{className:"min-w-0 space-y-4 rounded-lg border border-border p-4",children:[e.jsxs("legend",{className:"flex items-center gap-2.5 px-2 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(Lt,{className:"h-4 w-4"})}),s.name," · Registration details"]}),a.map(l=>{const m=n[l.id]??{},c=In(s.fields,m),d=On(c,m);return c.map(u=>e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-sm font-medium",children:[u.label,u.required&&e.jsx("span",{className:"text-muted-foreground",children:" (required)"})]}),Xm(u,l,m[u.field_key],d.has(u.field_key),r,!0),u.help_text&&e.jsx("p",{className:"text-sm text-muted-foreground",children:u.help_text})]},`${l.id}:${u.field_key}`))}),i>0&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:[i," required question",i===1?"":"s"," left"]})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-xs font-medium uppercase tracking-wider text-muted-foreground/80",children:[s.name," â registration form"]}),e.jsx("div",{className:"overflow-x-auto rounded-md border",children:e.jsxs("table",{className:"w-full min-w-max text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b bg-muted/30",children:[e.jsx("th",{className:"sticky left-0 z-10 whitespace-nowrap bg-muted/30 px-3 py-2 text-left font-medium text-muted-foreground",children:"Registrant"}),s.fields.map(l=>e.jsx("th",{className:"whitespace-nowrap px-2 py-2 text-left font-medium text-muted-foreground",children:e.jsxs("span",{className:"inline-flex items-center gap-1",children:[l.label,l.required&&e.jsx("span",{className:"text-red-500","aria-label":"required",title:"Required",children:"*"}),Tf(l)&&e.jsx(Lt,{className:"h-3.5 w-3.5 text-muted-foreground","aria-hidden":"true"})]})},l.field_key))]})}),e.jsx("tbody",{children:a.map(l=>{const m=n[l.id]??{},c=In(s.fields,m),d=new Set(c.map(h=>h.field_key)),u=On(c,m);return e.jsxs("tr",{className:"border-t hover:bg-brand-navy/[0.04] dark:hover:bg-brand-navy/10",children:[e.jsxs("td",{className:"sticky left-0 z-10 whitespace-nowrap bg-card px-3 py-2 font-medium",children:[l.first_name," ",l.last_name,l.membership_type_name&&e.jsx("span",{className:"block text-xs font-normal text-muted-foreground",children:l.membership_type_name})]}),s.fields.map(h=>e.jsx("td",{className:"px-2 py-1.5 align-middle",children:d.has(h.field_key)?Xm(h,l,m[h.field_key],u.has(h.field_key),r):e.jsx("span",{className:"text-muted-foreground",children:"â"})},h.field_key))]},l.id)})})]})}),e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-4 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx("span",{className:me("inline-block h-3 w-3 rounded-sm border",pi)}),"Needs input"]}),e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(Lt,{className:"h-3.5 w-3.5","aria-hidden":"true"}),"Prefilled from member record â new values fill empty member fields after checkout"]})]}),i>0?e.jsxs("p",{className:"text-xs font-medium text-amber-700 dark:text-amber-300",children:[i," required question",i===1?"":"s"," left"]}):e.jsx("p",{className:"text-xs text-muted-foreground",children:"All required questions answered"})]})]})}function Mf({id:t,amount:s,reason:a,placeholder:n,overridden:r,onChange:i}){return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:`${t}-amount`,children:"Price override ($)"}),e.jsx(O,{id:`${t}-amount`,className:"min-h-[44px]",inputMode:"decimal",type:"number",min:"0",step:"0.01",value:s,placeholder:n,onChange:l=>i({amount:l.target.value})})]}),r&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:`${t}-reason`,children:"Reason for override (required)"}),e.jsx(O,{id:`${t}-reason`,className:"min-h-[44px]",value:a,onChange:l=>i({reason:l.target.value})})]})]})}function B2(t){return t.startsWith("member_via_offer:")?"Member rate with free membership":t.startsWith("non_member")?"Non-member rate":t.startsWith("member")?"Member rate":"Rate unavailable"}function K2(t){const{member:s,children:a,selectedChildren:n,forms:r,rawResponses:i,formsReady:l,formsError:m,quote:c,quotePending:d,quoteError:u,claims:h,overrides:p,onToggleChild:x,onClaim:f,onOverride:b,onField:N,onRetry:j}=t;return e.jsxs("div",{className:"space-y-5",children:[a.length>0&&e.jsxs("fieldset",{className:"space-y-2",children:[e.jsxs("legend",{className:"mb-2 flex items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 items-center justify-center rounded-lg bg-brand-navy
4/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(vr,{className:"h-4 w-4"})}),"Add-on sessions"]}),a.map(w=>e.jsxs("label",{className:"flex min-h-[44px] cursor-pointer items-center gap-3 rounded-md border border-border p-3 text-sm",children:[e.jsx(ot,{checked:n.includes(w.id),onCheckedChange:()=>x(w.id)}),e.jsx("span",{className:"min-w-0 break-words",children:w.name})]},w.id))]}),d&&e.jsxs("p",{role:"status",className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(He,{className:"h-4 w-4 animate-spin"}),"Updating rateâ¦"]}),u&&e.jsxs("div",{role:"alert",className:"space-y-2 rounded-md border border-destructive/30 p-3 text-sm",children:[e.jsx("p",{children:u}),e.jsx(g,{type:"button",variant:"outline",className:"min-h-[44px]",onClick:j,children:"Retry quote"})]}),c&&e.jsxs("div",{className:"space-y-3","aria-busy":d,children:[c.batch_errors.length>0&&e.jsx("div",{role:"alert",className:"space-y-1 text-sm text-destructive",children:c.batch_errors.map((w,v)=>e.jsx("p",{children:w},v))}),c.lines.map(w=>{const v=`${w.event_id}::${s.id}`,k=p[v]??{amount:"",reason:""};return e.jsxs("div",{className:"space-y-3 rounded-lg border border-border bg-muted/20 p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0 space-y-1",children:[e.jsx("p",{className:"break-words text-sm font-medium",children:r.find(S=>S.eventId===w.event_id)?.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:B2(w.rate_label)})]}),e.jsxs("p",{className:"text-2xl font-semibold tracking-tight",children:["$",w.final_amount]})]}),w.offer_eligible&&e.jsxs("label",{className:"flex min-h-[44px] cursor-pointer items-center gap-3 rounded-md border border-primary/30 bg-primary/5 p-3 text-sm",children:[e.jsx(ot,{checked:!!h[w.event_id],onCheckedChange:S=>f(w.event_id,S===!0),disabled:d}),e.jsxs("span",{children:["Join free for ",w.offer_months," months â pays member rate"]})]}),w.errors.length>0&&e.jsx("div",{role:"alert",className:"space-y-1 text-sm text-destructive",children:w.errors.map((S,_)=>e.jsx("p",{children:S},_))}),e.jsxs("details",{className:"rounded-md border border-border bg-background px-3",open:k.amount.trim()?!0:void 0,children:[e.jsxs("summary",{className:"flex min-h-[44px] cursor-pointer items-center gap-2 text-sm font-medium",children:[e.jsx(xa,{className:"h-4 w-4"}),"Adjust price"]}),e.jsxs("div",{className:"space-y-2 pb-3",children:[e.jsx(Mf,{id:`walk-override-${w.event_id}`,amount:k.amount,reason:k.reason,placeholder:w.resolved_price,overridden:k.amount.trim()!=="",onChange:S=>b(v,S)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Leave blank to use the quoted rate. Enter 0 for a complimentary registration."})]})]})]},v)}),c.lines.length===0&&e.jsxs("div",{className:"space-y-2 text-sm text-muted-foreground",children:[e.jsx("p",{children:"No registration rate was returned."}),e.jsx(g,{type:"button",variant:"outline",className:"min-h-[44px]",onClick:j,children:"Retry quote"})]})]}),!l&&!m&&e.jsx("p",{role:"status",className:"text-sm text-muted-foreground",children:"Loading registration detailsâ¦"}),m&&e.jsxs("div",{role:"alert",className:"space-y-2 text-sm",children:[e.jsx("p",{children:"Could not load registration details."}),e.jsx(g,{type:"button",variant:"outline",className:"min-h-[44px]",onClick:j,children:"Retry details"})]}),l&&r.filter(w=>w.fields.length>0).map(w=>e.jsx(Rf,{layout:"stacked",form:w,registrants:[s],rawValuesByMember:{[s.id]:i[`${s.id}::${w.eventId}`]??{}},onChangeValue:(v,k,S)=>N(v,w.eventId,k,S)},w.eventId))]})}function Q2({clientSecret:t,publishableKey:s,onSucceeded:a,onProcessing:n,cardOnly:r=!1}){const{theme:i}=bd(),l=Td(s,0),[m,c]=o.useState(!1);return o.useEffect(()=>{let d=!0;return l?.then(u=>{d&&c(u===null)}),()=>{d=!1}},[l]),m?e.jsxs("div",{role:"alert",className:"space-y-3 text-sm",children:[e.jsx("p",{children:"Card entry could not load. Retry to resume this payment safely."}),e.jsx(g,{type:"button",variant:"outline",className:"min-h-[44px]",onClick:()=>window.location.reload(),children:"Retry card entry"})]}):e.jsx(dn,{stripe:l,options:{clientSecret:t,appearance:{theme:i==="dark"?"night":"stripe",variables:{spacingUnit:"5
4px"}}},children:e.jsx(W2,{cardOnly:r,clientSecret:t,onSucceeded:a,onProcessing:n})})}function W2({cardOnly:t,clientSecret:s,onSucceeded:a,onProcessing:n}){const r=mn(),i=un(),[l,m]=o.useState(!1),[c,d]=o.useState(!1),[u,h]=o.useState(!1),[p,x]=o.useState(null),[f,b]=o.useState(!1),N=o.useRef(!1),j=async k=>{if(r){b(!0);try{const S=await r.retrievePaymentIntent(s);if(S.error||!S.paymentIntent){x("Could not check this payment. Check its status before trying to charge again.");return}const _=S.paymentIntent.status;_==="succeeded"?await a():_==="requires_payment_method"||_==="requires_confirmation"||_==="requires_action"?(b(!1),x(k)):n()}catch{x("Could not check this payment. Check its status before trying to charge again.")}}},w=async()=>{if(!N.current){N.current=!0,h(!0);try{await j("Payment did not complete. Check the card details and try again.")}finally{N.current=!1,h(!1)}}},v=async k=>{if(k.preventDefault(),!r||!i||!l||N.current||f)return;N.current=!0,h(!0),x(null);let S=!1;try{const _=await i.submit();if(_.error){x(_.error.message||"Check the card details and try again.");return}S=!0;const y=await r.confirmPayment({elements:i,confirmParams:{return_url:window.location.href},redirect:"if_required"});if(y.error){const C=y.error.message||"Payment failed. Check the card details and try again.";y.error.type==="api_connection_error"||y.error.type==="api_error"?await j(C):x(C);return}y.paymentIntent?.status==="succeeded"?await a():y.paymentIntent?.status==="processing"?n():x("Payment did not complete. Please try again.")}catch(_){const y=_ instanceof Error&&_.message?_.message:"Could not submit the payment. Check the card details and try again.";S?await j(y):x(y)}finally{N.current=!1,h(!1)}};return e.jsxs("form",{onSubmit:v,className:"space-y-4 py-2",children:[!l&&!p&&e.jsx("p",{role:"status",className:"text-sm text-muted-foreground",children:"Loading card entryâ¦"}),e.jsx(hn,{options:{layout:{type:"tabs",defaultCollapsed:!1},...t?{wallets:{applePay:"never",googlePay:"never"}}:{}},onReady:()=>m(!0),onLoadError:()=>{m(!1),d(!0),x("Card entry could not load. Retry to resume this payment safely.")}}),p&&e.jsx("div",{role:"alert",className:"rounded-md border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-800 dark:border-red-800 dark:bg-red-950/20 dark:text-red-200",children:p}),c&&e.jsx(g,{type:"button",variant:"outline",className:"min-h-[44px] w-full",onClick:()=>window.location.reload(),children:"Retry card entry"}),f&&e.jsx(g,{type:"button",variant:"outline",className:"min-h-[44px] w-full",disabled:u,onClick:()=>{w()},children:"Check payment status"}),e.jsxs(g,{type:"submit",className:"min-h-[44px] w-full",disabled:!r||!l||u||f,children:[u&&e.jsx(He,{className:"mr-1.5 h-4 w-4 animate-spin"}),u?f?"Checking paymentâ¦":"Chargingâ¦":"Charge card"]})]})}function V2(t){let s=null,a=!1,n=!1,r=!1;const i=()=>{if(n||a||!r||!s)return null;const l=t(s);return l.length===0?null:(n=!0,O2(l))};return{setResult(l){return s=l,i()},markSurfaced(){a=!0},markDead(){return r=!0,i()},markAlive(){n||(r=!1)}}}const Un="Couldn't save â correct and retry, or edit the member directly";function Zr(t,s){return{source:t.source,label:t.label,fieldType:t.fieldType,options:t.options,attemptedValue:t.value,reason:s}}function ia(t){return t.source.kind==="column"?`col:${t.source.column}`:`cf:${t.source.key}`}const eu=500;function Fl(t){return t.length>eu?t.slice(0,eu):t}function Df(t){try{const s=JSON.stringify(t);return Fl(s===void 0?String(t):s)}catch{return Fl(String(t))}}function Rl(t,s){const a={};for(const n of t)a[ia(n)]=Un;return{implicated:t,reasonByClaimId:a,unattributed:s,attributed:!1}}function G2(t){return typeof t=="object"&&t!==null}function Y2(t,s){const a={},n=new Set;for(const i of t){if(!G2(i))continue;const{loc:l,msg:m}=i;if(!Array.isArray(l)||typeof m!="string")continue;const c=l[1];if(c==="custom_fields"){for(const u of s)u.source.kind==="custom"&&(n.add(ia(u)),a[ia(u)]=m);continue}const d=s.find(u=>u.source.kind==="column"&&u.source.column===c);d&&(n.add(ia(d)),a[ia(d)]=m)}return n.size===0?Rl(s,Df(t)):{implicated:s.filter(i=>n.has(ia(i))),reasonByClaimId:a,unattributed:null,attributed:!0}
4}function H2(t,s){const a=s.filter(u=>u.source.kind==="custom"),n=new Map;for(const u of a)n.set(u.label,(n.get(u.label)??0)+1);const r=[...n.values()].some(u=>u>1),i=a.some(u=>u.label.includes("; ")||u.label.includes(": "));if(r||i)return Rl(s,Fl(t));const l=t.split("; "),m={},c=new Set;for(const u of l){const h=a.find(p=>u.startsWith(`${p.label}: `)||u===`${p.label} is required`);if(!h)return Rl(s,Fl(t));c.add(ia(h)),m[ia(h)]=u}return{implicated:a.filter(u=>c.has(ia(u))),reasonByClaimId:m,unattributed:null,attributed:!0}}function J2(t,s){return Array.isArray(t)?Y2(t,s):typeof t=="string"?H2(t,s):Rl(s,Df(t))}function Lf(t){const s=typeof t=="object"&&t!==null?t:void 0;return{status:s?.response?.status??null,detail:s?.response?.data?.detail,message:String(s?.message??t)}}function Z2(t){const s={},a={};for(const n of t)n.source.kind==="column"?s[n.source.column]=n.value:a[n.source.key]=n.value;return{columns:s,customFieldDeltas:a}}function tu(t,s){return{...t,...Object.keys(s).length>0?{custom_fields:s}:{}}}function su(t,s){return t.reasonByClaimId[s]??Un}async function X2(t){const s=t.extractError??Lf,a=[];for(const{member:n,forms:r}of t.registrants){const i=`${n.first_name} ${n.last_name}`;let l;try{l=await t.getMember(n.id)}catch(u){const h=Gm(n,r)?.claims??[];a.push({memberId:n.id,name:i,updatedFieldCount:0,failures:h.map(p=>Zr(p,"Couldn't load the member record â retry")),unattributed:s(u).message});continue}const m=Gm(l,r);if(!m){a.push({memberId:n.id,name:i,updatedFieldCount:0,failures:[],unattributed:null});continue}const c=m.claims,d=tu(m.columns,m.customFieldDeltas);try{await t.updateMember(n.id,d),a.push({memberId:n.id,name:i,updatedFieldCount:c.length,failures:[],unattributed:null});continue}catch(u){const h=s(u);if(h.status!==422){a.push({memberId:n.id,name:i,updatedFieldCount:0,failures:c.map(k=>Zr(k,Un)),unattributed:h.message});continue}const p=J2(h.detail,c);if(!(p.attributed&&p.implicated.length>0&&p.implicated.length<c.length)){a.push({memberId:n.id,name:i,updatedFieldCount:0,failures:p.implicated.map(k=>Zr(k,su(p,ia(k)))),unattributed:p.unattributed});continue}const f=new Set(p.implicated.map(ia)),b=c.filter(k=>!f.has(ia(k))),{columns:N,customFieldDeltas:j}=Z2(b),w=tu(N,j),v=p.implicated.map(k=>Zr(k,su(p,ia(k))));try{await t.updateMember(n.id,w),a.push({memberId:n.id,name:i,updatedFieldCount:b.length,failures:v,unattributed:null})}catch(k){const S=s(k).message;a.push({memberId:n.id,name:i,updatedFieldCount:0,failures:[...v,...b.map(_=>Zr(_,S))],unattributed:null})}}}return{updatedCount:a.filter(n=>n.updatedFieldCount>0).length,failedNames:a.filter(n=>n.failures.length>0).map(n=>n.name),members:a}}const e4="Couldn't load the member record â retry";function t4(t){return typeof t=="object"&&t!==null&&typeof t.msg=="string"}function s4(t,s){const{status:a,detail:n}=s(t);if(a!==422)return Un;if(typeof n=="string"){const r=n.trim();return r.length>0?r:Un}if(Array.isArray(n)){const r=n.find(t4);if(r)return r.msg}return Un}function a4(t,s){return t.kind==="column"?{[t.column]:s}:{custom_fields:{[t.key]:s}}}async function n4(t,s){const a=s.extractError??Lf,n=[];for(const r of t){if(r.source.kind==="column"&&r.source.column==="email"){n.push({request:r,outcome:{kind:"failed",reason:Un}});continue}let i;try{i=await s.getMember(r.memberId)}catch{n.push({request:r,outcome:{kind:"failed",reason:e4}});continue}const l=r.source.kind==="column"?i[r.source.column]:i.custom_fields?.[r.source.key];if(!fo(l)){n.push({request:r,outcome:{kind:"already_filled"}});continue}try{await s.updateMember(r.memberId,a4(r.source,r.value)),n.push({request:r,outcome:{kind:"updated"}})}catch(m){n.push({request:r,outcome:{kind:"failed",reason:s4(m,a)}})}}return n}const r4="Already filled on the member record",i4="Couldn't update profiles â try again.",au="rounded-md border border-amber-300 bg-amber-50 px-3 py-2 text-sm dark:border-amber-700/60 dark:bg-amber-950/30";function zn(t){return t.kind==="column"?`col:${t.column}`:`cf:${t.key}`}function hl(t,s){return`${t}::${s}`}function l4(t){return t.filter(s=>s.failures.length>0).map(s=>({memberId:s.memberId,name:s.name,unattributed:s.unattributed,fields:s.failures.map(a=>({source:a.source,label:a.label,fieldType:a.fieldType,options:a.options,reason:a.reason})),updatedCount:0,resolvedNotes:[]}))}function o4(t){const s={};for(const a of t)for(const n of a.failures)s[hl(a.memberId,zn(n.source))]=n.attemptedValue;return s}function c4(t,s){return t.map(a=>{let n=a.updatedCount;const r=[...a.resolvedNotes],i=[];for(const l of a.fields){const m=s.find(c=>c.request.memberId===a.memberId&&zn(c.request.source)===zn(l.source));if(!m){i.push(l);continue}if(m.outcome.kind==="updated"){n+=1;continue}if(m.outcome.kind==="already_filled"){r.push({key:zn(l.source),label:l.label,note:r4});continue}i.push({...l,reason:m.outcome.reason})}return{...a,fields:i,updatedCount:n,resolvedNotes:r}}).filter(a=>a.fields.length>0)}function Qi(t){return t==null?"":String(t)}const d4={text:"text",email:"email",phone:"tel",url:"url",number:"number"};function m4(t,s,a,n,r){const i=`${s.label} â ${t}`,l=me("border-border bg-background text-foreground",pi);switch(s.fieldType){case"text":case"email":case"phone":case"url":case"number":return e.jsx(O,{type:d4[s.fieldType]??"text",value:Qi(a),onChange:m=>n(m.target.value),"aria-label":i,"aria-describedby":r,className:l});case"date":return e.jsx(O,{type:"date",value:Qi(a),onChange:m=>n(m.target.value),"aria-label":i,"aria-describedby":r,className:l});case"textarea":return e.jsx(It,{value:Qi(a),onChange:m=>n(m.target.value),"aria-label":i,"aria-describedby":r,className:l});
4case"dropdown":{const m=s.options??[],c=typeof a=="string"&&m.includes(a)?a:"";return e.jsxs(qe,{value:c,onValueChange:d=>n(d),children:[e.jsx(Le,{"aria-label":i,"aria-describedby":r,className:l,children:e.jsx(Ie,{placeholder:"Selectâ¦"})}),e.jsx($e,{children:m.map(d=>e.jsx(q,{value:d,children:d},d))})]})}case"multi_select":{const m=Array.isArray(a)?a:[],c=s.options??[];return e.jsx("div",{role:"group","aria-label":i,"aria-describedby":r,className:me("space-y-1.5 rounded-md border p-2",l),children:c.map(d=>{const u=m.includes(d);return e.jsxs("label",{className:"flex items-center gap-2 text-sm text-foreground",children:[e.jsx(ot,{checked:u,onCheckedChange:h=>{n(h?[...m,d]:m.filter(p=>p!==d))},"aria-label":d}),d]},d)})})}default:return e.jsx(O,{type:"text",value:Qi(a),onChange:m=>n(m.target.value),"aria-label":i,"aria-describedby":r,className:l})}}function nu({secondaryActions:t=!1,members:s,onRetry:a,onDismiss:n}){const[r,i]=o.useState(()=>l4(s)),[l,m]=o.useState(()=>o4(s)),[c,d]=o.useState(!1),[u,h]=o.useState(null);if(s.length===0)return null;if(r.length===0)return e.jsx("div",{className:au,children:e.jsxs("p",{className:"flex items-center gap-1.5 font-medium text-emerald-700 dark:text-emerald-400",children:[e.jsx(Kt,{className:"h-4 w-4","aria-hidden":"true"}),"All profiles updated."]})});const p=(b,N,j)=>{m(w=>({...w,[hl(b,zn(N))]:j}))},x=async()=>{d(!0),h(null);const b=[];for(const N of r)for(const j of N.fields)b.push({memberId:N.memberId,source:j.source,label:j.label,value:l[hl(N.memberId,zn(j.source))]});try{const N=await a(b);i(j=>c4(j,N))}catch{h(i4)}finally{d(!1)}},f=r.length;return e.jsxs("div",{className:au,role:"status",children:[e.jsx("p",{className:"font-medium text-amber-800 dark:text-amber-200",children:`We hit an error updating ${f} member profile${f===1?"":"s"}. Please update the following fields:`}),e.jsx("div",{className:"mt-3 space-y-4",children:r.map(b=>e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-semibold text-foreground",children:b.name}),b.updatedCount>0&&e.jsx("p",{className:"text-[11px] text-emerald-700 dark:text-emerald-400",children:`Updated ${b.updatedCount} field${b.updatedCount===1?"":"s"}.`}),b.resolvedNotes.map(N=>e.jsx("p",{className:"text-[11px] text-muted-foreground",children:`${N.label}: ${N.note}`},N.key)),e.jsx("div",{className:"space-y-3",children:b.fields.map(N=>{const j=hl(b.memberId,zn(N.source)),w=`${j}-reason`;return e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs font-medium text-foreground",children:N.label}),m4(b.name,N,l[j],v=>p(b.memberId,N.source,v),w),e.jsx("p",{id:w,className:"text-[11px] text-amber-700 dark:text-amber-300",children:N.reason})]},j)})}),b.unattributed&&e.jsx("p",{className:"whitespace-pre-wrap text-xs text-muted-foreground",children:b.unattributed})]},b.memberId))}),u&&e.jsx("p",{className:"mt-2 text-[11px] text-amber-700 dark:text-amber-300",children:u}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsx(g,{type:"button",variant:t?"outline":"default",size:"sm",disabled:c,onClick:()=>{x()},children:"Update profiles"}),e.jsx(g,{type:"button",variant:"ghost",size:"sm",onClick:n,children:"Skip"})]})]})}const $f=25,ru={aborted_refunded:"Payment was refunded â no one was registered.",abort_refund_pending:"Registration failed â the refund is still processing; verify in Stripe before re-charging.",payment_declined:"The card was declined â no one was registered. Try a different card.",reversed_before_confirm:"The payment was refunded/disputed before completion â no one was registered."};function iu(t,s){return t&&ru[t]?ru[t]:s||"Registration failed â no one was registered."}function Ya(t,s){if(Ta.isAxiosError(t)){const a=t.response?.data?.detail;if(typeof a=="string"&&a.trim())return a;if(Array.isArray(a)){const n=a.flatMap(r=>typeof r!="object"||r===null||!("msg"in r)||typeof r.msg!="string"?[]:[r.msg]);if(n.length)return n.join(" ")}}return t instanceof Error&&t.message?t.message:s}function qf(t,s){const a=t.trim();return a!==""&&s!==void 0&&a!==s}function Uo(t){return`ams_admin_reg_order_key_${t}`}
4function La(t,s){return`${t}::${s}`}function gr(t,s){return`${t}::${s}`}function u4(t,s){return JSON.stringify(t)===JSON.stringify(s)}function If({eventId:t,onClose:s,walkIn:a=!1}){const{selectedSocietyId:n}=V(),r=J(),{data:i,isLoading:l}=Pi(t),m=Lg(),{data:c}=m,{data:d,isSuccess:u,isError:h,fetchStatus:p,refetch:x}=go(),{data:f,isSuccess:b,isError:N,fetchStatus:j,refetch:w}=er(),v=u&&b,k=h||N||p==="idle"&&!u||j==="idle"&&!b,S=E2(),_=T2(),y=F2(),C=R2(),[P,A]=o.useState({}),[E,Q]=o.useState(null),[U,D]=o.useState(""),[K,xe]=o.useState(0),[z,ae]=o.useState(null),[ue,_e]=o.useState(null),[ee,se]=o.useState(1),[le,oe]=o.useState({kind:"wizard"}),[Pe,M]=o.useState([]),[I,R]=o.useState({}),[X,Se]=o.useState({}),[ce,ke]=o.useState({}),[ve,Ne]=o.useState({}),Qe=o.useRef(new Set),[Oe,Ce]=o.useState({}),[ze,Ze]=o.useState({}),[Re,de]=o.useState(null),[ge,mt]=o.useState(""),[ye,Ke]=o.useState(null),[ut,De]=o.useState("keyed_card"),[he,Xe]=o.useState(""),[rt,yt]=o.useState(""),[dt,jt]=o.useState(null),[Ot,be]=o.useState(null),[lt,ht]=o.useState(!1),[zt,Tt]=o.useState(null),[Jt,is]=o.useState(!1),[Va,nt]=o.useState(""),[Vt,et]=o.useState(!1),bt=o.useRef(null),qt=o.useRef(!1),xs=o.useRef(null);xs.current===null&&(xs.current=V2(te=>te.failedNames));const ns=xs.current,[ua,aa]=o.useState(null);o.useEffect(()=>(qt.current=!1,ns.markAlive(),()=>{qt.current=!0;const te=ns.markDead();te&&Ut.error(te)}),[ns]);const _s=o.useMemo(()=>Tl(i?.registration_form_config,d,f),[i?.registration_form_config,d,f]),Ls=o.useMemo(()=>(c??[]).filter(te=>te.parent_event_id===t&&te.status==="published"),[c,t]),pe=o.useMemo(()=>{const te={};
4i&&(te[i.id]={eventId:i.id,name:i.name,fields:_s,sections:i.form_sections??[]});for(const fe of Ls)te[fe.id]={eventId:fe.id,name:fe.name,fields:Tl(fe.registration_form_config,d,f),sections:fe.form_sections??[]};return te},[i,_s,Ls,d,f]),Z=o.useCallback(te=>{const fe=[];i&&pe[i.id]&&fe.push(pe[i.id]);const Ye=new Set(I[te]??[]);for(const st of Ls)Ye.has(st.id)&&pe[st.id]&&fe.push(pe[st.id]);return fe},[i,pe,I,Ls]),We=o.useCallback((te,fe,Ye)=>{const st=La(te,fe);Se(at=>{const vt=at[st];return vt&&u4(vt,Ye.values)?at:{...at,[st]:Ye.values}}),ke(at=>at[st]===Ye.canSubmit?at:{...at,[st]:Ye.canSubmit})},[]);o.useEffect(()=>{if(!v)return;const te=[];for(const at of Pe)for(const vt of Z(at.id))vt.fields.length!==0&&te.push({key:La(at.id,vt.eventId),member:at,fields:vt.fields});const fe=new Set(Qe.current),{next:Ye,newlySeeded:st}=Ym(ve,fe,te);if(st.length!==0){for(const at of st)Qe.current.add(at);Ne(at=>Ym(at,fe,te).next);for(const at of te){if(!st.includes(at.key))continue;const vt=Ye[at.key]??{},gs=In(at.fields,vt),[Es,rs]=at.key.split("::");We(Es,rs,{values:Pc(gs,vt),canSubmit:On(gs,vt).size===0})}}},[Pe,Z,ve,We,v]);const Ve=o.useCallback((te,fe,Ye,st)=>{const at=La(te,fe),vt={...ve[at]??{},[Ye]:st};Ne(Es=>({...Es,[at]:{...Es[at]??{},[Ye]:st}}));const gs=pe[fe];if(gs){const Es=In(gs.fields,vt);We(te,fe,{values:Pc(Es,vt),canSubmit:On(Es,vt).size===0})}},[ve,pe,We]),xt=o.useMemo(()=>{for(const te of Pe)for(const fe of Z(te.id))if(fe.fields.length!==0&&ce[La(te.id,fe.eventId)]===!1)return!1;return!0},[Pe,Z,ce]),Ht=o.useCallback(()=>{try{sessionStorage.removeItem(Uo(t))}catch{}bt.current=null},[t]),Zt=o.useCallback(te=>{if((te.kind==="success"||te.kind==="failed"||te.kind==="refunded")&&Ht(),te.kind==="failed"||te.kind==="refunded"){const fe=ns.markDead();fe&&Ut.error(fe)}te.kind==="success"&&Af(r),oe(te)},[Ht,r,ns]),Cs=o.useRef(async()=>{}),Ga=o.useCallback(async te=>{if(!qt.current){if(te.status==="paid"){Zt({kind:"success",registrationIds:[]});return}if(te.status==="refunded"){Zt({kind:"refunded"});return}if(te.status==="failed"){Zt({kind:"failed",reason:te.failure_reason,message:iu(te.failure_reason,te.error)});return}if(te.client_secret&&te.publishable_key){oe({kind:"card_confirm",orderId:te.order_id,clientSecret:te.client_secret,publishableKey:te.publishable_key});return}if(te.pi_status==="processing"){oe({kind:"polling",orderId:te.order_id});return}if(te.pi_status==="succeeded"){try{const fe=await y.mutateAsync(te.order_id);await Cs.current(fe)}catch(fe){if(fe instanceof Dn)oe({kind:"polling",orderId:te.order_id});else throw fe}return}try{const fe=await C.mutateAsync(te.order_id);await Cs.current(fe)}catch(fe){if(fe instanceof Dn)oe({kind:"polling",orderId:te.order_id});else throw fe}}},[Zt,y,C]);Cs.current=Ga;const Is=o.useCallback(async te=>{if(!qt.current){if(_e({total:te.total,lines:te.lines}),te.status==="paid"){Zt({kind:"success",registrationIds:te.registration_ids});return}if(te.status==="refunded"){Zt({kind:"refunded"});return}if(te.status==="failed"){Zt({kind:"failed",reason:te.failure_reason,message:iu(te.failure_reason,null)});return}if(te.pi_status==="succeeded"){try{const fe=await y.mutateAsync(te.order_id);await Cs.current(fe)}catch(fe){if(fe instanceof Dn)oe({kind:"polling",orderId:te.order_id});else throw fe}return}if(te.client_secret&&te.publishable_key){oe({kind:"card_confirm",orderId:te.order_id,clientSecret:te.client_secret,publishableKey:te.publishable_key});return}if(te.pi_status==="processing"){oe({kind:"polling",orderId:te.order_id});return}try{const fe=await C.mutateAsync(te.order_id);await Cs.current(fe)}catch(fe){if(fe instanceof Dn)oe({kind:"polling",orderId:te.order_id});else throw fe}}},[Zt,y,C]),na=o.useCallback(async te=>{oe({kind:"recovery"}),nt("Previous attempt unresolved â checkingâ¦");let fe=0;for(;!qt.current&&bt.current===te;){try{const st=await Ia.findRegistrationOrderByKey(te,n);if(qt.current||bt.current!==te)return;if(st){await Is(st);return}nt("Previous attempt unresolved â checkingâ¦")}catch{nt("Could not check the previous payment. Retryingâ¦")}fe+=1;const Ye=Math.min(2e3*fe,15e3);await new Promise(st=>setTimeout(st,Ye))}},[n,Is]),Qr=o.useRef(!1);o.useEffect(()=>{if(Qr.current)return;Qr.current=!0;let te=null;try{te=sessionStorage.getItem(Uo(t))}catch{}te&&(bt.current=te,na(te))},[t,na]);const B=o.useCallback(async()=>
4{if(bt.current){is(!0);try{const te=await Ia.findRegistrationOrderByKey(bt.current,n);if(te){await Is(te);return}Ht(),et(!1),oe({kind:"wizard"}),se(1)}catch(te){nt(Ya(te,"Could not check the previous payment. Please try again."))}finally{is(!1)}}},[n,Is,Ht]),we=le.kind==="polling"?le.orderId:null,Je=M2(we),it=o.useRef(!1),ct=o.useRef(0);o.useEffect(()=>{if(le.kind!=="polling"||!Je.data||it.current||ct.current===Je.dataUpdatedAt)return;const te=Je.data;te.status==="pending"&&te.pi_status==="processing"||(it.current=!0,ct.current=Je.dataUpdatedAt,(async()=>{try{await Is(te)}catch(fe){Tt(Ya(fe,"Could not check this payment. Keep this page open while we retry."))}finally{it.current=!1}})())},[le,Je.data,Je.dataUpdatedAt,Is]);const Nt=o.useCallback(te=>{const fe=(st,at)=>{const vt={event_id:st,registrant_member_id:at.id,registration_data:X[La(at.id,st)]??{}};if(a&&P[st]&&(vt.claim_membership_offer=!0),te){const gs=gr(st,at.id),Es=Oe[gs];if(Es&&(a?Es.amount.trim()!=="":qf(Es.amount,ze[gs]))){const rs=parseFloat(Es.amount);!isNaN(rs)&&rs>=0&&(vt.price_override=rs,vt.price_override_reason=Es.reason.trim()||null)}}return vt},Ye=[];for(const st of Pe){Ye.push(fe(t,st));for(const at of I[st.id]??[])Ye.push(fe(at,st))}return Ye},[Pe,Oe,ze,X,t,I,a,P]),Mt=JSON.stringify({parent_event_id:t,items:Nt(!0)}),lr=a&&Pe.length===1&&(ee===2||ee===3)&&le.kind==="wizard";o.useEffect(()=>{if(!lr||!n)return;let te=!0;Q(null),D("");const fe=setTimeout(()=>{const Ye=JSON.parse(Mt);Ia.validateRegistrationOrder(Ye,n).then(st=>{if(!te)return;de(st),D(Mt);const at=Ye.items.filter(vt=>vt.claim_membership_offer&&st.lines.some(gs=>gs.event_id===vt.event_id&&!gs.offer_eligible));at.length>0&&(A(vt=>{const gs={...vt};for(const Es of at)delete gs[Es.event_id];return gs}),ae("The free membership offer is no longer available for a selected registration. It was removed; review the updated rate."))}).catch(st=>{te&&Q(Ya(st,"Could not load the registration rate."))})},300);return()=>{te=!1,clearTimeout(fe)}},[lr,Mt,n,K]);const Di=o.useCallback(()=>{const te=Re?parseFloat(Re.total)===0:!1;return ut==="member_card_on_file"&&!te?{mode:"member_card_on_file",payer_member_id:dt?.id??null,payment_method_id:Ot,authorization_attested:lt,payer_name:dt?`${dt.first_name} ${dt.last_name}`:null,payer_email:dt?.email??null}:{mode:"keyed_card",payer_name:he.trim()||null,payer_email:rt.trim()||null}},[ut,dt,Ot,lt,he,rt,Re]),gn=o.useCallback(async(te,fe)=>{Tt(null);const Ye=fe===void 0?ye:fe,st=gs=>S.mutateAsync({parent_event_id:t,items:Nt(te),...gs?{promo_code:gs}:{}});let at=await st(Ye??null),vt=!1;if(Ye&&!at.promo_code){vt=!0,Ke(null);const gs=at.batch_errors.find(Es=>Es.toLowerCase().includes("promo"))??"Promo code could not be applied.";return at=await st(null),de(at),Tt(gs),{quote:at,promoDropped:vt}}return de(at),{quote:at,promoDropped:vt}},[S,t,Nt,ye]),Dy=o.useCallback(async()=>{const te=ge.trim().toUpperCase();if(!(!te||Jt)){is(!0);try{Ke(te),await gn(!0,te)}catch(fe){Ke(null),Tt(Ya(fe,"Could not apply the promo code."))}finally{is(!1)}}},[ge,Jt,gn]),Ly=o.useCallback(async()=>{if(!Jt){is(!0);try{Ke(null),mt(""),await gn(!0,null)}catch(te){Tt(Ya(te,"Could not re-price this batch."))}finally{is(!1)}}},[Jt,gn]),$y=o.useCallback(async()=>{is(!0);try{const{quote:te}=await gn(!1),fe={};for(const Ye of te.lines)fe[gr(Ye.event_id,Ye.registrant_member_id)]=Ye.final_amount;Ze(fe),Ce(Ye=>{const st={...Ye};for(const at of te.lines){const vt=gr(at.event_id,at.registrant_member_id);st[vt]||(st[vt]={amount:at.final_amount,reason:""})}return st}),se(3)}catch(te){Tt(Ya(te,"Could not price this batch."))}finally{is(!1)}},[gn]),Gd=o.useCallback(async()=>{is(!0);try{const{quote:te,promoDropped:fe}=await gn(!0);if(fe)return;if(!te.valid){a&&xe(Ye=>Ye+1),Tt("Please resolve the pricing issues before continuing.");return}if(a&&Re&&Wi(Re,te)){ae(Wi(Re,te));return}se(4)}catch(te){Tt(Ya(te,"Could not re-price this batch."))}finally{is(!1)}},[gn,a,Re]),Yd=o.useCallback(()=>{const te=Pe.map(fe=>({member:fe,forms:Z(fe.id).filter(Ye=>Ye.fields.length>0).map(Ye=>({fields:Ye.fields,cleanedValues:X[La(fe.id,Ye.eventId)]??{}}))}));X2({registrants:te,getMember:fe=>Gt.get(fe,n||void 0),updateMember:(fe,Ye)=>Gt.update(fe,Ye,n||void 0)}).then(fe=>{const Ye=ns.setResult(fe);Ye&&Ut.error(Ye),qt.current||aa(fe)})},[Pe,Z,X,n,ns]),Hd=o.useCallback(async()=>
4{if(!Re||Jt)return;Tt(null),is(!0),bt.current||(bt.current=typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`);const te=bt.current;try{sessionStorage.setItem(Uo(t),te)}catch{}try{const fe=await _.mutateAsync({parent_event_id:t,items:Nt(!0),payer:Di(),idempotency_key:te,expected_lines:Re.lines.map(Ye=>({event_id:Ye.event_id,registrant_member_id:Ye.registrant_member_id,final_amount:Ye.final_amount,...a&&P[Ye.event_id]?{offer_months:Ye.offer_months}:{}})),...Re.promo_code?{promo_code:Re.promo_code,expected_discount:Re.discount_amount}:{}});Yd(),_e({total:Re.total,lines:Re.lines}),await Ga(fe)}catch(fe){fe instanceof Sf?(de(fe.quote),Ke(fe.quote.promo_code??null),se(3),Tt("Prices, availability or membership terms changed. Review the updated registration."),a&&(Ht(),ae(Wi(Re,fe.quote)||"Registration availability changed. Review the messages below."),D(""),xe(Ye=>Ye+1))):fe instanceof Cf?(de(fe.quote),Ke(fe.quote.promo_code??null),fe.quote.promo_code||mt(""),se(3),a&&(Ht(),ae(Wi(Re,fe.quote)||"Registration details or offer eligibility changed. Review the messages below."),D(""),xe(Ye=>Ye+1)),Tt(fe.quote.batch_errors[0]??"Order validation failed â review the reported issues.")):fe instanceof Dn?oe({kind:"polling",orderId:fe.orderId}):fe instanceof Pf?(a&&na(te),Tt("This attempt was already submitted with different details. Reload to retry.")):(Tt(Ya(fe,"Could not submit the order.")),a&&Ta.isAxiosError(fe)&&fe.response?.status===422?(Ht(),se(2),D(""),xe(Ye=>Ye+1)):a&&na(te))}finally{is(!1)}},[Re,Jt,t,Nt,Di,_,Ga,Yd,a,P,Ht,na]),qy=o.useCallback(te=>{const fe=[t,...I[te]??[]].map(st=>La(te,st)),Ye=Jm(fe,{raw:ve,cleaned:X,validity:ce,seeded:Qe.current});Qe.current=Ye.seeded,Ne(Ye.raw),Se(Ye.cleaned),ke(Ye.validity),M(st=>st.filter(at=>at.id!==te)),R(st=>{const at={...st};return delete at[te],at})},[t,I,ve,X,ce]),Jd=o.useCallback((te,fe)=>{if((I[te]??[]).includes(fe)){A(at=>{const vt={...at};return delete vt[fe],vt}),Ce(at=>{const vt={...at};return delete vt[gr(fe,te)],vt});const st=Jm([La(te,fe)],{raw:ve,cleaned:X,validity:ce,seeded:Qe.current});Qe.current=st.seeded,Ne(st.raw),Se(st.cleaned),ke(st.validity)}R(st=>{const at=st[te]??[],vt=at.includes(fe);return{...st,[te]:vt?at.filter(gs=>gs!==fe):[...at,fe]}})},[I,ve,X,ce]),Li=o.useMemo(()=>ua?.members.filter(te=>te.failures.length>0)??[],[ua]),$i=Li.length>0;o.useEffect(()=>{le.kind==="success"&&$i&&ns.markSurfaced()},[le.kind,$i,ns]);const Zd=o.useCallback(te=>n4(te,{getMember:fe=>Gt.get(fe,n||void 0),updateMember:(fe,Ye)=>Gt.update(fe,Ye,n||void 0)}),[n]);if(l)return e.jsxs("div",{className:"space-y-3 py-4",children:[e.jsx(Y,{className:"h-8 w-full"}),e.jsx(Y,{className:"h-24 w-full"})]});if(le.kind==="recovery")return e.jsx(y4,{message:Va,busy:Jt,abandonConfirming:Vt,onAbandonRequest:()=>et(!0),onAbandonCancel:()=>et(!1),onAbandonConfirm:()=>{B()}});if(le.kind==="polling")return e.jsxs("div",{className:"flex flex-col items-center gap-3 py-10 text-center",children:[e.jsx(He,{className:"h-8 w-8 animate-spin text-primary"}),e.jsx("p",{className:"text-sm font-medium",children:"Finalizing paymentâ¦"}),(Je.isError||zt)&&e.jsx("p",{role:"alert",className:"text-sm text-destructive",children:zt||"Could not check payment status. Retryingâ¦"}),Je.isError&&e.jsx(g,{variant:"outline",className:"min-h-[44px]",onClick:()=>{Je.refetch()},children:"Check payment status"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This can take a moment. Please don't close this window."})]});if(le.kind==="card_confirm"){const te=le.orderId;return e.jsxs("div",{className:"space-y-4",children:[a&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Step 3 of 3 · Pay"}),e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("span",{className:"flex h-7 w-7 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(Qt,{className:"h-4 w-4"})}),e.jsx("h2",{className:"text-lg font-semibold tracking-tight",children:"Enter card details"})]}),e.jsxs("div",{className:"flex flex-wrap justify-between gap-3 rounded-md border border-border bg-muted/30 p-3",children:[e.jsx("p",{className:"text-sm",children:ue?.lines[0]?.registrant_name??Pe[0]?.first_name}),e.jsxs("p",{className:"text-2xl font-semibold tracking-tight",children:["$",ue?.total??Re?.total]})]})]}),e.jsx(Q2,{cardOnly:a,clientSecret:le.clientSecret,publishableKey:le.publishableKey,onSucceeded:async()=>{is(!0),Tt(null);try{const fe=await y.mutateAsync(te);await Ga(fe)}
4catch(fe){fe instanceof Dn||Tt(Ya(fe,"Payment succeeded. Checking that registration completedâ¦")),oe({kind:"polling",orderId:te})}finally{is(!1)}},onProcessing:()=>{Tt(null),oe({kind:"polling",orderId:te})}})]})}if(a&&le.kind==="success"){const te=ue??Re;return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"flex h-10 w-10 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(Kt,{className:"h-5 w-5"})}),e.jsx("h2",{className:"text-lg font-semibold tracking-tight",children:"Registration complete"})]}),e.jsxs("p",{className:"inline-flex items-center gap-2 text-sm",children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-emerald-500","aria-hidden":"true"}),"Paid",te?` · $${te.total}`:""]}),te?.lines.map(fe=>e.jsxs("div",{className:"flex flex-wrap justify-between gap-2 rounded-md border border-border p-3 text-sm",children:[e.jsxs("span",{className:"min-w-0 break-words",children:[fe.registrant_name," ·"," ",pe[fe.event_id]?.name??"Event registration"]}),e.jsxs("span",{children:["$",fe.final_amount]})]},`${fe.event_id}:${fe.registrant_member_id}`)),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Receipt + confirmation emails on their way."}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"For connected events, badge and session access sync automatically to the event app."})]}),e.jsx(g,{className:"min-h-[44px] w-full",onClick:s,children:"Next walk-in"}),$i&&e.jsx(nu,{secondaryActions:!0,members:Li,onRetry:Zd,onDismiss:()=>aa(null)})]})}if(le.kind==="success")return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-col items-center gap-3 py-10 text-center",children:[e.jsx(Kt,{className:"h-10 w-10 text-emerald-500"}),e.jsx("p",{className:"text-base font-semibold tracking-tight",children:"Registrations complete"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:le.registrationIds.length>0?`${le.registrationIds.length} registration${le.registrationIds.length===1?"":"s"} created.`:"The order is paid and registrations are created."}),e.jsx(g,{className:"mt-2",onClick:s,children:"Done"})]}),$i&&e.jsx(nu,{members:Li,onRetry:Zd,onDismiss:()=>aa(null)},Li.map(te=>te.memberId).join(","))]});if(le.kind==="refunded")return e.jsx(ou,{tone:"warn",title:"Order refunded",body:"This order was refunded â no one is registered.",actionLabel:a?"Next walk-in":"Close",onClose:s});if(le.kind==="failed")return e.jsx(ou,{tone:"danger",title:"Registration failed",body:le.message,actionLabel:a?"Next walk-in":"Close",onClose:s});const Xd=h4(ee,{members:Pe,formsValid:xt,formDefsReady:v,quote:Re,payerMode:ut,payerName:he,payerEmail:rt,payerMember:dt,paymentMethodId:Ot,attested:lt}),em=[pe[t],...Ls.map(te=>pe[te.id])].filter(te=>!!te),Iy=em.some(te=>te.fields.length>0&&Hm(Pe,I,te.eventId,t).length>0);if(a){const te=Pe[0],fe=ee===2||ee===3,Ye=fe&&U!==Mt&&!E,st=te?Z(te.id):[],at=v&&st.every(rs=>{const va=ve[La(te.id,rs.eventId)]??{};return On(In(rs.fields,va),va).size===0}),vt=Nt(!1).every(rs=>{const va=Oe[gr(rs.event_id,rs.registrant_member_id)];return va?.amount.trim()?/^\d+(\.\d{1,2})?$/.test(va.amount.trim())&&Number.isFinite(Number(va.amount))&&!!va.reason.trim():!0}),gs=!Jt&&!Ye&&!E&&m.isSuccess&&at&&vt&&!!Re?.valid&&Re.lines.length>0,Es=ee===1?fa:fe?vr:Qt;return e.jsxs("div",{className:"space-y-5",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Step ",ee===1?1:fe?2:3," of 3 · One person at a time"]}),e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(Es,{className:"h-4 w-4"})}),e.jsx("h2",{className:"text-lg font-semibold tracking-tight",children:ee===1?"Find person":fe?"Rate & details":"Pay"})]}),ee===1&&e.jsx(L2,{onSelect:rs=>{M([rs]),Xe(`${rs.first_name} ${rs.last_name}`),yt(rs.email),ae(null),se(2)}}),te&&ee!==1&&e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 rounded-md border border-border bg-muted/30 p-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("p",{className:"break-words text-sm font-medium",children:[te.first_name," ",te.last_name]}),e.jsx("p",{className:"break-words text-sm text-muted-foreground",children:te.email})]}),fe&&e.jsx(g,{variant:"ghost",className:"min-h-[44px]",disabled:Jt,onClick:s,children:"Change person"})]}),z&&e.jsx("p",{role:"status",className:"rounded-md border border-border bg-muted/30 p-3 text-sm",children:z}),fe&&te&&e.jsxs(e.Fragment,{children:[m.isPending&&e.jsx("p",{role:"status",className:"text-sm text-muted-foreground",children:"Loading add-on sessionsâ¦"}),m.isError&&e.jsxs("div",{role:"alert",className:"text-sm",children:[e.jsx("p",{children:"Could not load add-on sessions."}),e.jsx(g,{className:"min-h-[44px]",variant:"outline",onClick:()=>{m.refetch()},children:"Retry sessions"})]}),e.jsx("fieldset",{disabled:Jt,className:"min-w-0",children:e.jsx(K2,{member:te,children:Ls,selectedChildren:I[te.id]??[],forms:st,rawResponses:ve,formsReady:v,formsError:k,quote:Re,quotePending:Ye,quoteError:E,claims:P,overrides:Oe,onToggleChild:rs=>Jd(te.id,rs),onClaim:(rs,va)=>{ae(null),A(qi=>({...qi,[rs]:va}))},onOverride:(rs,va)=>Ce(qi=>({...qi,[rs]:{...qi[rs]??{amount:"",reason:""},...va}})),onField:Ve,onRetry:()=>{D(""),xe(rs=>rs+1),x(),w()}})}),!vt&&e.jsx("p",{role:"alert",className:"text-sm text-destructive",children:"Enter a non-negative amount with up to two decimal places and a reason for each price override."}),e.jsxs("div",{className:"sticky bottom-0 space-y-3 border-t border-border bg-card py-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"text-sm font-medium",children:"Total"}),e.jsx("span",{className:"text-2xl font-semibold tracking-tight",children:Ye?"Updatingâ¦":!E&&Re?`$${Re.total}`:"â"})]}),e.jsxs(g,{className:"min-h-[44px] w-full",disabled:!gs,onClick:()=>{Gd()},children:[Jt&&e.jsx(He,{className:"mr-2 h-4 w-4 animate-spin"}),"Continue to payment"]}),!at&&v&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Complete the required details to continue."})]})]}),ee===4&&Re&&e.jsxs("form",{className:"space-y-4",onSubmit:rs=>{rs.preventDefault(),Hd()},children:[e.jsx("fieldset",{disabled:Jt,className:"min-w-0",children:e.jsx(lu,{quote:Re,keyedOnly:!0,mode:"keyed_card",onModeChange:De,payerName:he,onPayerName:Xe,payerEmail:rt,onPayerEmail:yt,payerMember:null,onPayerMember:jt,paymentMethodId:null,onPaymentMethodId:be,attested:!1,onAttested:ht})}),e.jsxs(g,{type:"submit",className:"min-h-[44px] w-full",disabled:Jt||!Xd,children:[Jt&&e.jsx(He,{className:"mr-2 h-4 w-4 animate-spin"}),Number(Re.total)===0?"Complete registration":"Continue to card entry"]}),e.jsx(g,{type:"button",variant:"ghost",className:"min-h-[44px] w-full",disabled:Jt,onClick:()=>{se(2),Tt(null)},children:"Back to rate & details"})]}),zt&&e.jsx("p",{role:"alert",className:"text-sm text-destructive",children:zt})]})}return e.jsxs("div",{className:"space-y-5",children:[e.jsx(p4,{step:ee}),ee===1&&e.jsx(x4,{members:Pe,publishedChildren:Ls,childSelections:I,onAdd:te=>M(fe=>fe.some(Ye=>Ye.id===te.id)||fe.length>=$f?fe:[...fe,te]),onRemove:qy,onToggleChild:Jd}),ee===2&&!v&&!k&&e.jsxs("div",{className:"space-y-3 py-4","data-tour":"reg-forms",children:[e.jsx(Y,{className:"h-8 w-full"}),e.jsx(Y,{className:"h-32 w-full"})]}),ee===2&&k&&e.jsx("div",{className:"rounded-md border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-800 dark:border-red-800 dark:bg-red-950/20 dark:text-red-200",children:"Couldn't load the registration form definitions â close and reopen the dialog to retry."}),ee===2&&v&&e.jsx("div",{className:"space-y-6","data-tour":"reg-forms",children:Iy?em.map(te=>{const fe=Hm(Pe,I,te.eventId,t);
4if(fe.length===0||te.fields.length===0)return null;const Ye=Object.fromEntries(fe.map(st=>[st.id,ve[La(st.id,te.eventId)]??{}]));return e.jsx(Rf,{form:te,registrants:fe,rawValuesByMember:Ye,onChangeValue:(st,at,vt)=>Ve(st,te.eventId,at,vt)},te.eventId)}):e.jsx("p",{className:"py-4 text-sm text-muted-foreground",children:"These registrations collect no information â continue to review pricing."})}),ee===3&&Re&&e.jsx(g4,{quote:Re,overrides:Oe,overrideBaselines:ze,eventNameById:pe,onOverrideChange:(te,fe)=>Ce(Ye=>({...Ye,[te]:{...Ye[te]??{amount:"",reason:""},...fe}})),promoInput:ge,onPromoInput:mt,onApplyPromo:()=>{Dy()},onRemovePromo:()=>{Ly()},promoBusy:Jt}),ee===4&&Re&&e.jsx(lu,{quote:Re,mode:ut,onModeChange:De,payerName:he,onPayerName:Xe,payerEmail:rt,onPayerEmail:yt,payerMember:dt,onPayerMember:jt,paymentMethodId:Ot,onPaymentMethodId:be,attested:lt,onAttested:ht}),ee===2&&v&&!xt&&e.jsx("div",{className:"rounded-md border border-amber-300 bg-amber-50 px-3 py-2 text-sm text-amber-800 dark:border-amber-700/60 dark:bg-amber-950/30 dark:text-amber-200",children:"Answer the required questions highlighted above before continuing."}),zt&&e.jsx("div",{className:"rounded-md border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-800 dark:border-red-800 dark:bg-red-950/20 dark:text-red-200",children:zt}),e.jsx(f4,{step:ee,busy:Jt,canNext:Xd,isFreeOrder:Re?parseFloat(Re.total)===0:!1,onBack:()=>{Tt(null),se(te=>te>1?te-1:te)},onNext:()=>{ee===1?se(2):ee===2?$y():ee===3?Gd():ee===4&&Hd()}})]})}function Wi(t,s){const a=[];t.total!==s.total&&a.push(`Total changed from $${t.total} to $${s.total}.`);for(const n of s.lines){const r=t.lines.find(i=>i.event_id===n.event_id&&i.registrant_member_id===n.registrant_member_id);r&&(r.final_amount!==n.final_amount&&a.push(`${n.registrant_name}: $${r.final_amount} â $${n.final_amount}.`),r.offer_months!==n.offer_months&&a.push(`Free membership changed from ${r.offer_months??0} to ${n.offer_months??0} months.`),r.offer_eligible&&!n.offer_eligible&&a.push("The free membership offer is no longer available."),r.rate_label!==n.rate_label&&a.push("The applicable registration rate changed."))}return a.length?a.join(" "):null}function h4(t,s){return t===1?s.members.length>0:t===2?s.formDefsReady&&s.formsValid:t===3?s.quote?.valid??!1:t===4?(s.quote?parseFloat(s.quote.total)===0:!1)||s.payerMode==="keyed_card"?s.payerName.trim().length>0&&s.payerEmail.trim().length>0:!!s.payerMember&&!!s.paymentMethodId&&s.attested:!0}function p4({step:t}){const s=["Members","Forms","Review","Payment"];return e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:s.map((a,n)=>{const r=n+1,i=r===t,l=r<t;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:me("flex h-6 w-6 items-center justify-center rounded-full text-xs font-medium",i?"bg-primary text-primary-foreground":l?"bg-emerald-500 text-white":"bg-muted text-muted-foreground"),children:r}),e.jsx("span",{className:me("text-xs font-medium",i?"text-foreground":"text-muted-foreground"),children:a}),r<s.length&&e.jsx("span",{className:"text-muted-foreground/40",children:"âº"})]},a)})})}function x4({members:t,publishedChildren:s,childSelections:a,onAdd:n,onRemove:r,onToggleChild:i}){return e.jsxs("div",{className:"space-y-3","data-tour":"reg-member-search",children:[e.jsx(ho,{selectedMember:null,onSelectMember:n,onClearMember:()=>{},label:"Add registrants",placeholder:"Search by name or emailâ¦",inputId:"add-reg-member-search"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[t.length," of ",$f," selected"]}),t.length>0&&e.jsx("div",{className:"space-y-1.5",children:t.map(l=>{const m=a[l.id]??[];return e.jsxs("div",{className:"rounded-md border px-3 py-2 text-sm",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("span",{className:"font-medium",children:[l.first_name," ",l.last_name]}),e.jsx("span",{className:"ml-2 text-muted-foreground",children:l.email}),l.membership_type_name&&e.jsxs("span",{className:"ml-2 text-xs text-muted-foreground",children:["· ",l.membership_type_name]})]}),e.jsx(g,{type:"button",variant:"ghost",size:"sm",onClick:()=>r(l.id),children:"Remove"})]}),s.length>0&&e.jsxs("div",{className:"mt-2 border-t pt-2",children:[e.jsx("p",{className:"mb-1 text-[11px] font-medium uppercase tracking-wider text-muted-foreground
4/80",children:"Add-on sessions"}),e.jsx("div",{className:"space-y-1",children:s.map(c=>e.jsxs("label",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(ot,{checked:m.includes(c.id),onCheckedChange:()=>i(l.id,c.id)}),c.name]},c.id))})]})]},l.id)})})]})}function g4({quote:t,overrides:s,overrideBaselines:a,eventNameById:n,onOverrideChange:r,promoInput:i,onPromoInput:l,onApplyPromo:m,onRemovePromo:c,promoBusy:d}){const u=parseFloat(t.discount_amount||"0")>0;return e.jsxs("div",{className:"space-y-3","data-tour":"reg-review",children:[t.batch_errors.length>0&&e.jsx("div",{className:"rounded-md border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-800 dark:border-red-800 dark:bg-red-950/20 dark:text-red-200",children:e.jsx("ul",{className:"list-disc pl-4",children:t.batch_errors.map((h,p)=>e.jsx("li",{children:h},p))})}),e.jsx("div",{className:"space-y-2",children:t.lines.map(h=>{const p=gr(h.event_id,h.registrant_member_id),x=s[p]??{amount:h.final_amount,reason:""},f=qf(x.amount,a[p]),b=parseFloat(x.amount||h.final_amount)===0,N=n[h.event_id]?.name;return e.jsxs("div",{className:"rounded-md border p-3",children:[e.jsx("div",{className:"flex items-center justify-between gap-3",children:e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium",children:h.registrant_name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[N?`${N} · `:"",h.rate_label,h.eligibility_override&&" · eligibility override",b&&" · comp ($0)"]})]})}),e.jsx(Mf,{id:`override-${p}`,amount:x.amount,reason:x.reason,overridden:f,onChange:j=>r(p,j)}),h.errors.length>0&&e.jsx("p",{className:"mt-1 text-xs font-medium text-red-600 dark:text-red-400",children:h.errors.join(", ")})]},p)})}),t.promo_code?e.jsxs("div",{className:"flex items-center justify-between rounded-md border bg-muted/40 px-3 py-2",children:[e.jsxs("p",{className:"text-sm",children:["Promo ",e.jsx("span",{className:"font-medium",children:t.promo_code}),e.jsxs("span",{className:"text-muted-foreground",children:[" â $",t.discount_amount," off"]})]}),e.jsx(g,{type:"button",variant:"ghost",size:"sm",disabled:d,onClick:c,children:"Remove"})]}):e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(O,{className:"h-9 max-w-56",placeholder:"Promo code",maxLength:50,value:i,onChange:h=>l(h.target.value),onKeyDown:h=>{h.key==="Enter"&&(h.preventDefault(),m())}}),e.jsx(g,{type:"button",variant:"outline",size:"sm",disabled:d||!i.trim(),onClick:m,children:"Apply"})]}),e.jsxs("div",{className:"space-y-1 border-t pt-3",children:[u&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Subtotal"}),e.jsxs("span",{className:"text-sm",children:["$",t.subtotal??t.total]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-sm text-muted-foreground",children:["Promo (",t.promo_code,")"]}),e.jsxs("span",{className:"text-sm",children:["â$",t.discount_amount]})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm font-medium",children:"Batch total"}),e.jsxs("span",{className:"text-base font-semibold tracking-tight",children:["$",t.total]})]})]})]})}function lu({keyedOnly:t=!1,quote:s,mode:a,onModeChange:n,payerName:r,onPayerName:i,payerEmail:l,onPayerEmail:m,payerMember:c,onPayerMember:d,paymentMethodId:u,onPaymentMethodId:h,attested:p,onAttested:x}){const f=parseFloat(s.total)===0,{data:b,isLoading:N}=A2(a==="member_card_on_file"?c?.id??void 0:void 0);return f?e.jsxs("div",{className:"space-y-4","data-tour":"reg-payment",children:[e.jsxs("div",{className:"rounded-md border bg-muted/40 px-3 py-2 text-sm",children:[t?"This registration totals ":"This batch totals ",e.jsx("span",{className:"font-semibold",children:"$0.00"}),s.promo_code?` after promo ${s.promo_code}`:""," â no payment is required. We still need payer identity for the receipt."]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(T,{htmlFor:"payer-name",children:"Payer name"}),e.jsx(O,{id:"payer-name",required:!0,autoComplete:"off",value:r,onChange:j=>i(j.target.value),placeholder:"Name for the receipt"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(T,{htmlFor:"payer-email",children:"Receipt email"}),e.jsx(O,{id:"payer-email",required:!0,autoComplete:"off",type:"email",value:l,onCh
4ange:j=>m(j.target.value),placeholder:"[email protected]"})]})]})]}):e.jsxs("div",{className:"space-y-4","data-tour":"reg-payment",children:[e.jsxs("div",{className:"rounded-md border bg-muted/40 px-3 py-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Total to charge"}),e.jsxs("span",{className:"text-base font-semibold tracking-tight",children:["$",s.total]})]}),s.promo_code&&e.jsxs("p",{className:"mt-0.5 text-xs text-muted-foreground",children:["Includes promo ",s.promo_code," (â$",s.discount_amount,")"]})]}),!t&&e.jsxs(Cn,{value:a,onValueChange:j=>n(j),className:"space-y-2",children:[e.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[e.jsx(la,{value:"keyed_card",id:"payer-keyed"}),e.jsx("span",{children:"Key in a card"})]}),e.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[e.jsx(la,{value:"member_card_on_file",id:"payer-on-file"}),e.jsx("span",{children:"Charge a member's card on file"})]})]}),a==="keyed_card"&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(T,{htmlFor:"payer-name",children:"Cardholder name"}),e.jsx(O,{id:"payer-name",required:!0,autoComplete:"off",value:r,onChange:j=>i(j.target.value),placeholder:"Name on the card"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(T,{htmlFor:"payer-email",children:"Receipt email"}),e.jsx(O,{id:"payer-email",required:!0,autoComplete:"off",type:"email",value:l,onChange:j=>m(j.target.value),placeholder:"[email protected]"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"You'll enter the card details on the next screen."})]}),a==="member_card_on_file"&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(ho,{selectedMember:c,onSelectMember:j=>{d(j),h(null)},onClearMember:()=>{d(null),h(null)},label:"Payer",placeholder:"Search the paying memberâ¦",inputId:"add-reg-payer-search"}),c&&e.jsx("div",{className:"space-y-2",children:N?e.jsx(Y,{className:"h-10 w-full"}):!b||b.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"This member has no saved cards. Use key-in-card instead."}):e.jsx(Cn,{value:u??"",onValueChange:j=>h(j),className:"space-y-1.5",children:b.map(j=>e.jsxs("label",{className:"flex items-center gap-2 rounded-md border px-3 py-2 text-sm",children:[e.jsx(la,{value:j.payment_method_id,id:`pm-${j.payment_method_id}`}),e.jsx(Qt,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"capitalize",children:j.brand}),e.jsxs("span",{className:"text-muted-foreground",children:["â¢â¢â¢â¢ ",j.last4]}),e.jsxs("span",{className:"ml-auto text-xs text-muted-foreground",children:[j.exp_month,"/",j.exp_year]})]},j.payment_method_id))})}),c&&b&&b.length>0&&e.jsxs("label",{className:"flex items-start gap-2 rounded-md border bg-muted/30 px-3 py-2 text-sm",children:[e.jsx(ot,{checked:p,onCheckedChange:j=>x(!!j),className:"mt-0.5"}),e.jsx("span",{className:"text-muted-foreground",children:"I confirm the payer authorized charging this saved card for these registrations."})]})]})]})}function f4({step:t,busy:s,canNext:a,isFreeOrder:n,onBack:r,onNext:i}){const l=t===1?"Next":t===2?"Review pricing":t===3?"Continue to payment":n?"Complete registration":"Charge & register";return e.jsxs("div",{className:"flex items-center justify-between border-t pt-4",children:[e.jsx(g,{type:"button",variant:"ghost",onClick:r,disabled:t===1||s,children:"Back"}),e.jsxs(g,{type:"button",onClick:i,disabled:!a||s,children:[s&&e.jsx(He,{className:"mr-1.5 h-4 w-4 animate-spin"}),l]})]})}function y4({message:t,busy:s,abandonConfirming:a,onAbandonRequest:n,onAbandonCancel:r,onAbandonConfirm:i}){return e.jsxs("div",{className:"flex flex-col items-center gap-3 py-8 text-center",children:[e.jsx(He,{className:"h-8 w-8 animate-spin text-amber-500"}),e.jsx("p",{className:"text-sm font-medium",children:t||"Previous attempt unresolved â checkingâ¦"}),e.jsx("p",{className:"max-w-md text-xs text-muted-foreground",children:"A previous registration attempt for this event hasn't reached a final state yet. We're checking on it so no one is charged twice."}),a?e.jsxs("div",{className:"mt-2 space-y-2 rounded-md border border-amber-300 bg-amber-50 px-3 py-3 text-left dark:border-amber-700/60 dark:bg-amber-950/30",children:[e.jsx("p",{className:"text-xs text-amber-800 dark:text-amber-200",children:"The previous attempt may still complete and charge the payer. Only abandon it if you're sure â we'll re-check before clearing it."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(g,{type:"button",size:"sm",variant:"ghost",onClick:r,disabled:s,children:"Keep checking"}),e.jsxs(g,{type:"button",size:"sm",onClick:i,disabled:s,children:[s&&e.jsx(He,{className:"mr-1.5 h-4 w-4 animate-spin"}),"Abandon & start over"]})]})]}):e.jsx(g,{type:"button",variant:"ghost",size:"sm",className:"mt-2",onClick:n,children:"Abandon previous attempt"})]})}function ou({tone:t,title:s,body:a,onClose:n,actionLabel:r="Close"}){const i=t==="danger"?"bg-red-500":"bg-amber-500";return e.jsxs("div",{className:"flex flex-col items-center gap-3 py-10 text-center",children:[e.jsx("span",{className:"flex h-10 w-10 items-center justify-center rounded-lg bg-brand-navy
4/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(Bt,{className:"h-5 w-5"})}),e.jsxs("p",{className:"inline-flex items-center gap-2 text-base font-semibold tracking-tight",children:[e.jsx("span",{className:me("h-1.5 w-1.5 rounded-full",i),"aria-hidden":"true"}),s]}),e.jsx("p",{className:"max-w-md text-sm text-muted-foreground",children:a}),e.jsx(g,{className:"mt-2 min-h-[44px]",variant:"outline",onClick:n,children:r})]})}function cu(t){return!!t.target?.closest?.("[data-tour-ui]")}function b4({eventId:t,eventName:s,open:a,onOpenChange:n}){return e.jsx(Fe,{open:a,onOpenChange:n,children:e.jsxs(Te,{className:"max-h-[90vh] w-[95vw] overflow-y-auto sm:max-w-2xl",onPointerDownOutside:r=>{cu(r)&&r.preventDefault()},onInteractOutside:r=>{cu(r)&&r.preventDefault()},children:[e.jsx(Ae,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(Lt,{className:"h-4 w-4"})}),e.jsxs(Ee,{children:["Add registrations â ",s]})]})}),a&&e.jsx(If,{eventId:t,onClose:()=>n(!1)})]})})}const Ml="_contact.",yr=["first_name","last_name","email","phone","organization","address_line1","address_line2","city","state","postal_code","country"];function j4(){return yr.reduce((t,s)=>({...t,[s]:""}),{})}function v4(t){const s={};for(const a of yr)t[a]&&(s[`${Ml}${a}`]=t[a]);return s}const bo=new Set(["first_name","last_name","email","phone","address","city","state","zip_code","country","organization"]);function w4(t){const{parent:s,selectedChildIds:a,memberHasParentRegistration:n}=t,i=(s.registration_form_fields?.fields??[]).some(d=>!bo.has(d.field_key)),l=!n&&i,m=(s.children??[]).filter(d=>a.includes(d.id)&&d.has_form),c=[{kind:"event"},{kind:"contact"}];l&&c.push({kind:"event-fields",eventId:s.id,eventName:s.name});for(const d of m)c.push({kind:"event-fields",eventId:d.id,eventName:d.name});return{steps:c,parentNeedsFields:l,childrenWithForms:m}}const N4=new Set(["cancelled","archived","pending","rejected","suspended"]);function k4(t){return!N4.has((t??"").toLowerCase())}function du(t){return!!t.target?.closest?.("[data-tour-ui]")}function _4(t){if(!t)return null;const s=Ct(t);return Number.isNaN(s.getTime())?null:s.toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"})}function Of(t){return t==null?"":typeof t=="boolean"?t?"Yes":"No":Array.isArray(t)?t.join(", "):typeof t=="object"?JSON.stringify(t):String(t)}function S4(t){if(!t)return null;const s=[`${Ml}city`,`${Ml}state`].map(a=>t[a]==null?"":Of(t[a]).trim()).filter(Boolean);return s.length?s.join(", "):null}const Dd=[{token:"first_name",label:"First name"},{token:"last_name",label:"Last name"},{token:"email",label:"Email"},{token:"organization",label:"Organization"},{token:"city",label:"City"},{token:"state",label:"State"},{token:"member_type",label:"Member type"},{token:"member_status",label:"Member status"},{token:"faculty_tag",label:"Faculty"},{token:"registered_at",label:"Registered at"},{token:"status",label:"Registration status"},{token:"price_paid",label:"Price paid"},{token:"is_guest",label:"Guest"}],Ld=[{token:"contact_phone",label:"Phone"},{token:"contact_address_line1",label:"Address line 1"},{token:"contact_address_line2",label:"Address line 2"},{token:"contact_postal_code",label:"Postal code"},{token:"contact_country",label:"Country"},{token:"contact_organization",label:"Organization"}],C4="legacy";function zo({groupId:t,title:s,columns:a,isChecked:n,onToggle:r,onSetAll:i}){const l=a.map(m=>m.token);return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx(T,{className:"text-sm font-medium",children:s}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx("button",{type:"button",className:"hover:text-foreground",onClick:()=>i(l,!0),children:"All"}),e.jsx("span",{"aria-hidden":"true",children:"·"}),e.jsx("button",{type:"button",className:"hover:text-foreground",onClick:()=>i(l,!1),children:"None"})]})]}),e.jsx("div",{className:"grid grid-cols-1 gap-2 rounded-md border p-3 sm:grid-cols-2",children:a.map((m,c)=>{const d=`${t}-${c}`;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ot,{id:d,checked:n(m.token),onCheckedChange:()=>r(m.token)}),e.jsx(T,{htmlFor:d,className:"cursor-pointer text-sm font-normal",children:m.label})]},m.token)})})]})}const P4=new Map([...Dd,...Ld].map(t=>[t.token,t.label])),mu=new Set(Dd.map(t=>t.token)),uu=new Set(Ld.map(t=>t.token));function A4({eventId:t,eventName:s,hasChildren:a=!1,open:n,onOpenChange:r}){const{selectedSocietyId:i}=V(),{data:l,isLoading:m,isError:c}=Pi(n?t:void 0),{data:d}=go(),{data:u}
4=er(),[h,p]=o.useState(!1),[x,f]=o.useState(!1),[b,N]=o.useState(new Set);o.useEffect(()=>{n&&(N(new Set),f(!1))},[n]);const j=re({queryKey:["admin","export-columns",t,x,i],queryFn:()=>Wt.getRegistrationExportColumns(t,i,!0),enabled:n&&x&&!!i}),w=o.useMemo(()=>[...Tl(l?.registration_form_config,d?.filter(z=>z.is_active),u).map(z=>({token:`field:${z.field_key}`,label:z.label||z.field_key})),{token:C4,label:"Other stored answers"}],[l?.registration_form_config,d,u]),v=o.useMemo(()=>!x||!j.data?null:j.data.map(z=>({token:z.token,label:P4.get(z.token)??z.label})),[x,j.data]),k=o.useMemo(()=>[...Dd,...Ld,...w],[w]),S=v??k,_=x&&j.isPending,y=x&&j.isError,C=_||y,P=o.useMemo(()=>S.filter(z=>mu.has(z.token)),[S]),A=o.useMemo(()=>S.filter(z=>uu.has(z.token)),[S]),E=o.useMemo(()=>S.filter(z=>!mu.has(z.token)&&!uu.has(z.token)),[S]),Q=S.map(z=>z.token).filter(z=>!b.has(z)),U=z=>!b.has(z),D=z=>N(ae=>{const ue=new Set(ae);return ue.has(z)?ue.delete(z):ue.add(z),ue}),K=(z,ae)=>N(ue=>{const _e=new Set(ue);for(const ee of z)ae?_e.delete(ee):_e.add(ee);return _e}),xe=async()=>{if(!(!i||Q.length===0)){p(!0);try{const z=Q.length===S.length?void 0:Q.join(","),{blob:ae,filename:ue}=await Wt.downloadEventRegistrationsCsv(t,i,z,x),_e=URL.createObjectURL(ae),ee=document.createElement("a");ee.href=_e;const se=s.replace(/[^a-zA-Z0-9-_]+/g,"-").toLowerCase().replace(/^-+|-+$/g,"");ee.download=ue??`registrations_${se}.csv`,ee.click(),URL.revokeObjectURL(_e),r(!1)}catch{Ut.error("Failed to export registrations")}finally{p(!1)}}};return e.jsx(Fe,{open:n,onOpenChange:r,children:e.jsxs(Te,{className:"max-w-lg",children:[e.jsxs(Ae,{children:[e.jsx(Ee,{children:"Export registrations"}),e.jsx(tt,{children:"Choose the columns to include, then download."})]}),e.jsxs("div",{className:"max-h-[50vh] space-y-4 overflow-y-auto pr-1",children:[a&&e.jsxs("div",{className:"space-y-2 rounded-md border p-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ot,{id:"export-include-children",checked:x,onCheckedChange:z=>f(z===!0)}),e.jsx(T,{htmlFor:"export-include-children",className:"cursor-pointer text-sm font-normal",children:"Include child add-on events"})]}),_&&e.jsxs("p",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(He,{className:"h-3 w-3 animate-spin"}),"Loading the combined column listâ¦"]}),y&&e.jsxs("div",{className:"flex items-center justify-between gap-2 text-xs text-red-600 dark:text-red-400",children:[e.jsx("span",{children:"Couldnât load the combined column list."}),e.jsx(g,{variant:"ghost",size:"sm",className:"h-7 px-2",onClick:()=>{j.refetch()},children:"Try again"})]})]}),e.jsx("fieldset",{disabled:C,className:me(C&&"opacity-50"),children:e.jsxs("div",{className:"space-y-4",children:[e.jsx(zo,{groupId:"export-attendee",title:"Attendee",columns:P,isChecked:U,onToggle:D,onSetAll:K}),e.jsx(zo,{groupId:"export-contact",title:"Contact details",columns:A,isChecked:U,onToggle:D,onSetAll:K}),e.jsx(zo,{groupId:"export-answers",title:"Form answers",columns:E,isChecked:U,onToggle:D,onSetAll:K})]})})]}),e.jsxs(Ge,{className:"items-center gap-3 sm:justify-between",children:[e.jsxs("span",{className:"text-xs text-muted-foreground",children:[Q.length," of ",S.length," columns selected"]}),e.jsxs(g,{onClick:()=>{xe()},disabled:h||m||c||C||Q.length===0,children:[h?e.jsx(He,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(vs,{className:"mr-2 h-4 w-4"}),"Download CSV"]})]})]})})}function Uf({eventId:t,eventName:s,hasChildren:a=!1,initialExport:n=!1,open:r,onOpenChange:i}){const{data:l,isLoading:m}=lk(r?t:void 0),c=$g(),[d,u]=o.useState(!1),[h,p]=o.useState(!1);return o.useEffect(()=>{p(r?!!n:!1)},[r,n]),e.jsx(Fe,{open:r,onOpenChange:i,children:e.jsxs(Te,{className:"max-h-[80vh] max-w-2xl overflow-y-auto",onPointerDownOutside:x=>{du(x)&&x.preventDefault()},onInteractOutside:x=>{du(x)&&x.preventDefault()},children:[e.jsx(Ae,{className:"min-w-0",children:e.jsxs("div",{className:"flex min-w-0 flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0 flex-1 pr-8",children:[e.jsxs(Ee,{className:"truncate",title:s,children:["Registration quickview · ",s]}),a&&e.jsx(tt,{className:"mt-1 text-xs",children:"This event only â each child event has its own list on its dashboard"})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[e.jsxs(g,{variant:"outline",size:"sm",onClick:()=>p(!0),disabled:m||(l?.length??0)===0&&!a,children:[e.jsx(vs,{className:"mr-1 h-4 w-4"}),"Export CSV"]}),e.jsxs(g,{size:"sm","data-tour":"add-registrations-btn",onClick:()=>u(!0),children:[e.jsx(Rt,{className:"mr-1 h-4 w-4"}),"Add registrations"]})]})]})}),e.jsx(b4,{eventId:t,eventName:s,open:d,onOpenChange:u}),e.jsx(A4,{eventId:t,eventName:s,hasChildren:a,open:h,onOpenChange:p}),m?e.jsx("div",{className:"space-y-2",children:[1,2,3].map(x=>e.jsx(Y,{className:"h-12 w-full"},x))}):l?.length?e.jsx("div",{className:"min-w-0 divide-y",children:l.map(x=>{const f=_4(x.created_at),b=S4(x.registration_data),N=Object.entries(x.registration_data??{}).filter(([j])=>!j.startsWith(Ml));return e.jsxs("div",{className:"min-w-0 py-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate text-sm font-medium",title:x.member_name||x.guest_name||"Unknown",children:x.member_name||x.guest_name||"Unknown"}),e.jsx("div",{className:"truncate text-xs text-muted-foreground",title:x.member_email||x.guest_email||void 0,children:x.member_email||x.guest_email}),b&&e.jsx("div",{className:"truncate text-xs text-muted-foreground",children:b}),f&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Registered ",f]}
4)]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-3",children:[e.jsxs("div",{className:me("text-sm",x.status!=="confirmed"&&"text-muted-foreground line-through"),children:["$",x.price_paid.toFixed(2)]}),e.jsx("div",{className:"flex items-center gap-2",children:x.status!=="confirmed"?e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full bg-muted px-2.5 py-0.5 text-[11px] font-medium text-muted-foreground",children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-muted-foreground/60","aria-hidden":"true"}),e.jsx("span",{className:"capitalize",children:x.status})]}):x.event_app_pushed?e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full bg-emerald-100 px-2.5 py-0.5 text-[11px] font-medium text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400",children:[e.jsx(Xt,{className:"h-3 w-3"}),"Pushed"]}):x.event_app_push_error?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full bg-red-100 px-2.5 py-0.5 text-[11px] font-medium text-red-700 dark:bg-red-900/30 dark:text-red-400",children:[e.jsx(Bt,{className:"h-3 w-3"}),"Failed"]}),e.jsx(g,{variant:"ghost",size:"sm",onClick:()=>c.mutate({eventId:t,registrationId:x.id}),disabled:c.isPending,title:"Retry push","aria-label":"Retry push",children:e.jsx(St,{className:"h-3 w-3"})})]}):e.jsx("span",{className:"inline-flex items-center gap-1.5 rounded-full bg-muted px-2.5 py-0.5 text-[11px] font-medium text-muted-foreground",children:"Pending"})})]})]}),N.length>0&&e.jsx("div",{className:"mt-1.5 grid grid-cols-2 gap-x-6 gap-y-1 rounded bg-muted/40 px-2 py-1.5 sm:grid-cols-3",children:N.map(([j,w])=>e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:uo(j)}),e.jsx("div",{className:"break-words text-xs text-foreground",children:Of(w)})]},j))})]},x.id)})}):e.jsx("p",{className:"py-4 text-center text-muted-foreground",children:"No registrations yet."})]})})}function E4({section:t,fieldCount:s,onRename:a,onDelete:n,readOnly:r=!1}){const{attributes:i,listeners:l,setNodeRef:m,transform:c,transition:d,isDragging:u}=id({id:t.id}),h={transform:ld.Transform.toString(c),transition:d,opacity:u?.5:void 0,zIndex:u?10:void 0};return e.jsxs("li",{ref:m,style:h,className:"flex items-center gap-2 rounded border bg-card px-2 py-1",children:[e.jsx("button",{type:"button",className:`touch-none p-0.5 text-muted-foreground ${r?"cursor-not-allowed opacity-40":"cursor-grab hover:text-foreground active:cursor-grabbing"}`,"aria-label":"Reorder page",disabled:r,...r?{}:{...i,...l},children:e.jsx(Tr,{className:"h-3.5 w-3.5"})}),e.jsx(O,{value:t.name,onChange:p=>a(t.id,p.target.value),className:"h-7 flex-1 text-sm",disabled:r,readOnly:r}),e.jsxs(Ts,{variant:"secondary",className:"text-xs",children:[s," field",s===1?"":"s"]}),s===0&&e.jsxs("span",{className:"inline-flex items-center gap-1.5 whitespace-nowrap",title:"Empty pages don't appear in the member-facing form",children:[e.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-amber-500"}),e.jsx("span",{className:"text-xs font-medium",children:"Empty â won't show"})]}),!r&&e.jsx("button",{type:"button",onClick:()=>n(t.id),className:"text-muted-foreground hover:text-destructive","aria-label":"Delete page",children:e.jsx(Ft,{className:"h-3.5 w-3.5"})})]})}function zf(t,s,a,n){t(r=>r.map(i=>i.field_id===s?{...i,section_id:a}:i)),n?.()}function Bf({formSections:t,setFormSections:s,formConfig:a,setFormConfig:n,onMutate:r,className:i,readOnly:l=!1}){const[m,c]=o.useState(null),d=od(kr(ud,{activationConstraint:{distance:5}}),kr(md,{coordinateGetter:dd})),u=()=>{const f=typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`sec-${Date.now()}-${Math.random().toString(36).slice(2,10)}`;s(b=>[...b,{id:f,name:`Page ${b.length+1}`,description:null,order:b.length}]),r?.()},h=(f,b)=>{s(N=>N.map(j=>j.id===f?{...j,name:b}:j)),r?.()},p=f=>{n(b=>b.map(N=>N.section_id===f?{...N,section_id:null}:N)),s(b=>b.filter(N=>N.id!==f).map((N,j)=>({...N,order:j}))),r?.()},x=f=>{const{active:b,over:N}=f;!N||b.id===N.id||(s(j=>{const w=j.findIndex(k=>k.id===b.id),v=j.findIndex(k=>k.id===N.id);return w===-1||v===-1?j:cd(j,w,v).map((k,S)=>({...k,order:S}))}),r?.())};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:`space-y-1.5 rounded-md border bg-muted/30 p-2${i?` ${i}`:""}`,children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-xs font-semibold",children:"Pages (optional)"}),!l&&e.jsxs(g,{type:"button",size:"sm",variant:"outline",onClick:u,children:[e.jsx(Rt,{className:"mr-1 h-3 w-3"})," Add Page"]})]}),t.length===0?e.jsx("p",{className:"text-xs text-muted-foreground",children:l?"No pages defined â the form renders as a
4single page.":"No pages defined â the form renders as a single page. Add a page to split fields across multiple wizard steps."}):e.jsx(jl,{sensors:d,collisionDetection:vl,onDragEnd:l?void 0:x,children:e.jsx(wl,{items:t.map(f=>f.id),strategy:Nl,children:e.jsx("ul",{className:"space-y-1",children:t.map(f=>e.jsx(E4,{section:f,fieldCount:a.filter(b=>b.section_id===f.id).length,onRename:l?()=>{}:h,onDelete:l?()=>{}:c,readOnly:l},f.id))})})})]}),e.jsx(Fe,{open:m!==null,onOpenChange:f=>!f&&c(null),children:e.jsxs(Te,{children:[e.jsx(Ae,{children:e.jsx(Ee,{children:"Delete this page?"})}),e.jsx("p",{className:"text-sm text-muted-foreground",children:`Fields assigned to this page will become unsectioned (they'll show on the last "Other" page in the member's form). The fields themselves are not deleted.`}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(g,{variant:"outline",onClick:()=>c(null),children:"Cancel"}),e.jsx(g,{variant:"destructive",onClick:()=>{m&&p(m),c(null)},children:"Delete page"})]})]})})]})}function xn(t){const{data:s}=Qs(),a=`${t}_enabled`;return{enabled:s?.settings?.[a]===!0,loaded:!!s}}const Kf=new Set(["member_default","early_bird"]),Qf=new Set(["non_member"]),T4=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function F4(t){return!Kf.has(t)&&!Qf.has(t)}function hu(t){const s={},a={};if(!t)return{members:s,nonMembers:a};for(const[n,r]of Object.entries(t))!F4(n)||!r||("price"in r&&r.price!==void 0&&(s[n]=r.price),"non_member_price"in r&&r.non_member_price!==void 0&&(a[n]=r.non_member_price));return{members:s,nonMembers:a}}function R4(t,s,a,n,r){const i={};if(a.trim()!==""){const m=parseFloat(a);!isNaN(m)&&m>=0&&(i.member_default={price:Math.round(m*100)/100})}const l=new Set([...Object.keys(t),...Object.keys(s)]);for(const m of l){if(!m||Qf.has(m)||Kf.has(m)||!T4.test(m))continue;const c={},d=t[m],u=s[m];if(d&&d.trim()!==""){const h=parseFloat(d);!isNaN(h)&&h>=0&&(c.price=Math.round(h*100)/100)}if(u&&u.trim()!==""){const h=parseFloat(u);!isNaN(h)&&h>=0&&(c.non_member_price=Math.round(h*100)/100)}(c.price!==void 0||c.non_member_price!==void 0)&&(i[m]=c)}if(n&&n.amount>=0){const m={mode:n.mode,amount:Math.round(n.amount*100)/100},c={};for(const[d,u]of Object.entries(r)){if(!d||u.trim()==="")continue;const h=parseFloat(u);!isNaN(h)&&h>=0&&(c[d]=Math.round(h*100)/100)}Object.keys(c).length>0&&(m.overrides=c),(m.amount>0||m.overrides&&Object.keys(m.overrides).length>0)&&(i.early_bird=m)}return Object.keys(i).length===0?null:i}function M4({event:t,childCount:s,open:a,onOpenChange:n,onConfirm:r}){const[i,l]=o.useState(""),[m,c]=o.useState(!1),[d,u]=o.useState(null),h=s>0,p=!h||i===t.slug;o.useEffect(()=>{a||(l(""),u(null),c(!1))},[a]);const x=async()=>{c(!0),u(null);try{await r(h?i:void 0),n(!1)}catch(f){const b=f instanceof Error?f.message:"Failed to delete event";u(b)}finally{c(!1)}};return e.jsx(Fe,{open:a,onOpenChange:n,children:e.jsxs(Te,{className:"sm:max-w-md",children:[e.jsxs(Ae,{children:[e.jsxs(Ee,{className:"flex items-center gap-2",children:[e.jsx(Bt,{className:"h-5 w-5 text-destructive"}),"Delete ",h?"Parent Event":"Event"]}),e.jsx(tt,{children:h?e.jsxs(e.Fragment,{children:["This will delete ",e.jsx("strong",{children:t.name})," and"," ",e.jsxs("strong",{children:[s," child event",s===1?"":"s"]}),". Type the event slug to confirm."]}):e.jsxs(e.Fragment,{children:["This will delete ",e.jsx("strong",{children:t.name}),"."]})})]}),h&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(T,{htmlFor:"confirm-slug",children:["Type ",e.jsx("span",{className:"font-mono",children:t.slug})," to confirm"]}),e.jsx(O,{id:"confirm-slug",value:i,onChange:f=>l(f.target.value),placeholder:t.slug,autoComplete:"off",className:"font-mono"})]}),d&&e.jsx("div",{className:"rounded-md border border-destructive/50 bg-destructive/10 px-3 py-2 text-sm text-destructive",children:d}),e.jsxs(Ge,{className:"pt-2",children:[e.jsx(g,{type:"button",variant:"outline",onClick:()=>n(!1),disabled:m,children:"Cancel"}),e.jsx(g,{type:"button",variant:"destructive",onClick:()=>{x()},disabled:!p||m,children:m?"Deletingâ¦":h?`Delete parent + ${s} children`:"Delete event"})]})]})})}function Xs({onClick:t,active:s,disabled:a,label:n,children:r}){return e.jsx("button",{type:"button",onClick:t,disabled:a,title:n,"aria-label":n,className:`rounded p-1.5 transition-colors hover:bg-accent disabled:opacity-40 ${s?"bg-accent text-accent-foreground":"text-muted-foreground"}`,children:r})}function Xr(){return e.jsx("div",{className:"mx-0.5 h-5 w-px bg-border"})}function D4({editor:t}){const s=()=>
4{if(t.isActive("link")){t.chain().focus().unsetLink().run();return}const n=window.prompt("Enter URL (must start with https:// or mailto:):");if(n){if(!/^(https?:|mailto:)/i.test(n)){window.alert("Only https://, http://, and mailto: links are allowed.");return}t.chain().focus().setLink({href:n}).run()}};return e.jsxs("div",{className:"flex flex-wrap items-center gap-0.5 border-b bg-muted/30 px-2 py-1.5",children:[e.jsx(Xs,{onClick:()=>t.chain().focus().toggleBold().run(),active:t.isActive("bold"),label:"Bold",children:e.jsx(Pp,{size:16})}),e.jsx(Xs,{onClick:()=>t.chain().focus().toggleItalic().run(),active:t.isActive("italic"),label:"Italic",children:e.jsx(Ap,{size:16})}),e.jsx(Xs,{onClick:()=>t.chain().focus().toggleUnderline().run(),active:t.isActive("underline"),label:"Underline",children:e.jsx(Ep,{size:16})}),e.jsx(Xr,{}),e.jsx(Xs,{onClick:()=>t.chain().focus().toggleHeading({level:1}).run(),active:t.isActive("heading",{level:1}),label:"Heading 1",children:e.jsx(Tp,{size:16})}),e.jsx(Xs,{onClick:()=>t.chain().focus().toggleHeading({level:2}).run(),active:t.isActive("heading",{level:2}),label:"Heading 2",children:e.jsx(Fp,{size:16})}),e.jsx(Xs,{onClick:()=>t.chain().focus().toggleHeading({level:3}).run(),active:t.isActive("heading",{level:3}),label:"Heading 3",children:e.jsx(Rp,{size:16})}),e.jsx(Xr,{}),e.jsx(Xs,{onClick:s,active:t.isActive("link"),label:"Link",children:e.jsx(Mp,{size:16})}),e.jsx(Xr,{}),e.jsx(Xs,{onClick:()=>t.chain().focus().toggleBulletList().run(),active:t.isActive("bulletList"),label:"Bullet List",children:e.jsx(td,{size:16})}),e.jsx(Xs,{onClick:()=>t.chain().focus().toggleOrderedList().run(),active:t.isActive("orderedList"),label:"Ordered List",children:e.jsx(Dp,{size:16})}),e.jsx(Xr,{}),e.jsx(Xs,{onClick:()=>t.chain().focus().setTextAlign("left").run(),active:t.isActive({textAlign:"left"}),label:"Align Left",children:e.jsx(Lp,{size:16})}),e.jsx(Xs,{onClick:()=>t.chain().focus().setTextAlign("center").run(),active:t.isActive({textAlign:"center"}),label:"Align Center",children:e.jsx($p,{size:16})}),e.jsx(Xs,{onClick:()=>t.chain().focus().setTextAlign("right").run(),active:t.isActive({textAlign:"right"}),label:"Align Right",children:e.jsx(qp,{size:16})}),e.jsx(Xr,{}),e.jsx(Xs,{onClick:()=>t.chain().focus().undo().run(),disabled:!t.can().undo(),label:"Undo",children:e.jsx(Ip,{size:16})}),e.jsx(Xs,{onClick:()=>t.chain().focus().redo().run(),disabled:!t.can().redo(),label:"Redo",children:e.jsx(Op,{size:16})})]})}function L4({value:t,onChange:s,placeholder:a}){const n=o.useRef(!1),r=o.useRef(t),i=Xp({extensions:[tx.configure({heading:{levels:[1,2,3]}}),sx.configure({openOnClick:!1,HTMLAttributes:{target:"_blank",rel:"noopener noreferrer"},protocols:["http","https","mailto"]}),ex,ax.configure({types:["heading","paragraph"],alignments:["left","center","right"]}),nx.configure({placeholder:a??"Describe the event for attendeesâ¦"})],content:t,onUpdate:({editor:l})=>{if(n.current)return;const m=l.getHTML(),c=m==="<p></p>"?"":m;r.current=c,s(c)}});return o.useEffect(()=>{i&&t!==r.current&&(r.current=t,n.current=!0,i.commands.setContent(t||""),n.current=!1)},[t,i]),e.jsxs("div",{className:"tiptap-editor overflow-hidden rounded-md border",children:[i&&e.jsx(D4,{editor:i}),e.jsx(rx,{editor:i})]})}const $4={draft:"bg-muted-foreground/60",published:"bg-emerald-500",closed:"bg-amber-500",cancelled:"bg-red-500"},q4={draft:"Draft",published:"Published",closed:"Closed",cancelled:"Cancelled"};function pu({status:t}){return e.jsxs("span",{className:"inline-flex items-center gap-1.5 whitespace-nowrap",children:[e.jsx("span",{className:`h-1.5 w-1.5 shrink-0 rounded-full ${$4[t]||"bg-muted-foreground/60"}`}),e.jsx("span",{className:"text-xs font-medium",children:q4[t]||t})]})}function xu(t){return t.toLocaleString("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0})}function Vi(t){return t.target.closest('a, button, [role="button"], input, [data-no-row-nav]')!==null}
4const Gi="America/New_York",gu="SKIPPED: ";function I4({eventId:t,currentUrl:s,onChange:a}){const n=ck(),r=dk(),[i,l]=o.useState(null),m=async d=>{const u=d.target.files?.[0];if(d.target.value="",!!u){l(null);try{const h=await n.mutateAsync({eventId:t,file:u});a(h.hero_image_url)}catch(h){const p=h&&typeof h=="object"&&"response"in h?h.response?.data?.detail??"Upload failed":"Upload failed";l(typeof p=="string"?p:"Upload failed")}}},c=async()=>{l(null);try{await r.mutateAsync(t),a(null)}catch(d){const u=d&&typeof d=="object"&&"response"in d?d.response?.data?.detail??"Delete failed":"Delete failed";l(typeof u=="string"?u:"Delete failed")}};return e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{children:"Hero image"}),s?e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("img",{src:`${ds}${s}`,alt:"Event hero",className:"h-24 w-40 rounded border object-cover"}),e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsxs("label",{className:"cursor-pointer",children:[e.jsx("input",{type:"file",accept:"image/png,image/jpeg,image/webp",className:"hidden",onChange:m}),e.jsx("span",{className:"inline-flex items-center rounded border px-2 py-1 text-xs hover:bg-accent",children:"Replaceâ¦"})]}),e.jsx(g,{type:"button",variant:"ghost",size:"sm",onClick:c,disabled:r.isPending,className:"h-auto py-1 text-xs",children:"Remove"})]})]}):e.jsxs("label",{className:"inline-block cursor-pointer",children:[e.jsx("input",{type:"file",accept:"image/png,image/jpeg,image/webp",className:"hidden",onChange:m}),e.jsx("span",{className:"inline-flex items-center rounded-md border border-dashed px-3 py-2 text-sm hover:bg-accent",children:n.isPending?"Uploadingâ¦":"Upload hero image"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"PNG, JPEG, or WebP. Up to 4 MB. Korevera-only â not pushed to event-app."}),i&&e.jsx("p",{className:"text-xs text-red-600",children:i})]})}const fu={legacy:"Standard",options:"Options (beta)"};function O4(t){return t==="legacy"||t==="options"}function U4(t){if(!wi(t))return"No clear answer came back, so the event may or may not have been switched. Close this and check the event's pricing engine before trying again.";const s=Ni(t);return on(t)===409&&s?s:"The pricing engine couldn't be switched. Nothing was changed."}function yu(t){const s=t.pricing_timezone;return s===t.timezone?`the eventâs time zone (${s})`:`${s} (the eventâs time zone, â${t.timezone}â, isnât a valid time zone, so the default is used)`}function z4({event:t}){const s=rk(),a=o.useId(),[n,r]=o.useState("options"),[i,l]=o.useState(!1),[m,c]=o.useState(null),[d,u]=o.useState(null),h=t.pricing_source;if(typeof h!="string"||h==="")return null;const p=O4(h)?h:null,x=t.early_bird_deadline?Ps(t.early_bird_deadline).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):null,f=()=>{p!==null&&(u(null),c(null),r(p==="options"?"legacy":"options"),l(!0))},b=()=>{s.isPending||l(!1)},N=async()=>{c(null);try{await s.mutateAsync({eventId:t.id,pricingSource:n}),u(`This event is now priced by ${fu[n]}.`),l(!1)}catch(j){c(U4(j))}};return e.jsxs("div",{className:"mb-3",role:"group","aria-labelledby":a,children:[e.jsx(T,{id:a,className:"text-xs",children:"Pricing engine"}),p!==null?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1",children:[e.jsx("span",{className:"text-sm",children:fu[p]}),e.jsx(g,{type:"button",variant:"outline",size:"sm",onClick:f,disabled:s.isPending,children:p==="options"?"Switch to Standardâ¦":"Switch to Options (beta)â¦"})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Platform admins only. A switch takes effect at once, separately from Save changes."})]}):e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-sm",children:[e.jsx("span",{className:"font-mono text-xs",children:h}),e.jsx("span",{className:"text-muted-foreground",children:" · Managed by a newer release"})]}),m&&e.jsx("p",{role:"alert",className:"mt-1 text-xs text-destructive",children:m})]}),e.jsx("div",{role:"status",children:d&&e.jsx("p",{className:"mt-1 text-xs text-emerald-600 dark:text-emerald-400",children:d})}),e.jsx(Fe,{open:i&&p!==null,onOpenChange:j=>!j&&b(),children:e.jsxs(Te,{className:"max-w-md",children:[e.jsx(Ae,{children:e.jsx(Ee,{children:n==="options"?"Switch this event to Options (beta)?":"Switch this event back to Standard?"})}),n==="options"?e.jsxs(e.Fragment,{children:[e.jsx(tt,{children:"Prices stay the same. Korevera copies this eventâs saved prices into its option and checks that every one matches before switching. If any differs, nothing is switched."}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["One thing changes: the early-bird date. Standard checks the deadline against the serverâs date. Options (beta) checks it against todayâs date in"," ",yu(t),", so around midnight a buyer may get a different price than Standard would charge."]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:x?`This event's early-bird deadline is ${x}: early-bird prices end at midnight at the end of that day, ${t.pricing_timezone} time.`:"This event has no early-bird deadline, so this doesnât affect it."}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"You can switch back to Standard at any time."})]}):e.jsxs(tt,{children:["Prices stay the same: Standard prices from the eventâs own pricing fields, the ones its option was copied from. The early-bird deadline goes back to being checked against the serverâs date instead of todayâs date in"," ",yu(t),"."]}
4),m&&e.jsx("p",{role:"alert",className:"text-sm text-destructive",children:m}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(g,{type:"button",variant:"outline",onClick:b,disabled:s.isPending,children:"Cancel"}),e.jsx(g,{type:"button",onClick:N,disabled:s.isPending,children:s.isPending?e.jsxs(e.Fragment,{children:[e.jsx(He,{className:"mr-1 h-3 w-3 animate-spin"}),"Switchingâ¦"]}):n==="options"?"Switch to Options (beta)":"Switch to Standard"})]})]})})]})}function bu(t){return t.venue?t.address?`${t.venue}, ${t.address}`:t.venue:t.location??null}function B4({event:t,open:s,onOpenChange:a,parentEvent:n,allEvents:r}){const i=sk(),l=ak(),m=nk(),c=J(),{user:d}=V(),u=d?.role==="super_admin",{data:h}=Qs(),{data:p,isFetching:x}=jf(),{data:f}=go(),{data:b}=er(),{data:N}=oa(),{data:j=[]}=oa(!0,!0),{data:w=[]}=Ai(),[v,k]=o.useState(null),[S,_]=o.useState(!1),y=Pi(t?.id),C=y.data??t,P=h?.settings?.template_event_1to1_enabled===!0,A=P&&C?.registration_form_template_id?C.registration_form_template_id:null,E=A!==null,Q=E?p?.find(B=>B.id===A):null,U=y2(),D=b2(),[K,xe]=o.useState(!1),[z,ae]=o.useState(null),[ue,_e]=o.useState(null),ee=ok(),[se,le]=o.useState(null),[oe,Pe]=o.useState(null),[M,I]=o.use
4State(t?.registration_form_config||[]),[R,X]=o.useState(t?.form_sections||[]),Se=E?Q?.form_config??C?.registration_form_config??[]:M,ce=E?Q?.form_sections??C?.form_sections??[]:R,[ke,ve]=o.useState(!1),Ne=E?Q?.form_config??C?.registration_form_config??[]:M,Qe=E?Q?.form_sections??C?.form_sections??[]:R,Oe=Tl(Ne,f,b),[Ce,ze]=o.useState(()=>{const B=t?.registration_form_config;if(B?.length&&p?.length){const we=Nt=>Nt.map(Mt=>({field_id:Mt.field_id,order:Mt.order,required:Mt.required,section_id:Mt.section_id??null,conditional_logic:Mt.conditional_logic??null})),Je=Nt=>(Nt||[]).map(Mt=>({id:Mt.id,name:Mt.name,description:Mt.description,order:Mt.order})),it=JSON.stringify({config:we(B),sections:Je(t?.form_sections)});return p.find(Nt=>JSON.stringify({config:we(Nt.form_config),sections:Je(Nt.form_sections)})===it)?.id||"custom"}return B?.length?"custom":"none"}),[Ze,Re]=o.useState(()=>{const B=t?.type_prices?hu(t.type_prices).members:{},we={};for(const[Je,it]of Object.entries(B))we[Je]=String(it);return we}),[de,ge]=o.useState(()=>{const B=t?.type_prices?hu(t.type_prices).nonMembers:{},we={};for(const[Je,it]of Object.entries(B))we[Je]=String(it);return we}),[mt,ye]=o.useState(()=>{const B=t?.type_prices?.member_default;return B&&"price"in B?String(B.price):""}),[Ke,ut]=o.useState(()=>!!t?.type_prices?.early_bird),[De,he]=o.useState(()=>{const B=t?.type_prices?.early_bird;return B&&"mode"in B?B.mode:"flat"}),[Xe,rt]=o.useState(()=>{const B=t?.type_prices?.early_bird;return B&&"amount"in B?String(B.amount):""}),[yt,dt]=o.useState(()=>{const B=t?.type_prices?.early_bird;if(!B||!("overrides"in B)||!B.overrides)return{};const we={};for(const[Je,it]of Object.entries(B.overrides))we[Je]=String(it);return we}),[jt,Ot]=o.useState(t?.offer_free_membership_enabled??!1),[be,lt]=o.useState(t?.offer_free_membership_months??12),[ht,zt]=o.useState(t?.offer_role_eligibility??[]),[Tt,Jt]=o.useState(t?.registration_eligibility??[]),[is,Va]=o.useState((t?.registration_eligibility??[]).length>0),[nt,Vt]=o.useState({name:t?.name||"",slug:t?.slug||"",description:t?.description||"",description_html:t?.description_html||"",hero_image_url:t?.hero_image_url||null,event_app_event_slug:t?.event_app_event_slug||"",website_url:t?.website_url||"",external_registration_url:t?.external_registration_url||"",qbo_category:t?.qbo_category??null,attendee_tag:t?.attendee_tag??null,start_date:t?.start_date||"",end_date:t?.end_date||"",venue:t?.venue||t?.location||"",address:t?.address||"",timezone:t?.timezone||Gi,early_bird_deadline:t?.early_bird_deadline||"",regular_price:t?.regular_price??0,capacity:t?.capacity??null,status:t?.status||"draft",parent_event_id:t?.parent_event_id??n?.id??null}),[et,bt]=o.useState([]),[qt,xs]=o.useState(null),ns=n??(nt.parent_event_id?r?.find(B=>B.id===nt.parent_event_id):void 0),ua=ns?.start_date||"",aa=ns?.end_date||"",_s=!!n,Ls=(r??[]).filter(B=>!B.parent_event_id&&(!t||B.id!==t.id)),pe=t?.event_app_event_slug||nt.event_app_event_slug,Z=B=>
4{if(!(U.isPending||D.isPending)&&!(E&&(B==="none"||B==="custom"))){if(P&&B!=="none"&&B!=="custom"&&t?.id){ae(null),U.mutate({eventId:t.id,templateId:B},{onError:we=>{const Je=we&&typeof we=="object"&&"response"in we?we.response?.data?.detail??"":"",it=p?.find(ct=>ct.id===B)?.name??"This template";Je.includes("claim_collision")||Je.includes("409")?ae(`Sorry â "${it}" was just linked to another event. Refresh and try again, or pick a different template.`):Je.includes("template_deleted")?(ae("This template was just deleted. Refresh the page to see the updated list."),c.invalidateQueries({queryKey:["admin","event-form-templates"]})):Je.includes("template_event_1to1_disabled")?ae("Template linking is not enabled for this society."):ae("This template is no longer available. Refresh and try again.")}});return}if(ze(B),B==="none")I([]),X([]);else if(B!=="custom"){const we=p?.find(Je=>Je.id===B);we&&(I(we.form_config),X(we.form_sections||[]))}}},We=()=>ze("custom"),Ve=B=>B.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,""),xt=()=>({_id:typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`draft-${Date.now()}-${Math.random().toString(36).slice(2,10)}`,name:"",slug:"",description:"",start_date:"",end_date:"",venue:"",address:"",timezone:nt.timezone||Gi,regular_price:0,capacity:null,status:"draft",event_app_event_slug:""}),Ht=()=>{bt(B=>[...B,xt()])},Zt=B=>{bt(we=>we.filter(Je=>Je._id!==B))},Cs=(B,we)=>{bt(Je=>Je.map(it=>it._id===B?{...it,...we}:it))},Ga=async B=>{B.preventDefault(),xs(null);let we=null;if(Ke){const ct=parseFloat(Xe);!isNaN(ct)&&ct>=0&&(we={mode:De,amount:ct})}const Je=R4(Ze,de,mt,we,yt),it={...nt,start_date:nt.start_date||null,end_date:nt.end_date||null,early_bird_deadline:Ke&&nt.early_bird_deadline?nt.early_bird_deadline:null,event_app_event_slug:nt.event_app_event_slug||null,website_url:nt.website_url||null,external_registration_url:nt.external_registration_url||null,type_prices:Je,...E?{}:{registration_form_config:M.length>0?M:null,form_sections:R},parent_event_id:nt.parent_event_id??null,offer_free_membership_enabled:jt&&ht.length>0,offer_free_membership_months:be,offer_role_eligibility:ht,registration_eligibility:is&&Tt.length?Tt:null};try{if(t)await m.mutateAsync({eventId:t.id,data:it});else if(!t&&et.length>0){const ct=et.map(Mt=>({name:Mt.name,slug:Mt.slug||Ve(Mt.name),description:Mt.description||null,start_date:Mt.start_date||null,end_date:Mt.end_date||null,venue:Mt.venue,address:Mt.address||null,timezone:Mt.timezone||Gi,regular_price:Mt.regular_price,capacity:Mt.capacity,status:Mt.status,event_app_event_slug:Mt.event_app_event_slug||null})),Nt={...it,children:ct};await l.mutateAsync(Nt)}else await i.mutateAsync(it);bt([]),a(!1)}catch(ct){const Nt=ct&&typeof ct=="object"&&"response"in ct?ct.response?.data?.detail??"":"";if(typeof Nt=="string"&&Nt.includes("event_linked_to_template")){xs("This event is still synced with a template. Refresh and try again, or contact your platform admin.");return}const Mt=typeof Nt=="string"&&Nt?Nt:ct instanceof Error?ct.message:"Failed to save event";xs(typeof Mt=="string"?Mt:"Failed to save event")}},Is=B=>{if(!Ke)return"";const we=parseFloat(Xe);return isNaN(we)||we<0?"":De==="flat"?Math.max(0,B-we).toFixed(2):Math.max(0,B*(1-we/100)).toFixed(2)},na=B=>{if(B==="non_member")return nt.regular_price||0;if(B==="member_default"){const it=parseFloat(mt);return!isNaN(it)&&mt.trim()!==""?it:nt.regular_price||0}const we=Ze[B];if(we&&we.trim()!==""){const it=parseFloat(we);if(!isNaN(it))return it}const Je=parseFloat(mt);return!isNaN(Je)&&mt.trim()!==""?Je:nt.regular_price||0},Qr=()=>{if(mt.trim()!==""){const B=parseFloat(mt);if(!isNaN(B))return`$${B.toFixed(2)}`}return`$${(nt.regular_price||0).toFixed(2)}`};return e.jsxs(e.Fragment,{children:[e.jsx(Fe,{open:s,onOpenChange:a,children:e.jsxs(Te,{className:"max-h-[90vh] max-w-2xl overflow-y-auto",children:[e.jsx(Ae,{children:e.jsx(Ee,{children:t?"Edit event":"Create event"})}),e.jsxs("form",{onSubmit:Ga,className:"space-y-3",children:[_s&&n&&e.jsxs("div",{className:"rounded-md border border-primary/40 bg-primary/5 px-3 py-2 text-sm",children:["Child event under ",e.jsx("strong",{children:n.name})]}),t&&!_s&&u&&e.jsxs("div",{children:[e.jsx(T,{children:"Parent event"}),e.jsx(Ss,{value:nt.parent_event_id??null,onChange:B=>Vt(we=>({...we,parent_event_id:B})),noneLabel:"â None â",placeholder:"â None â",children:Ls.map(B=>e.jsx(q,{value:B.id,children:B.name},B.id))})]}),t?.parent_event_id&&!u&&ns&&e.jsxs("div",{children:[e.jsx(T,{children:"Parent event"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:ns.name})]}),e.jsxs("div",{children:[e.jsx(T,{children:"Name"}),e.jsx(O,{value:nt.name,onChange:B=>{const we=B.target.value;Vt(Je=>({...Je,name:we,slug:t?Je.slug:Ve(we)}))},required:!0})]}),e.jsxs("div",{children:[e.jsx(T,{children:"Short description"}),e.jsx(It,{value:nt.description||"",onChange:B=>Vt(we=>({...we,description:B.target.value})),rows:3,placeholder:"One or two sentences. Shown in listings and pushed to event-app."})]}),e.jsxs("div",{children:[e.jsx(T,{children:"Event page description"}),e.jsx(L4,{value:nt.description_html||"",onChange:B=>Vt(we=>({...we,description_html:B||null})),placeholder:"Rich description shown on the Korevera registration page. Leave empty to fall back to the short description."}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"Korevera-only â not pushed to event-app."})]}),t&&e.jsx(I4,{eventId:t.id,currentUrl:nt.hero_image_url,onChange:B=>Vt(we=>({...we,hero_image_url:B}))}),!t&&e.jsx("div",{className:"rounded-md border border-dashed border-muted-foreground
4/30 p-3 text-xs text-muted-foreground",children:"Save the event first, then you can upload a hero image."}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(T,{children:"Start date"}),e.jsx(Hr,{value:nt.start_date||"",min:ua||void 0,max:aa||void 0,onChange:B=>Vt(we=>({...we,start_date:B}))})]}),e.jsxs("div",{children:[e.jsx(T,{children:"End date"}),e.jsx(Hr,{value:nt.end_date||"",min:nt.start_date||ua||void 0,max:aa||void 0,onChange:B=>Vt(we=>({...we,end_date:B}))})]})]}),ns&&(ua||aa)&&e.jsxs("p",{className:"-mt-2 text-xs text-muted-foreground",children:["Must fall within parent event window (",ua||"â¦"," to ",aa||"â¦",")"]}),e.jsxs("div",{children:[e.jsx(T,{children:"Venue"}),e.jsx(O,{value:nt.venue,onChange:B=>Vt(we=>({...we,venue:B.target.value})),placeholder:"e.g. Phoenix Convention Center",required:!0})]}),e.jsxs("div",{children:[e.jsx(T,{children:"Address"}),e.jsx(O,{value:nt.address||"",onChange:B=>Vt(we=>({...we,address:B.target.value})),placeholder:"Street, City, State (optional)"})]}),e.jsxs("div",{children:[e.jsx(T,{children:"Time zone"}),e.jsxs(qe,{value:nt.timezone||Gi,onValueChange:B=>Vt(we=>({...we,timezone:B})),children:[e.jsx(Le,{children:e.jsx(Ie,{})}),e.jsxs($e,{children:[e.jsx(q,{value:"America/New_York",children:"Eastern â America/New_York"}),e.jsx(q,{value:"America/Chicago",children:"Central â America/Chicago"}),e.jsx(q,{value:"America/Denver",children:"Mountain â America/Denver"}),e.jsx(q,{value:"America/Phoenix",children:"Arizona (no DST) â America/Phoenix"}),e.jsx(q,{value:"America/Los_Angeles",children:"Pacific â America/Los_Angeles"}),e.jsx(q,{value:"America/Anchorage",children:"Alaska â America/Anchorage"}),e.jsx(q,{value:"Pacific/Honolulu",children:"Hawaii â Pacific/Honolulu"}),e.jsx(q,{value:"UTC",children:"UTC"})]})]})]}),e.jsxs("div",{className:"mt-3 border-t pt-3",children:[e.jsxs(T,{className:"mb-2 flex items-center gap-1.5 text-sm font-semibold",children:[e.jsx(Ua,{className:"h-4 w-4"}),"Pricing"]}),t&&u&&C&&e.jsx(z4,{event:C}),e.jsxs("div",{className:"mb-3",children:[e.jsx(T,{className:"text-xs",children:"Regular price ($)"}),e.jsx(O,{type:"number",step:"0.01",min:"0",value:nt.regular_price,onChange:B=>Vt(we=>({...we,regular_price:parseFloat(B.target.value)||0})),required:!0})]}),Ke?e.jsxs("div",{className:"mb-3 flex items-center gap-2 rounded bg-muted/40 p-2",children:[e.jsxs(qe,{value:De,onValueChange:B=>he(B),children:[e.jsx(Le,{className:"h-8 w-24 text-xs",children:e.jsx(Ie,{})}),e.jsxs($e,{children:[e.jsx(q,{value:"flat",children:"$ off"}),e.jsx(q,{value:"percent",children:"% off"})]})]}),e.jsx(O,{type:"number",step:"0.01",min:"0",max:De==="percent"?100:void 0,className:"h-8 w-24 text-sm",value:Xe,onChange:B=>rt(B.target.value),placeholder:"Amount"}),e.jsx("span",{className:"whitespace-nowrap text-xs text-muted-foreground",children:"before"}),e.jsx("div",{className:"flex-1",children:e.jsx(Hr,{value:nt.early_bird_deadline||"",max:nt.start_date||aa||void 0,onChange:B=>Vt(we=>({...we,early_bird_deadline:B})),placeholder:"Pick deadline",className:"h-8 text-sm"})}),e.jsx("button",{type:"button",className:"p-1 text-muted-foreground hover:text-destructive",onClick:()=>{ut(!1),rt(""),dt({}),Vt(B=>({...B,early_bird_deadline:""}))},title:"Remove early bird",children:e.jsx(Ft,{className:"h-3.5 w-3.5"})})]}):e.jsx("button",{type:"button",className:"mb-3 text-xs font-medium text-blue-600 hover:text-blue-700",onClick:()=>ut(!0),children:"+ Early bird discount"}),N&&N.length>0?e.jsxs("div",{className:"overflow-hidden rounded border",children:[e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-muted/50 text-muted-foreground",children:[e.jsx("th",{className:"px-2 py-1.5 text-left text-[11px] font-medium uppercase tracking-wider text-muted-foreground/80",children:"Audience"}),e.jsx("th",{className:"w-28 px-2 py-1.5 text-left text-[11px] font-medium uppercase tracking-wider text-muted-foreground/80",children:"Price"}),e.jsx("th",{className:"w-28 px-2 py-1.5 text-left text-[11px] font-medium uppercase tracking-wider text-muted-foreground
4/80",children:"Non-member"}),Ke&&e.jsx("th",{className:"w-28 px-2 py-1.5 text-left text-[11px] font-medium uppercase tracking-wider text-muted-foreground/80",children:"Early bird"})]})}),e.jsxs("tbody",{className:"divide-y",children:[e.jsxs("tr",{children:[e.jsx("td",{className:"px-2 py-1.5 font-medium",children:"Non-Member"}),e.jsx("td",{className:"px-2 py-1.5",children:e.jsxs("span",{className:"text-muted-foreground",children:["$",(nt.regular_price||0).toFixed(2)]})}),e.jsx("td",{className:"px-2 py-1.5",children:e.jsx("span",{className:"text-muted-foreground",children:"â"})}),Ke&&e.jsx("td",{className:"px-2 py-1.5",children:yt.non_member!==void 0&&yt.non_member!==""?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(O,{type:"number",step:"0.01",min:"0",className:"h-7 w-20 text-xs",value:yt.non_member,onChange:B=>dt(we=>({...we,non_member:B.target.value}))}),e.jsx("button",{type:"button",className:"text-muted-foreground hover:text-foreground",onClick:()=>dt(B=>{const we={...B};return delete we.non_member,we}),title:"Reset to auto",children:e.jsx(St,{className:"h-3 w-3"})})]}):e.jsxs("span",{className:"cursor-pointer text-muted-foreground hover:text-foreground",onClick:()=>dt(B=>({...B,non_member:Is(nt.regular_price||0)})),title:"Click to override",children:["$",Is(nt.regular_price||0)]})})]}),e.jsxs("tr",{className:"bg-muted/20",children:[e.jsx("td",{className:"px-2 py-1.5 font-medium",children:"All Members (default)"}),e.jsx("td",{className:"px-2 py-1.5",children:e.jsx(O,{type:"number",step:"0.01",min:"0",className:"h-7 w-full text-xs",value:mt,onChange:B=>ye(B.target.value),placeholder:`$${(nt.regular_price||0).toFixed(2)}`})}),e.jsx("td",{className:"px-2 py-1.5",children:e.jsx("span",{className:"text-muted-foreground",children:"â"})}),Ke&&e.jsx("td",{className:"px-2 py-1.5",children:yt.member_default!==void 0&&yt.member_default!==""?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(O,{type:"number",step:"0.01",min:"0",className:"h-7 w-20 text-xs",value:yt.member_default,onChange:B=>dt(we=>({...we,member_default:B.target.value}))}),e.jsx("button",{type:"button",className:"text-muted-foreground hover:text-foreground",onClick:()=>dt(B=>{const we={...B};return delete we.member_default,we}),title:"Reset to auto",children:e.jsx(St,{className:"h-3 w-3"})})]}):e.jsxs("span",{className:"cursor-pointer text-muted-foreground hover:text-foreground",onClick:()=>dt(B=>({...B,member_default:Is(na("member_default"))})),title:"Click to override",children:["$",Is(na("member_default"))]})})]}),N.filter(B=>!B.is_non_member).map(B=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-[140px] truncate px-2 py-1.5",title:B.name,children:B.name}),e.jsx("td",{className:"px-2 py-1.5",children:e.jsx(O,{type:"number",step:"0.01",min:"0",className:"h-7 w-full text-xs",value:Ze[B.id]??"",onChange:we=>Re(Je=>({...Je,[B.id]:we.target.value})),placeholder:Qr()})}),e.jsx("td",{className:"px-2 py-1.5",children:e.jsx(O,{type:"number",step:"0.01",min:"0",className:"h-7 w-full text-xs",value:de[B.id]??"",onChange:we=>ge(Je=>({...Je,[B.id]:we.target.value})),placeholder:Qr()})}),Ke&&e.jsx("td",{className:"px-2 py-1.5",children:yt[B.id]!==void 0&&yt[B.id]!==""?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(O,{type:"number",step:"0.01",min:"0",className:"h-7 w-20 text-xs",value:yt[B.id],onChange:we=>dt(Je=>({...Je,[B.id]:we.target.value}))}),e.jsx("button",{type:"button",className:"text-muted-foreground hover:text-foreground",onClick:()=>dt(we=>{const Je={...we};return delete Je[B.id],Je}),title:"Reset to auto",children:e.jsx(St,{className:"h-3 w-3"})})]}):e.jsxs("span",{className:"cursor-pointer text-muted-foreground hover:text-foreground",onClick:()=>dt(we=>({...we,[B.id]:Is(na(B.id))})),title:"Click to override",children:["$",Is(na(B.id))]})})]},B.id))]})]}),e.jsx("p",{className:"mt-1.5 px-1 text-[11px] text-muted-foreground",children:"Blank cells inherit from All Members default, then Regular Price."})]}):e.jsxs("div",{className:"mb-3",children:[e.jsx(T,{className:"text-xs",children:"Member price ($)"}),e.jsx(O,{type:"number",step:"0.01",min:"0",value:mt,onChange:B=>ye(B.target.value),placeholder:"Same as regular"})]})]}),e.jsxs("div",{className:"rounded-lg border bg-card p-4",children:[e.jsx(T,{className:"text-sm font-semibold tracking-tight",children:"Registration eligibility"}),e.jsxs(Cn,{className:"mt-3",value:is?"restricted":"open",onValueChange:B=>{B==="open"?(Va(!1),Jt([])):(Va(!0),Jt(we=>
4we.length?we:[j[0]?.id].filter(Boolean)))},children:[e.jsxs("label",{htmlFor:"reg-eligibility-open",className:"flex min-h-[44px] items-center gap-2 text-sm",children:[e.jsx(la,{id:"reg-eligibility-open",value:"open"}),"Open to everyone"]}),e.jsxs("label",{htmlFor:"reg-eligibility-restricted",className:"flex min-h-[44px] items-center gap-2 text-sm",children:[e.jsx(la,{id:"reg-eligibility-restricted",value:"restricted"}),"Restrict to selected membership types"]})]}),is&&e.jsxs("div",{className:"ml-6 mt-1 space-y-1",children:[j.map(B=>e.jsxs("label",{htmlFor:`reg-eligibility-${B.id}`,className:"flex min-h-[44px] items-center gap-2 text-sm",children:[e.jsx(ot,{id:`reg-eligibility-${B.id}`,checked:Tt.includes(B.id),onCheckedChange:we=>Jt(Je=>we===!0?[...Je,B.id]:Je.filter(it=>it!==B.id))}),e.jsx("span",{children:B.name})]},B.id)),Tt.length===0?e.jsx("p",{className:"text-xs text-amber-600 dark:text-amber-400",children:"No types selected â the event will be open to everyone on save."}):e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Child/add-on events inherit this restriction unless they set their own."})]})]}),e.jsxs("div",{className:"rounded-lg border bg-card p-4",children:[e.jsxs("div",{className:"mb-4 flex items-center gap-3",children:[e.jsx("span",{className:"grid h-8 w-8 place-items-center rounded-md bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(ci,{className:"h-4 w-4"})}),e.jsx("span",{className:"text-sm font-semibold tracking-tight",children:"Free membership offer"})]}),e.jsxs("label",{className:"flex min-h-[44px] items-start gap-3",children:[e.jsx(ot,{id:"offer-enabled",checked:jt,onCheckedChange:B=>Ot(B===!0),className:"mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Offer free 1-year membership to non-members"}),e.jsx("p",{className:"mt-0.5 text-xs text-muted-foreground",children:"Non-members can opt in at checkout and receive a free year of membership at the role they select."})]})]}),jt&&e.jsxs("div",{className:"mt-5 space-y-5",children:[e.jsxs("div",{children:[e.jsx(T,{className:"text-sm font-medium",children:"Eligible roles"}),e.jsx("p",{className:"mt-1 mb-2 text-xs text-muted-foreground",children:"Non-members picking one of these roles can claim the offer."}),e.jsxs("div",{className:"space-y-1",children:[(N??[]).filter(B=>B.is_active&&B.eligible_as_non_member_role&&!B.is_non_member).map(B=>e.jsxs("label",{className:"flex min-h-[44px] items-center gap-2",children:[e.jsx(ot,{checked:ht.includes(B.id),onCheckedChange:we=>zt(Je=>we===!0?[...Je,B.id]:Je.filter(it=>it!==B.id))}),e.jsx("span",{className:"text-sm",children:B.name})]},B.id)),(N??[]).filter(B=>B.is_active&&B.eligible_as_non_member_role&&!B.is_non_member).length===0&&e.jsx("p",{className:"text-xs text-muted-foreground",children:'No membership types are marked as eligible for non-member selection. Enable "Eligible as non-member role" on a membership type first.'})]}),ht.length===0&&e.jsx("p",{className:"mt-2 text-xs text-amber-600 dark:text-amber-400",children:"No roles selected â the offer will be disabled on save."})]}),e.jsxs("div",{children:[e.jsx(T,{htmlFor:"offer-months",className:"text-sm font-medium",children:h?.dues_cycle_type==="calendar"?"Minimum membership length":"Membership length"}),e.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[e.jsx(O,{id:"offer-months",type:"number",min:1,max:36,value:be,onChange:B=>lt(parseInt(B.target.value,10)||12),className:"min-h-[44px] w-20 text-right"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"months"})]}),h?.dues_cycle_type==="calendar"&&(()=>{const B=h.dues_cycle_start_month,we=B===1?12:B-1,Je=new Date,it=new Date(Je);it.setMonth(it.getMonth()+(be||0));const ct=it.getMonth()+1>=B?it.getFullYear()+(we<B?1:0):it.getFullYear()+(we<B?0:-1),Nt=new Date(ct,we,0).getDate(),lr=new Date(ct,we-1,Nt).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"});return e.jsxs("p",{className:"mt-1.5 text-xs text-muted-foreground",children:["Calendar-cycle society â actual end-date rounds forward to the next cycle end. Enroll today â expires ",e.jsx("strong",{children:lr}),"."]})})()]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(T,{children:"Capacity"}),e.jsx(O,{type:"number",min:"0",value:nt.capacity??"",onChange:B=>Vt(we=>({...we,capacity:B.target.value?parseInt(B.target.value):null})),placeholder:"Unlimited"})]}),e.jsxs("div",{children:[e.jsx(T,{children:"Status"}),e.jsxs(qe,{value:nt.status,onValueChange:B=>Vt(we=>({...we,status:B})),children:[e.jsx(Le,{children:e.jsx(Ie,{})}),e.jsxs($e,{children:[e.jsx(q,{value:"draft",children:"Draft"}),e.jsx(q,{value:"published",children:"Published"}),e.jsx(q,{value:"closed",children:"Closed"}),e.jsx(q,{value:"cancelled",children:"Cancelled"})]})]})]})]}),e.jsxs("div",{children:[e.jsx(T,{children:"Event App slug"}),e.jsx(O,{value:nt.event_app_event_slug||"",onChange:B=>Vt(we=>({...we,event_app_event_slug:B.target.value})),placeholder:"e.g. 2026am â the slug event-app will use for this event"}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"Type any URL-safe slug. On save, AMS creates (or updates) the matching event-app record. Leave blank to skip event-app integration (commerce-only event)."})]}),e.jsxs("div",{children:[e.jsx(T,{children:"Event website URL"}),e.jsx(O,{value:nt.website_url||"",onChange:B=>Vt(we=>({...we,website_url:B.target.value})),placeholder:"https://example.com/meeting"})]}
4),e.jsxs("div",{children:[e.jsx(T,{children:"External registration URL"}),e.jsx(O,{value:nt.external_registration_url||"",onChange:B=>Vt(we=>({...we,external_registration_url:B.target.value})),placeholder:"https://partner-site.com/register"}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:'If set, the portal "Register" button links here instead of using in-app registration.'})]}),e.jsxs("div",{children:[e.jsx(T,{children:"QBO category"}),e.jsx(O,{value:nt.qbo_category||"",onChange:B=>Vt(we=>({...we,qbo_category:B.target.value||null})),placeholder:"e.g. FGS-Annual-2026 (optional)"}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"Used by QuickBooks sync to categorize registration revenue â map this value to an item and class on the societyâs QuickBooks page. Leave blank to use the default âeventâ category."})]}),e.jsxs("div",{children:[e.jsx(T,{children:"Attendee tag"}),e.jsx(O,{list:"attendee-tag-suggestions",value:nt.attendee_tag||"",onChange:B=>Vt(we=>({...we,attendee_tag:B.target.value||null})),placeholder:"e.g. annual-conference-2026 (optional)"}),e.jsx("datalist",{id:"attendee-tag-suggestions",children:w.map(B=>e.jsx("option",{value:B.tag},B.tag))}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"Members who register for this event get this tag on their profile, for building email campaign lists. Saved lowercase. Changing it also tags everyone already registered."})]}),e.jsxs("div",{className:"mt-3 border-t pt-3",children:[e.jsxs(T,{className:"mb-1 flex items-center gap-1.5 text-sm font-semibold",children:[e.jsx(cs,{className:"h-4 w-4"}),"Registration Form",E&&Q&&e.jsxs("span",{className:"ml-1 inline-flex items-center gap-1 text-xs font-normal text-muted-foreground",children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-emerald-500"}),"Linked to template â",Q.name,"â"]})]}),e.jsx("p",{className:"mb-2 text-xs text-muted-foreground",children:"Select a form template to collect info at registration."}),e.jsxs(qe,{value:E?A??"none":Ce,onValueChange:Z,disabled:U.isPending||D.isPending,children:[e.jsx(Le,{children:U.isPending?e.jsxs("span",{className:"flex items-center gap-1.5 text-sm text-muted-foreground",children:[e.jsx(He,{className:"h-3 w-3 animate-spin"}),"Linkingâ¦"]}):e.jsx(Ie,{placeholder:"No registration form"})}),e.jsxs($e,{children:[e.jsx(q,{value:"none",disabled:E,children:"None"}),p?.map(B=>{const we=E&&B.id===A,Je=P&&B.owning_event_id!=null&&B.owning_event_name!=null&&!we,it=B.form_config.length,ct=`${it} field${it!==1?"s":""}`;return e.jsxs(q,{value:B.id,disabled:Je,className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"font-medium",children:B.name}),e.jsxs("span",{className:"text-muted-foreground text-xs",children:["(",ct,")"]}),P&&we&&e.jsxs("span",{className:"inline-flex items-center gap-1.5 whitespace-nowrap text-xs",children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-emerald-500"}),"Linked here"]}),P&&!we&&!Je&&e.jsxs("span",{className:"inline-flex items-center gap-1.5 whitespace-nowrap text-xs",children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-muted-foreground/60"}),"Available"]}),P&&Je&&e.jsxs("span",{className:"inline-flex items-center gap-1.5 whitespace-nowrap text-xs",children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-amber-500"}),"Linked to â",B.owning_event_name,"â"]}),Je&&e.jsxs("button",{type:"button",onClick:Nt=>{Nt.stopPropagation(),Nt.preventDefault(),window.open(`/registration-forms?duplicate_from=${B.id}`,"_blank","noopener,noreferrer")},className:"ml-auto inline-flex items-center gap-1 rounded border px-2 py-0.5 text-xs hover:bg-accent",children:[e.jsx(za,{className:"h-3 w-3"}),"Duplicate"]})]},B.id)}),!E&&M.length>0&&Ce==="custom"?e.jsxs(q,{value:"custom",children:["Custom (",M.length," field",M.length!==1?"s":"",")"]}):null]})]}),z&&e.jsx("p",{className:"mt-1 text-xs text-destructive",children:z}),E&&!Q&&x&&e.jsxs("div",{className:"mt-3 flex items-center gap-2 rounded-lg border bg-muted/40 p-3 text-xs text-muted-foreground",children:[e.jsx(He,{className:"h-3 w-3 animate-spin"}),"Loading templateâ¦"]}),E&&Q&&e.jsx("div",{className:"mt-3 rounded-lg border bg-muted/40 p-3",children:e.jsxs("div",{className:"flex items-start gap-2.5",children:[e.jsx("span",{className:"mt-1.5 h-1.5 w-1.5 shrink-0 rounded-full bg-emerald-500"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsxs("div",{children:[e.jsxs("p",{className:"text-sm font-medium",children:["This event's form comes from template"," ",e.jsxs("span",{className:"font-semibold",children:["â",Q.name,"â"]}),"."]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Edit the template to change fields here. Existing registrations stay valid."})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(g,{type:"button",variant:"outline",size:"sm",onClick:()=>window.open(`/registration-forms?edit=${Q.id}`,"_blank","noopener,noreferrer"),children:[e.jsx(Rs,{className:"mr-1 h-3 w-3"}),"Open template"]}),e.jsx(g,{type:"button",variant:"outline",size:"sm",onClick:()=>xe(!0),disabled:D.isPending,children:D.isPending?e.jsxs(e.Fragment,{children:[e.jsx(He,{className:"mr-1 h-3 w-3 animate-spin"}),"Unlinkingâ¦"]}):"Customize this event"})]}),ue&&e.jsx("p",{className:`text-xs ${ue.ok?"text-emerald-600":"text-destructive"}`,children:ue.message})]})]})}),Se.length>0&&e.jsxs("div",{className:"mt-1 flex items-center justify-between",children:[e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Se.length," field",Se.length!==1?"s":""," ","will be shown at registration."]}),e.jsxs(g,{type:"button",size:"sm",variant:"outline",onClick:()=>ve(!0),disabled:Oe.length===0,title:Oe.length===0?"Add at least one field to preview":"See what members will see",children:[e.jsx(ca,{className:"mr-1 h-3 w-3"}),"Preview"]})]}),Se.length>0&&e.jsx(Bf,{className:"mt-2",formSections:ce,setFormSections:X,formConfig:Se,setFormConfig:I,onMutate:We,readOnly:E}),Se.length>0&&e.jsxs("div",{className:`mt-2 space-y-1${E?" pointer-events-none opacity-60":""}`,children:[Se.map((B,we)=>{const Je=B.source==="form_field"?f?.find(Nt=>Nt.id===B.field_id):null,it=(B.source==="custom_field"?b?.find(Nt=>Nt.id===B.field_id)?.label:Je?.label)||"Field",ct=!!Je&&bo.has(Je.field_key);return e.jsxs("div",{className:"flex items-center gap-2 rounded bg-muted/50 px-2 py-1 text-xs",children:[e.jsx("span",{className:"min-w-0 flex-1 truncate text-muted-foreground",children:it}),B.source==="custom_field"?e.jsxs("span",{className:"inline-flex items-center gap-1.5 whitespace-nowrap rounded-full bg-emerald-100 px-2 py-0.5 text-[10px] font-medium text-emerald-800 dark:bg-emerald-900/30 dark:text-emerald-300",title:"Pre-fills from the member's saved value; answers update the member profile.",children:[e.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-emerald-600 dark:bg-emerald-400"}),"Saves to profile · Pre-fills from member"]}):e.jsxs("span",{className:"inline-flex items-center gap-1.5 whitespace-nowrap rounded-full bg-slate-100 px-2 py-0.5 text-[10px] font-medium text-slate-700 dark:bg-slate-800 dark:text-slate-300",title:"Stored only on this event registration. Not pre-filled and not written back to the member profile.",children:[e.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-slate-500"}),"Event-only"]}),ct&&e.jsxs("span",{className:"inline-flex items-center gap-1 rounded bg-amber-100 px-1.5 py-0.5 text-[10px] font-medium text-amber-700 dark:bg-amber-900/30 dark:text-amber-400",title:"The portal wizard's contact step already collects this from the member profile, so members won't see this field in the wizard. Other surfaces (admin add-attendee, form preview) still render it.",children:[e.jsx(Bt,{className:"h-3 w-3"}),"Hidden in portal"]}),ce.length>0&&e.jsx(Ss,{value:B.section_id??null,onChange:Nt=>zf(I,B.field_id,Nt,We),noneLabel:"â Unsectioned",className:"h-7 w-32 text-xs",ariaLabel:"Page",disabled:E,children:ce.map(Nt=>e.jsx(q,{value:Nt.id,children:Nt.name},Nt.id))}),e.jsxs("label",{className:`flex items-center gap-1.5 ${!pe||E?"opacity-50":""}`,title:E?"Edit Sync to Event App on the linked template's edit page.":void 0,children:[e.jsx("input",{type:"checkbox",checked:B.sync_to_event_app||!1,disabled:!pe||E,onChange:Nt=>{if(E)return;const Mt=[...M];Mt[we]={...B,sync_to_event_app:Nt.target.checked},I(Mt)},className:`h-3 w-3 rounded border-gray-300${E?" cursor-not-allowed":""}`}),e.jsx("span",{className:"text-muted-foreground",children:"Sync to Event App"})]})]},`${B.field_id}-${we}`)}),!pe&&Se.length>0&&e.jsx("p",{className:"text-xs italic text-muted-foreground",children:"Link this event to Event App to enable field sync."})]}),!E&&t?.event_app_event_slug&&M.some(B=>B.sync_to_event_app)&&(()=>{const B=JSON.stringify(M)!==JSON.stringify(t?.registration_form_config||[]);return e.jsxs("div",{className:"mt-2 flex items-center gap-2",children:[e.jsx(g,{type:"button",size:"sm",variant:"outline",disabled:S||B,onClick:async()=>{_(!0),k(null);try{const we=await Dr.syncRegistrationFields(t.society_id,t.id);we.ok?(k({message:`Synced ${we.fields_synced} field(s) to Event App`,ok:!0}
4),c.invalidateQueries({queryKey:["events"]})):k({message:`Sync failed: ${we.error}`,ok:!1})}catch{k({message:"Failed to sync fields",ok:!1})}finally{_(!1)}},children:S?"Syncingâ¦":"Sync Fields Now"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:t.event_app_schema_synced_at?`Last synced: ${Ct(t.event_app_schema_synced_at).toLocaleString()}`:"Never synced"}),B&&e.jsx("span",{className:"text-xs text-amber-600",children:"Save changes before syncing"})]})})(),v&&e.jsx("p",{className:`mt-1 text-xs ${v.ok?"text-green-600":"text-red-600"}`,children:v.message})]}),t&&t.event_app_event_slug&&(()=>{const B=!!t.parent_event_id&&!!ns&&!ns.event_app_event_slug,we=B?"Link the parent event to event-app first.":void 0,Je=!!t.event_app_metadata_push_error&&t.event_app_metadata_push_error!==oe;return e.jsxs("div",{className:"mt-2 space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(g,{type:"button",size:"sm",variant:"outline",disabled:ee.isPending||B,title:we,onClick:async()=>{le(null);try{const it=await ee.mutateAsync(t.id);it.ok?(le({message:"Event pushed to event-app",ok:!0}),Pe(null)):le({message:`Push failed: ${it.error||"unknown error"}`,ok:!1})}catch(it){const ct=it&&typeof it=="object"&&"response"in it?it.response?.data?.detail??"Failed to push event":"Failed to push event";le({message:ct,ok:!1})}},children:ee.isPending?"Syncingâ¦":"Sync to event-app"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:t.event_app_metadata_pushed_at?`Last pushed: ${Ct(t.event_app_metadata_pushed_at).toLocaleString()}`:"Never pushed"}),B&&e.jsx("span",{className:"text-xs text-amber-600",children:we})]}),se&&e.jsx("p",{className:`text-xs ${se.ok?"text-green-600":"text-red-600"}`,children:se.message}),Je&&(()=>{const it=t.event_app_metadata_push_error||"",ct=it.startsWith(gu),Nt=ct?it.slice(gu.length):it,Mt=ct?"border-amber-200 bg-amber-50 text-amber-800 dark:border-amber-700 dark:bg-amber-950/30 dark:text-amber-200":"border-red-200 bg-red-50 text-red-700 dark:border-red-800 dark:bg-red-950/30 dark:text-red-400",lr=ct?"text-amber-700/80 dark:text-amber-300/80":"text-red-600/80 dark:text-red-400/80",Di=ct?"text-amber-700 hover:text-amber-900 dark:text-amber-200 dark:hover:text-amber-100":"text-red-600 hover:text-red-800 dark:text-red-400 dark:hover:text-red-200";return e.jsxs("div",{className:`flex items-start gap-2 rounded-md border p-2 text-xs ${Mt}`,children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-medium",children:ct?"Event not yet synced":"Last push failed"}),e.jsx("div",{className:"break-words",children:Nt}),e.jsx("div",{className:`mt-0.5 ${lr}`,children:t.event_app_metadata_pushed_at?`Previously pushed ${Ct(t.event_app_metadata_pushed_at).toLocaleString()}`:"Never successfully pushed"})]}),e.jsx("button",{type:"button","aria-label":"Dismiss",className:Di,onClick:()=>Pe(t.event_app_metadata_push_error),children:"Dismiss"})]})})()]})})(),!t&&!_s&&e.jsxs("div",{className:"space-y-3 border-t pt-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-medium",children:"Add-on events (optional)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Additional events attendees can register for alongside this one. They inherit this event as their parent and share its date window."})]}),e.jsxs(g,{type:"button",variant:"outline",size:"sm",onClick:Ht,children:[e.jsx(Rt,{className:"mr-1 h-4 w-4"}),"Add child event"]})]}),et.map((B,we)=>{const Je=nt.start_date||"",it=nt.end_date||"";return e.jsx(L,{className:"border-muted-foreground/20",children:e.jsxs($,{className:"space-y-2 pt-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("span",{className:"text-sm font-medium",children:["Child event ",we+1,B.name&&e.jsxs("span",{className:"font-normal text-muted-foreground",children:[" ","â ",B.name]})]}),e.jsx(g,{type:"button",variant:"ghost",size:"sm",onClick:()=>Zt(B._id),"aria-label":"Remove child event",children:e.jsx(Ft,{className:"h-4 w-4"})})]}),e.jsxs("div",{children:[e.jsx(T,{className:"text-xs",children:"Name"}),e.jsx(O,{value:B.name,onChange:ct=>{const Nt=ct.target.value;Cs(B._id,{name:Nt,slug:B.slug&&B.slug!==Ve(B.name)?B.slug:Ve(Nt)})},required:!0})]}),e.jsxs("div",{children:[e.jsx(T,{className:"text-xs",children:"Slug"}),e.jsx(O,{value:B.slug,onChange:ct=>Cs(B._id,{slug:ct.target.value}),placeholder:"auto-generated from name"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{children:[e.jsx(T,{className:"text-xs",children:"Start date"}),e.jsx(Hr,{value:B.start_date,min:Je||void 0,max:it||void 0,onChange:ct=>Cs(B._id,{start_date:ct})})]}),e.jsxs("div",{children:[e.jsx(T,{className:"text-xs",children:"End date"}),e.jsx(Hr,{value:B.end_date,min:B.start_date||Je||void 0,max:it||void 0,onChange:ct=>Cs(B._id,{end_date:ct})})]})]}),(Je||it)&&e.jsxs("p",{className:"-mt-1 text-xs text-muted-foreground",children:["Must fall within parent event window (",Je||"â¦"," â"," ",it||"â¦",")."]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{children:[e.jsx(T,{className:"text-xs",children:"Regular price ($)"}
4),e.jsx(O,{type:"number",step:"0.01",min:"0",value:B.regular_price,onChange:ct=>Cs(B._id,{regular_price:parseFloat(ct.target.value)||0}),required:!0})]}),e.jsxs("div",{children:[e.jsx(T,{className:"text-xs",children:"Capacity"}),e.jsx(O,{type:"number",min:"0",value:B.capacity??"",onChange:ct=>Cs(B._id,{capacity:ct.target.value?parseInt(ct.target.value):null}),placeholder:"Unlimited"})]})]}),e.jsxs("div",{children:[e.jsx(T,{className:"text-xs",children:"Venue"}),e.jsx(O,{value:B.venue,onChange:ct=>Cs(B._id,{venue:ct.target.value}),placeholder:"e.g. Phoenix Convention Center",required:!0})]}),e.jsxs("div",{children:[e.jsx(T,{className:"text-xs",children:"Address"}),e.jsx(O,{value:B.address,onChange:ct=>Cs(B._id,{address:ct.target.value}),placeholder:"Optional"})]}),e.jsxs("div",{children:[e.jsx(T,{className:"text-xs",children:"Status"}),e.jsxs(qe,{value:B.status,onValueChange:ct=>Cs(B._id,{status:ct}),children:[e.jsx(Le,{children:e.jsx(Ie,{})}),e.jsxs($e,{children:[e.jsx(q,{value:"draft",children:"Draft"}),e.jsx(q,{value:"published",children:"Published"})]})]})]}),e.jsxs("div",{children:[e.jsx(T,{className:"text-xs",children:"Event App slug"}),e.jsx(O,{value:B.event_app_event_slug,onChange:ct=>Cs(B._id,{event_app_event_slug:ct.target.value}),placeholder:"e.g. 2026am-preconf"}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"Links this child to event-app for the attendee experience. Leave blank to create a commerce-only add-on with no event-app presence."})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Pricing tiers and registration form can be configured after creation by editing the child."})]})},B._id)})]}),qt&&e.jsx("div",{className:"rounded-md border border-red-200 bg-red-50 p-2 text-sm text-red-700",children:qt}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(g,{type:"button",variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(g,{type:"submit",disabled:i.isPending||l.isPending||m.isPending||U.isPending||D.isPending||y.isFetching,children:U.isPending||D.isPending||y.isFetching?e.jsxs(e.Fragment,{children:[e.jsx(He,{className:"mr-1 h-3 w-3 animate-spin"}),"Updatingâ¦"]}):t?"Save changes":"Create event"})]})]})]})}),e.jsx(Fe,{open:K,onOpenChange:xe,children:e.jsxs(Te,{className:"max-w-md",children:[e.jsx(Ae,{children:e.jsxs(Ee,{children:["Stop syncing with template â",Q?.name,"â?"]})}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Future edits to the template will no longer apply to this event. The event keeps its current fields â existing registrations stay valid."}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(g,{type:"button",variant:"outline",onClick:()=>xe(!1),children:"Cancel"}),e.jsx(g,{type:"button",onClick:async()=>{if(t?.id){_e(null);try{await D.mutateAsync(t.id);const B=await y.refetch();B.data&&(I(B.data.registration_form_config??[]),X(B.data.form_sections??[]),ze("custom")),xe(!1),_e({message:"This event's form is now editable.",ok:!0})}catch{xe(!1),_e({message:"Failed to unlink. Please try again.",ok:!1})}}},disabled:D.isPending,children:D.isPending?e.jsxs(e.Fragment,{children:[e.jsx(He,{className:"mr-1 h-3 w-3 animate-spin"}),"Unlinkingâ¦"]}):"Stop syncing"})]})]})}),ke&&e.jsx(_f,{open:ke,onOpenChange:ve,fields:Oe,sections:Qe,eventName:`${nt.name||"Untitled event"} (preview)`,onSubmit:()=>ve(!1)})]})}function K4(){const t=kt(),{enabled:s,loaded:a}=xn("commerce"),{data:n,isLoading:r}=Lg(),{data:i}=Qs(),{data:l}=mk(),{data:m}=Kx(i?.id),c=$g(),[d,u]=o.useState(!1);if(a&&!s)return e.jsx(_t,{to:"/",replace:!0});const h=ik(),[p,x]=o.useState(!1),[f,b]=o.useState(void 0),[N,j]=o.useState(void 0),[w,v]=o.useState(null),[k,S]=o.useState(""),[_,y]=o.useState(null),[C,P]=o.useState(null),[A,E]=o.useState(()=>new Set),Q=ee=>{E(se=>{const le=new Set(se);return le.has(ee)?le.delete(ee):le.add(ee),le})},[U,D]=o.useState(!1),K=new Map;for(const ee of n??[])if(ee.parent_event_id){const se=K.get(ee.parent_event_id)??[];se.push(ee),K.set(ee.parent_event_id,se)}const xe=(n??[]).filter(ee=>!ee.parent_event_id),z=ee=>{if(!i?.slug)return;const se=`${window.location.origin}/${i.slug}/portal/signup?mode=event-registration&event=${ee}`;navigator.clipboard.writeText(se),y(ee),setTimeout(()=>y(null),2e3)},ae=ee=>{b(ee),j(void 0),x(!0)},ue=()=>{b(void 0),j(void 0),x(!0)},_e=ee=>{b(void 0),j(ee),x(!0)};return e.jsx(nr,{tourIds:["phone-orders"],children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-brand-navy
4/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(Yt,{className:"h-5 w-5"})}),e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:"Events"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[m?.configured&&m.base_url&&i?.id&&e.jsxs(g,{variant:"outline",onClick:()=>{const ee=window.open("about:blank","_blank");Dr.getAdminSsoToken(i.id).then(({token:se,base_url:le})=>{const oe=`${le.replace(/\/$/,"")}/api/auth/verify-member?token=${encodeURIComponent(se)}&redirect=${encodeURIComponent("/")}`;ee?ee.location.href=oe:window.location.href=oe}).catch(se=>{console.error("Event-app admin SSO failed",se),ee&&ee.close()})},children:[e.jsx(Rs,{className:"mr-2 h-4 w-4"}),"Open in event app"]}),e.jsxs(g,{onClick:ue,children:[e.jsx(Rt,{className:"mr-2 h-4 w-4"}),"Create event"]})]})]}),l&&l.length>0&&e.jsx(L,{className:"min-w-0 overflow-hidden border-amber-300 bg-amber-50 dark:border-amber-700 dark:bg-amber-950/30",children:e.jsxs($,{className:"pb-3 pt-4",children:[e.jsxs("button",{type:"button",className:"flex w-full items-center gap-2 text-left",onClick:()=>u(!d),children:[e.jsx(Bt,{className:"h-4 w-4 flex-shrink-0 text-amber-600"}),e.jsxs("span",{className:"font-medium text-amber-800 dark:text-amber-200",children:[l.length," registration",l.length!==1?"s":""," failed to sync to Event App"]}),d?e.jsx(ps,{className:"ml-auto h-4 w-4"}):e.jsx(ts,{className:"ml-auto h-4 w-4"})]}),d&&e.jsx("div",{className:"mt-3 space-y-2",children:l.map(ee=>e.jsxs("div",{className:"flex items-center justify-between rounded border border-amber-200 bg-white px-3 py-2 text-sm dark:border-amber-800 dark:bg-background",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("span",{className:"font-medium",children:ee.member_name||ee.guest_name||"Unknown"}),e.jsxs("span",{className:"text-muted-foreground",children:[" · ",ee.event_name]}),ee.event_app_push_error&&e.jsx("p",{className:"mt-0.5 truncate text-xs text-red-600 dark:text-red-400",children:ee.event_app_push_error})]}),e.jsxs(g,{variant:"outline",size:"sm",className:"ml-3 flex-shrink-0",disabled:c.isPending,onClick:()=>c.mutate({eventId:ee.event_id,registrationId:ee.id}),children:[e.jsx(St,{className:"mr-1 h-3 w-3"}),"Retry"]})]},ee.id))})]})}),r?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(ee=>e.jsx(Y,{className:"h-20 w-full"},ee))}):n?.length?(()=>{const ee=kd(),se=I=>!!I.end_date&&I.end_date<ee,le=xe.filter(I=>!se(I)),oe=xe.filter(se),Pe=I=>{const R=se(I);return A.has(I.id)?!R:R},M=(I,R)=>{const X=K.get(I.id)??[],Se=bu(I),ce=X.length>0,ke=Pe(I);return e.jsx(L,{className:"min-w-0 overflow-hidden",children:e.jsxs($,{className:"p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4 cursor-pointer",role:"link",tabIndex:0,onClick:ve=>{Vi(ve)||t(`/events/${I.id}`)},onKeyDown:ve=>{(ve.key==="Enter"||ve.key===" ")&&ve.target===ve.currentTarget&&!Vi(ve)&&(ve.preventDefault(),t(`/events/${I.id}`))},children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"mb-1 flex items-center gap-2",children:[ce?e.jsx("button",{type:"button",className:"text-muted-foreground hover:text-foreground","aria-label":ke?"Expand child events":"Collapse child events","aria-expanded":!ke,onClick:()=>Q(I.id),children:ke?e.jsx(ts,{className:"h-4 w-4"}):e.jsx(ps,{className:"h-4 w-4"})}):e.jsx("span",{className:"inline-block w-4","aria-hidden":"true"}),e.jsx(je,{to:`/events/${I.id}`,className:"font-semibold text-brand-navy hover:underline dark:text-sky-300",children:I.name}),e.jsx(pu,{status:I.status}),e.jsx(Ac,{count:I.registration_count,capacity:I.capacity}),ce&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",X.length," add-on",X.length!==1?"s":"",")"]})]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[I.start_date&&e.jsx("span",{children:I.start_date}),Se&&e.jsxs("span",{children:[" · ",Se]}),e.jsxs("span",{children:[" · ",xu(I.revenue)," earned"]}),I.type_prices?.member_default&&"price"in I.type_prices.member_default&&I.type_prices.member_default.price!==void 0&&e.jsxs("span",{children:[" ","(member: $",I.type_prices.member_default.price.toFixed(2),")"]}),I.type_prices&&(()=>{const ve=Object.keys(I.type_prices).filter(Ne=>Ne!=="member_default"&&Ne!=="early_bird").length;return ve>0?e.jsxs("span",{children:[" ","· ",ve," type price",ve!==1?"s":""]}):null})()]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsxs(g,{variant:"outline",size:"sm",onClick:()=>_e(I),children:[e.jsx(Rt,{className:"mr-1 h-3.5 w-3.5"}),"Add child event"]}),e.jsx(g,{variant:"ghost",size:"sm",title:"Copy registration link","aria-label":"Copy registration link",onClick:()=>z(I.id),children:_===I.id?e.jsx(Xt,{className:"h-4 w-4 text-emerald-500"}):e.jsx(li,{className:"h-4 w-4"})}),e.jsx(g,{variant:"ghost",size:"sm",...R?{"data-tour":"event-registrants"}:{},"aria-label":"Registration quickview",onClick:()=>{v(I.id),S(I.name)},children:e.jsx(Lt,{className:"h-4 w-4"})}),e.jsx(g,{variant:"ghost",size:"sm","aria-label":"Edit event",onClick:()=>ae(I),children:e.jsx(wr,{className:"h-4 w-4"})}),e.jsx(g,{variant:"ghost",size:"sm","aria-label":"Delete event",disabled:h.isPending,onClick:()=>P(I),children:e.jsx(Ft,{className:"h-4 w-4"})})]})]}),ce&&!ke&&e.jsxs("div",{className:"mt-4 border-l-2 border-muted pl-4",children:[e.jsx("div",{className:"mb-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Child events"}),e.jsx("div",{className:"space-y-2",children:X.map(ve=>{const Ne=bu(ve);return e.jsxs("div",{className:"flex items-start justify-between gap-3 rounded border bg-muted/30 p-3 cursor-pointer",role:"link",tabIndex:0,onClick:Qe=>
4{Vi(Qe)||t(`/events/${ve.id}`)},onKeyDown:Qe=>{(Qe.key==="Enter"||Qe.key===" ")&&Qe.target===Qe.currentTarget&&!Vi(Qe)&&(Qe.preventDefault(),t(`/events/${ve.id}`))},children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"mb-0.5 flex items-center gap-2",children:[e.jsx(je,{to:`/events/${ve.id}`,className:"text-sm font-medium text-brand-navy hover:underline dark:text-sky-300",children:ve.name}),e.jsx(pu,{status:ve.status}),e.jsx(Ac,{count:ve.registration_count,capacity:ve.capacity})]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[ve.start_date&&e.jsx("span",{children:ve.start_date}),Ne&&e.jsxs("span",{children:[" · ",Ne]}),e.jsxs("span",{children:[" · ",xu(ve.revenue)," earned"]})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(g,{variant:"ghost",size:"sm",title:"Copy registration link","aria-label":"Copy registration link",onClick:()=>z(ve.id),children:_===ve.id?e.jsx(Xt,{className:"h-4 w-4 text-emerald-500"}):e.jsx(li,{className:"h-4 w-4"})}),e.jsx(g,{variant:"ghost",size:"sm","aria-label":"Registration quickview",onClick:()=>{v(ve.id),S(ve.name)},children:e.jsx(Lt,{className:"h-4 w-4"})}),e.jsx(g,{variant:"ghost",size:"sm","aria-label":"Edit event",onClick:()=>ae(ve),children:e.jsx(wr,{className:"h-4 w-4"})}),e.jsx(g,{variant:"ghost",size:"sm","aria-label":"Delete event",disabled:h.isPending,onClick:()=>P(ve),children:e.jsx(Ft,{className:"h-4 w-4"})})]})]},ve.id)})})]})]})},I.id)};return e.jsxs(e.Fragment,{children:[le.length>0&&e.jsx("div",{className:"space-y-3",children:le.map((I,R)=>M(I,R===0))}),le.length===0&&oe.length>0&&e.jsx(L,{className:"min-w-0 overflow-hidden",children:e.jsx($,{className:"py-6 text-center text-sm text-muted-foreground",children:"No upcoming events. See past events below."})}),oe.length>0&&e.jsxs("div",{className:"mt-6",children:[e.jsxs("button",{type:"button",className:"flex items-center gap-2 py-2 text-sm font-medium text-muted-foreground hover:text-foreground","aria-expanded":U,onClick:()=>D(!U),children:[U?e.jsx(ps,{className:"h-4 w-4"}):e.jsx(ts,{className:"h-4 w-4"}),"Past events (",oe.length,")"]}),U&&e.jsx("div",{className:"mt-2 space-y-3",children:oe.map(I=>M(I,!1))})]})]})})():e.jsx(L,{className:"min-w-0 overflow-hidden",children:e.jsx($,{className:"py-8 text-center text-muted-foreground",children:"No events created yet."})}),e.jsx(B4,{event:f,parentEvent:N,allEvents:n,open:p,onOpenChange:ee=>{x(ee),ee||(b(void 0),j(void 0))}},f?.id||N?.id||"new"),w&&e.jsx(Uf,{eventId:w,eventName:k,hasChildren:K.has(w??""),open:!!w,onOpenChange:ee=>{ee||v(null)}}),C&&e.jsx(M4,{event:C,childCount:(K.get(C.id)??[]).length,open:!!C,onOpenChange:ee=>{ee||P(null)},onConfirm:async ee=>{await h.mutateAsync({eventId:C.id,confirm_slug:ee})}})]})})}const Ha=t=>t.toLocaleString("en-US",{style:"currency",currency:"USD"}),$d="flex h-7 w-7 shrink-0 items-center justify-center rounded-lg",Yi=`${$d} bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300`;function Q4(){const{theme:t}=bd();return t==="dark"?{bars:"hsl(212 100% 64.5%)",line:"#818cf8"}:{bars:"hsl(var(--brand-navy))",line:"#6366f1"}}function Bo(t,s="MMM d, yyyy"){if(!t)return null;const a=Ps(t);return Number.isNaN(a.getTime())?null:Be(a,s)}function W4(){return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Y,{className:"h-10 w-10 rounded-lg"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Y,{className:"h-7 w-64"}),e.jsx(Y,{className:"h-4 w-40"})]})]}),e.jsx("div",{className:"grid gap-4 md:grid-cols-2 xl:grid-cols-4",children:[0,1,2,3].map(t=>e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx(Y,{className:"h-7 w-7 rounded-lg"}),e.jsx(Y,{className:"h-4 w-28"})]})}),e.jsx($,{children:e.jsx(Y,{className:"h-8 w-20"})})]},t))}),e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx(Y,{className:"h-7 w-7 rounded-lg"}),e.jsx(Y,{className:"h-4 w-40"})]})}),e.jsx($,{children:e.jsx(Y,{className:"h-[280px] w-full"})})]})]})}function V4({onRetry:t}){return e.jsx("div",{className:"space-y-6",children:e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex items-center gap-2.5",children:[e.jsx("span",{className:me($d,"bg-red-100 text-red-600 dark:bg-red-900/30 dark:text-red-400"),children:e.jsx(Bt,{className:"h-4 w-4"})}),"Couldnât load this eventâs dashboard"]})}),e.jsxs($,{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"The event may have been deleted, or the request didnât make it through. Try again."}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(g,{onClick:t,children:[e.jsx(St,{className:"mr-2 h-4 w-4"}),"Try again"]}),e.jsx(g,{variant:"outline",asChild:!0,children:e.jsx(je,{to:"/events",className:"text-foreground",children:"Back to events"})})]})]})]})})}function Hi({title:t,icon:s,iconClass:a,value:n,secondary:r}){return e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-2",children:e.jsxs(ie,{className:"flex items-center gap-2.5",children:[e.jsx("span",{className:me($d,a),children:s}),t]})}),e.jsxs($,{children:[e.jsx("div",{className:"text-2xl font-semibold tracking-tight",children:n}),r&&e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:r})]})]})}function ei({dotClass:t,label:s,count:a}){return e.jsxs("div",{className:"flex items-center justify-between gap-3 text-sm",children:[e.jsxs("span",{className:"flex min-w-0 items-center gap-2",children:[e.jsx("span",{className:me("h-2 w-2 shrink-0 rounded-full",t),"aria-hidden":"true"}),e.jsx("span",{className:"truncate",children:s})]}),e.jsx("span",{className:"shrink-0 font-semibold tracking-tight",children:a.toLocaleStr
4ing()})]})}function G4(){const{id:t}=Ds(),s=kt(),{selectedSocietyId:a}=V(),{enabled:n,loaded:r}=xn("commerce"),{data:i}=Pi(r&&n?t:void 0),{data:l,isLoading:m,isError:c,refetch:d}=uk(r&&n?t:void 0),u=pk(),h=Q4(),[p,x]=o.useState(!1),[f,b]=o.useState(!1),[N,j]=o.useState(!1),w=o.useMemo(()=>(l?.weekly??[]).map(K=>({...K,week:Bo(K.week_start,"MMM d")??K.week_start})),[l?.weekly]),v=async K=>{if(!(!t||!a)){j(!0);try{const{blob:xe,filename:z}=await Wt.downloadEventDashboardReport(t,a,K),ae=URL.createObjectURL(xe),ue=document.createElement("a");ue.href=ae,ue.download=z??`event_${K}.csv`,ue.click(),URL.revokeObjectURL(ae)}catch{Ut.error("Failed to export report")}finally{j(!1)}}};if(r&&!n)return e.jsx(_t,{to:"/",replace:!0});if(!r||m||!c&&!l)return e.jsx(W4,{});if(c||!l)return e.jsx(V4,{onRetry:()=>{d()}});const{event:k,totals:S,mix:_,children:y,membership_wins:C,sync:P}=l,A=_.member_types,E=y.length>0,Q=Bo(k.start_date),U=[];if(S.refund_payment_count>0){const K=S.refund_payment_count,xe=K===1?"payment":"payments",z=S.partial_refund_count;let ae;z===K?ae=`${K.toLocaleString()} ${xe} partially refunded`:z===0?ae=`${K.toLocaleString()} ${xe} refunded`:ae=`${K.toLocaleString()} ${xe} refunded (${z.toLocaleString()} partially)`,S.refunded_via_payment_count>K&&(ae+=` across ${S.refunded_via_payment_count.toLocaleString()} registrations`),U.push(ae)}S.offline_refunded_count>0&&U.push(`${S.offline_refunded_count.toLocaleString()} registration${S.offline_refunded_count===1?"":"s"} refunded offline`),S.cancelled_count>0&&U.push(`${S.cancelled_count.toLocaleString()} cancelled`);const D=K=>{b(K),x(!0)};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[e.jsx(g,{variant:"ghost",size:"icon",onClick:()=>s("/events"),"aria-label":"Back to events",children:e.jsx(es,{className:"h-4 w-4"})}),e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(Kb,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h1",{className:"truncate text-2xl font-semibold tracking-tight",children:k.name}),e.jsxs("p",{className:"mt-1 flex flex-wrap items-center gap-x-1.5 text-sm text-muted-foreground",children:[Q&&e.jsx("span",{children:Q}),k.parent_event_id&&e.jsxs(e.Fragment,{children:[Q&&e.jsx("span",{"aria-hidden":"true",children:"·"}),e.jsxs("span",{children:["Part of"," ",e.jsx(je,{to:`/events/${k.parent_event_id}`,className:"font-medium text-brand-navy hover:underline dark:text-sky-300",children:k.parent_name??"parent event"})]})]})]})]})]}),e.jsxs("div",{className:"flex shrink-0 flex-wrap items-center gap-2",children:[e.jsxs(Ws,{children:[e.jsx(Vs,{asChild:!0,children:e.jsxs(g,{variant:"outline",disabled:N,children:[e.jsx(vs,{className:"mr-2 h-4 w-4"}),"Export"]})}),e.jsxs($s,{align:"end",className:"w-56",children:[e.jsx(wt,{onSelect:()=>D(!0),children:"Registrations CSV"}),e.jsx(wt,{onSelect:()=>{v("weekly")},children:"Weekly registrations CSV"}),e.jsx(wt,{onSelect:()=>{v("financial")},children:"Financial summary CSV"}),e.jsx(wt,{onSelect:()=>{v("membership_wins")},children:"Membership wins CSV"})]})]}),r&&n&&i?.status==="published"&&e.jsx(g,{asChild:!0,variant:"outline",className:"min-h-[44px]",children:e.jsxs(je,{to:`/events/${i.parent_event_id??t}/walk-in`,children:[e.jsx(fa,{className:"mr-2 h-4 w-4"}),"Walk-in desk"]})}),e.jsx(g,{onClick:()=>D(!1),children:"Registration quickview"})]})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2 xl:grid-cols-4",children:[e.jsx(Hi,{title:"Registrations",icon:e.jsx(Lt,{className:"h-4 w-4"}),iconClass:"bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",value:S.own_registrations.toLocaleString(),secondary:E?k.capacity!=null?`Capacity ${k.capacity.toLocaleString()} · ${S.registrations.toLocaleString()} incl. sessions`:`${S.registrations.toLocaleString()} registrations incl. sessions`:k.capacity!=null?`Capacity ${k.capacity.toLocaleStr
4ing()}`:"No capacity limit"}),e.jsx(Hi,{title:"Net revenue",icon:e.jsx(Ua,{className:"h-4 w-4"}),iconClass:"bg-emerald-100 text-emerald-600 dark:bg-emerald-900/30 dark:text-emerald-400",value:Ha(S.net_revenue),secondary:S.comped_amount>0?`${Ha(S.gross_revenue)} gross booked · ${Ha(S.comped_amount)} comped`:`${Ha(S.gross_revenue)} gross booked`}),e.jsx(Hi,{title:"Refunds & cancellations",icon:e.jsx(fi,{className:"h-4 w-4"}),iconClass:"bg-amber-100 text-amber-600 dark:bg-amber-900/30 dark:text-amber-400",value:Ha(S.refunded_amount),secondary:U.length>0?U.join(" · "):"No refunds or cancellations"}),e.jsx(Hi,{title:"Membership wins",icon:e.jsx(fa,{className:"h-4 w-4"}),iconClass:"bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",value:(C.offers_granted+C.renewals_count).toLocaleString(),secondary:`${C.offers_granted.toLocaleString()} new members · ${C.renewals_count.toLocaleString()} renewals (${Ha(C.renewals_revenue)})`})]}),e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex items-center gap-2.5",children:[e.jsx("span",{className:Yi,children:e.jsx(Qb,{className:"h-4 w-4"})}),"Registrations over time",e.jsx("span",{className:"text-xs font-normal text-muted-foreground",children:"Bookings by week â includes later cancellations"})]})}),e.jsx($,{children:w.length===0?e.jsx("div",{className:"flex h-[280px] items-center justify-center text-sm text-muted-foreground",children:"No registrations yet â the weekly trend appears once bookings start."}):e.jsx("div",{className:"h-[280px] w-full",children:e.jsx(nn,{width:"100%",height:"100%",children:e.jsxs(dj,{data:w,margin:{top:10,right:10,left:0,bottom:0},children:[e.jsx(Yl,{strokeDasharray:"3 3",vertical:!1,stroke:"hsl(var(--border))"}),e.jsx(_n,{dataKey:"week",fontSize:12,tick:{fill:"hsl(var(--muted-foreground))"},stroke:"hsl(var(--border))"}),e.jsx(rn,{yAxisId:"left",allowDecimals:!1,fontSize:12,tick:{fill:"hsl(var(--muted-foreground))"},stroke:"hsl(var(--border))"}),e.jsx(rn,{yAxisId:"right",orientation:"right",hide:!0}),e.jsx(ln,{cursor:{fill:"hsl(var(--muted-foreground) / 0.08)"},contentStyle:{background:"hsl(var(--popover))",border:"1px solid hsl(var(--border))",borderRadius:"0.5rem",fontSize:"0.75rem",color:"hsl(var(--popover-foreground))"},labelStyle:{color:"hsl(var(--foreground))"},isAnimationActive:!1,formatter:(K,xe)=>[Number(K??0).toLocaleString(),xe==="new_registrations"?"New per week":"Cumulative"],labelFormatter:K=>e.jsxs(e.Fragment,{children:["Week of ",K]})}),e.jsx(Nr,{yAxisId:"left",dataKey:"new_registrations",fill:h.bars,radius:[4,4,0,0]}),e.jsx(di,{yAxisId:"left",type:"monotone",dataKey:"cumulative_registrations",stroke:h.line,strokeWidth:2,dot:!1})]})})})})]}),e.jsxs("div",{className:me("grid gap-4",P&&"lg:grid-cols-2"),children:[e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex items-center gap-2.5",children:[e.jsx("span",{className:Yi,children:e.jsx(_p,{className:"h-4 w-4"})}),"Registrant mix",e.jsx($r,{children:e.jsxs(fs,{children:[e.jsx(ys,{asChild:!0,children:e.jsx("button",{type:"button",className:"text-muted-foreground hover:text-foreground","aria-label":"About registrant mix",children:e.jsx(zp,{className:"h-3.5 w-3.5"})})}),e.jsx(hs,{children:"Membership type evaluated at query time"})]})})]})}),e.jsxs($,{className:"space-y-2.5",children:[A?e.jsxs(e.Fragment,{children:[A.map(K=>e.jsx(ei,{dotClass:K.is_untyped?"bg-muted-foreground/60":"bg-indigo-500 dark:bg-indigo-400",label:K.label,count:K.count},`${K.label}|${K.is_untyped}`)),A.length>0&&e.jsx("div",{className:"border-t border-border","aria-hidden":"true"})]}):e.jsxs(e.Fragment,{children:[e.jsx(ei,{dotClass:"bg-emerald-500",label:"Active members",count:_.active_members}),e.jsx(ei,{dotClass:"bg-amber-500",label:"Other members",count:_.other_members})]}),e.jsx(ei,{dotClass:"bg-brand-navy dark:bg-sky-300",label:"Non-members",count:_.non_members}),e.jsx(ei,{dotClass:"bg-muted-foreground/60",label:"Guests",count:_.guests})]})]}),P&&e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex items-center gap-2.5",children:[e.jsx("span",{className:Yi,children:e.jsx(St,{className:"h-4 w-4"})}),"Event app sync"]})}),e.jsxs($,{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-x-4 gap-y-1.5 text-sm",children:[e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-emerald-500","aria-hidden":"true"}
4),P.pushed.toLocaleString()," pushed"]}),e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-red-500","aria-hidden":"true"}),P.failed.toLocaleString()," failed"]}),e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-muted-foreground/60","aria-hidden":"true"}),P.pending.toLocaleString()," pending"]})]}),P.failures.length>0&&e.jsx("div",{className:"divide-y rounded-md border",children:P.failures.map(K=>e.jsxs("div",{className:"flex items-center justify-between gap-3 bg-red-50 px-3 py-2 dark:bg-red-900/20",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate text-sm font-medium",children:K.name}),e.jsx("div",{className:"truncate text-xs text-muted-foreground",children:K.error})]}),e.jsx(g,{variant:"ghost",size:"sm",className:"shrink-0",disabled:u.isPending,onClick:()=>u.mutate({eventId:K.event_id,registrationId:K.registration_id}),children:"Retry"})]},K.registration_id))})]})]})]}),E&&e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex items-center gap-2.5",children:[e.jsx("span",{className:Yi,children:e.jsx(Wb,{className:"h-4 w-4"})}),"Child events"]})}),e.jsx($,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(Pt,{children:[e.jsx(At,{children:e.jsxs(Ue,{children:[e.jsx(H,{children:"Event"}),e.jsx(H,{children:"Date"}),e.jsx(H,{children:"Registered"}),e.jsx(H,{className:"text-right",children:"Gross"}),e.jsx(H,{className:"text-right",children:"Comped"}),e.jsx(H,{className:"text-right",children:"Net"})]})}),e.jsx(Et,{children:y.map(K=>e.jsxs(Ue,{children:[e.jsx(G,{className:"max-w-[18rem]",children:e.jsx(je,{to:`/events/${K.event_id}`,className:"block truncate font-medium text-brand-navy hover:underline dark:text-sky-300",children:K.name})}),e.jsx(G,{className:"whitespace-nowrap text-muted-foreground",children:Bo(K.start_date,"MMM d")??"â"}),e.jsx(G,{children:e.jsx(Ac,{count:K.registrations,capacity:K.capacity})}),e.jsx(G,{className:"whitespace-nowrap text-right",children:Ha(K.gross_revenue)}),e.jsx(G,{className:"whitespace-nowrap text-right text-muted-foreground",children:K.comped_amount>0?Ha(K.comped_amount):"â"}),e.jsx(G,{className:"whitespace-nowrap text-right",children:Ha(K.net_revenue)})]},K.event_id))})]})})})]}),t&&e.jsx(Uf,{eventId:t,eventName:k.name,hasChildren:E,initialExport:f,open:p,onOpenChange:x})]})}function Y4(){const{eventId:t}=Ds(),{selectedSocietyId:s}=V(),{enabled:a,loaded:n}=xn("commerce"),r=Pi(n&&a?t:void 0),[i,l]=o.useState(0);return n&&!a?e.jsx(_t,{to:"/",replace:!0}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(fa,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:"Walk-in desk"}),e.jsx("p",{className:"break-words text-sm text-muted-foreground",children:r.data?.name??"Event registration"})]})]}),e.jsx(g,{asChild:!0,variant:"outline",className:"min-h-[44px]",children:e.jsx(je,{to:`/events/${t}`,children:"Event dashboard"})})]}),!n||r.isPending?e.jsx("p",{role:"status",className:"text-sm text-muted-foreground",children:"Loading eventâ¦"}):r.isError?e.jsxs("div",{role:"alert",className:"space-y-3",children:[e.jsx("p",{children:"Could not load this event."}),e.jsx(g,{className:"min-h-[44px]",onClick:()=>{r.refetch()},children:"Try again"})]}):r.data?.parent_event_id?e.jsx(_t,{to:`/events/${r.data.parent_event_id}/walk-in`,replace:!0}):r.data?.status!=="published"?e.jsx("p",{className:"text-sm text-muted-foreground",children:"The walk-in desk is available for published events. Publish this event to open the desk."}):e.jsx(L,{className:"min-w-0 overflow-hidden",children:e.jsx($,{className:"p-4 sm:p-6 [&_button:not([role=checkbox])]:min-h-[44px] [&_input]:min-
4h-[44px]",children:e.jsx(If,{eventId:t,walkIn:!0,onClose:()=>l(m=>m+1)},`${s}:${t}:${i}`)})})]})}function H4({product:t,open:s,onOpenChange:a}){const n=gk(),r=fk(),[i,l]=o.useState({name:t?.name||"",description:t?.description||"",price:t?.price??0,inventory_count:t?.inventory_count??null,image_url:t?.image_url||"",is_active:t?.is_active??!0,display_order:t?.display_order??0,qbo_category:t?.qbo_category??null});o.useEffect(()=>{l({name:t?.name||"",description:t?.description||"",price:t?.price??0,inventory_count:t?.inventory_count??null,image_url:t?.image_url||"",is_active:t?.is_active??!0,display_order:t?.display_order??0,qbo_category:t?.qbo_category??null})},[t]);const m=async c=>{c.preventDefault();const d={...i,image_url:i.image_url||null,description:i.description||null};t?await r.mutateAsync({productId:t.id,data:d}):await n.mutateAsync(d),a(!1)};return e.jsx(Fe,{open:s,onOpenChange:a,children:e.jsxs(Te,{className:"max-w-md",children:[e.jsx(Ae,{children:e.jsx(Ee,{children:t?"Edit product":"Create product"})}),e.jsxs("form",{onSubmit:m,className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(T,{children:"Name"}),e.jsx(O,{value:i.name,onChange:c=>l(d=>({...d,name:c.target.value})),required:!0})]}),e.jsxs("div",{children:[e.jsx(T,{children:"Description"}),e.jsx(It,{value:i.description||"",onChange:c=>l(d=>({...d,description:c.target.value})),rows:3})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(T,{children:"Price ($)"}),e.jsx(O,{type:"number",step:"0.01",min:"0",value:i.price,onChange:c=>l(d=>({...d,price:parseFloat(c.target.value)||0})),required:!0})]}),e.jsxs("div",{children:[e.jsx(T,{children:"Inventory"}),e.jsx(O,{type:"number",min:"0",value:i.inventory_count??"",onChange:c=>l(d=>({...d,inventory_count:c.target.value?parseInt(c.target.value):null})),placeholder:"Unlimited"})]})]}),e.jsxs("div",{children:[e.jsx(T,{children:"Image URL"}),e.jsx(O,{value:i.image_url||"",onChange:c=>l(d=>({...d,image_url:c.target.value})),placeholder:"https://â¦"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(T,{children:"Display order"}),e.jsx(O,{type:"number",value:i.display_order,onChange:c=>l(d=>({...d,display_order:parseInt(c.target.value)||0}))})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-6",children:[e.jsx(ss,{checked:i.is_active,onCheckedChange:c=>l(d=>({...d,is_active:c}))}),e.jsx(T,{children:"Active"})]})]}),e.jsxs("div",{children:[e.jsx(T,{children:"QBO category"}),e.jsx(O,{value:i.qbo_category||"",onChange:c=>l(d=>({...d,qbo_category:c.target.value||null})),placeholder:"e.g. FGS-Products (optional)"}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"Used by QuickBooks sync to categorize product revenue â map this value to an item and class on the societyâs QuickBooks page. Leave blank to use the default âproductâ category."})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(g,{type:"button",variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(g,{type:"submit",disabled:n.isPending||r.isPending,children:t?"Save changes":"Create product"})]})]})]})})}function J4(){const{enabled:t,loaded:s}=xn("commerce"),{data:a,isLoading:n}=xk(),{data:r}=Qs();if(s&&!t)return e.jsx(_t,{to:"/",replace:!0});const i=yk(),[l,m]=o.useState(!1),[c,d]=o.useState(void 0),[u,h]=o.useState(null),p=x=>{if(!r?.slug)return;const f=`${window.location.origin}/${r.slug}/portal/signup?mode=event-registration&product=${x}`;navigator.clipboard.writeText(f),h(x),setTimeout(()=>h(null),2e3)};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(Cr,{className:"h-5 w-5"})}),e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:"Products"})]}),e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:e.jsxs(g,{onClick:()=>{d(void 0),m(!0)},children:[e.jsx(Rt,{className:"mr-2 h-4 w-4"}),"Create product"]})})]}),n?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(x=>e.jsx(Y,{className:"h-16 w-full"},x))}):a?.length?e.jsx("div",{className:"space-y-3",children:a.map(x=>e.jsx(L,{className:"min-w-0 overflow-hidden",children:e.jsx($,{className:"p-4",children:e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-semibold",children:x.name}),!x.is_active&&e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full bg-muted px-2.5 py-0.5 text-[11px] font-medium text-muted-foreground",children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-muted-foreground
4/60","aria-hidden":"true"}),"Inactive"]})]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:["$",x.price.toFixed(2),x.inventory_count!==null&&e.jsxs("span",{children:[" · ",x.inventory_count," in stock"]})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(g,{variant:"ghost",size:"sm",title:"Copy purchase link","aria-label":"Copy purchase link",onClick:()=>p(x.id),children:u===x.id?e.jsx(Xt,{className:"h-4 w-4 text-emerald-500"}):e.jsx(li,{className:"h-4 w-4"})}),e.jsx(g,{variant:"ghost",size:"sm","aria-label":"Edit product",onClick:()=>{d(x),m(!0)},children:e.jsx(wr,{className:"h-4 w-4"})}),e.jsx(g,{variant:"ghost",size:"sm","aria-label":"Delete product",disabled:i.isPending,onClick:()=>{confirm(`Delete "${x.name}"?`)&&i.mutate(x.id)},children:e.jsx(Ft,{className:"h-4 w-4"})})]})]})})},x.id))}):e.jsx(L,{className:"min-w-0 overflow-hidden",children:e.jsx($,{className:"py-8 text-center text-muted-foreground",children:"No products created yet."})}),e.jsx(H4,{product:c,open:l,onOpenChange:x=>{m(x),x||d(void 0)}})]})}function Z4({campaign:t,open:s,onOpenChange:a}){const n=jk(),r=vk(),[i,l]=o.useState({name:t?.name||"",description:t?.description||"",goal_amount:t?.goal_amount??null,is_active:t?.is_active??!0,qbo_category:t?.qbo_category??null}),m=async c=>{c.preventDefault(),t?await r.mutateAsync({campaignId:t.id,data:i}):await n.mutateAsync(i),a(!1)};return e.jsx(Fe,{open:s,onOpenChange:a,children:e.jsxs(Te,{className:"max-w-md",children:[e.jsx(Ae,{children:e.jsx(Ee,{children:t?"Edit campaign":"Create campaign"})}),e.jsxs("form",{onSubmit:m,className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(T,{children:"Name"}),e.jsx(O,{value:i.name,onChange:c=>l(d=>({...d,name:c.target.value})),required:!0})]}),e.jsxs("div",{children:[e.jsx(T,{children:"Description"}),e.jsx(It,{value:i.description||"",onChange:c=>l(d=>({...d,description:c.target.value})),rows:3})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(T,{children:"Goal amount ($)"}),e.jsx(O,{type:"number",step:"0.01",min:"0",value:i.goal_amount??"",onChange:c=>l(d=>({...d,goal_amount:c.target.value?parseFloat(c.target.value):null})),placeholder:"Optional"})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-6",children:[e.jsx(ss,{checked:i.is_active,onCheckedChange:c=>l(d=>({...d,is_active:c}))}),e.jsx(T,{children:"Active"})]})]}),e.jsxs("div",{children:[e.jsx(T,{children:"QBO category"}),e.jsx(O,{value:i.qbo_category||"",onChange:c=>l(d=>({...d,qbo_category:c.target.value||null})),placeholder:"e.g. FGS-Donations (optional)"}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"Used by QuickBooks sync to categorize donation revenue â map this value to an item and class on the societyâs QuickBooks page. Leave blank to use the default âdonationâ category."})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(g,{type:"button",variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(g,{type:"submit",disabled:n.isPending||r.isPending,children:t?"Save changes":"Create campaign"})]})]})]})})}function X4(){const{enabled:t,loaded:s}=xn("commerce"),{data:a,isLoading:n}=bk(),r=wk(),[i,l]=o.useState(!1),[m,c]=o.useState(void 0);return s&&!t?e.jsx(_t,{to:"/",replace:!0}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(br,{className:"h-5 w-5"})}),e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:"Donation campaigns"})]}),e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:e.jsxs(g,{onClick:()=>{c(void 0),l(!0)},children:[e.jsx(Rt,{className:"mr-2 h-4 w-4"}),"Create campaign"]})})]}),n?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(d=>e.jsx(Y,{className:"h-16 w-full"},d))}):a?.length?e.jsx("div",{className:"space-y-3",children:a.map(d=>e.jsx(L,{className:"min-w-0 overflow-hidden",children:e.jsx($,{className:"p-4",children:e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-semibold",children:d.name}),!d.is_active&&e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full bg-muted px-2.5 py-0.5 text-[11px] font-medium text-muted-foreground",children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-muted-foreground
4/60","aria-hidden":"true"}),"Inactive"]})]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[d.goal_amount?`Goal: $${d.goal_amount.toFixed(2)}`:"No goal set",d.description&&` â ${d.description}`]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(g,{variant:"ghost",size:"sm","aria-label":"Edit campaign",onClick:()=>{c(d),l(!0)},children:e.jsx(wr,{className:"h-4 w-4"})}),e.jsx(g,{variant:"ghost",size:"sm","aria-label":"Delete campaign",disabled:r.isPending,onClick:()=>{confirm(`Delete "${d.name}"?`)&&r.mutate(d.id)},children:e.jsx(Ft,{className:"h-4 w-4"})})]})]})})},d.id))}):e.jsx(L,{className:"min-w-0 overflow-hidden",children:e.jsx($,{className:"py-8 text-center text-muted-foreground",children:"No campaigns created yet."})}),e.jsx(Z4,{campaign:m,open:i,onOpenChange:d=>{l(d),d||c(void 0)}},m?.id??"new")]})}const e5={pending:"bg-amber-500",abandoned:"bg-muted-foreground/60",paid:"bg-emerald-500",refunded:"bg-muted-foreground/60",failed:"bg-red-500"};function Wf({status:t}){return e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx("span",{className:me("h-1.5 w-1.5 rounded-full",e5[t]||"bg-muted-foreground"),"aria-hidden":"true"}),e.jsx("span",{className:"text-xs font-medium capitalize text-foreground/85",children:t})]})}const t5={event:"Event",product:"Product",donation:"Donation"},s5=3600*1e3;function Vf(t){return t.status==="pending"&&Date.now()-Ct(t.created_at).getTime()>s5?"abandoned":t.status}function a5({order:t,open:s,onOpenChange:a,onDownloadReceipt:n}){return t?e.jsx(Fe,{open:s,onOpenChange:a,children:e.jsxs(Te,{className:"max-w-lg",children:[e.jsx(Ae,{children:e.jsx(Ee,{children:"Order details"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3 text-sm",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Status"}),e.jsx("div",{children:e.jsx(Wf,{status:Vf(t)})})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Date"}),e.jsx("div",{children:Be(pt(t.created_at),"MMM d, yyyy h:mm a")})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Customer"}),e.jsx("div",{children:t.member_name||t.guest_name||"Unknown"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:t.member_email||t.guest_email})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Total"}),e.jsx("div",{className:"text-2xl font-semibold tracking-tight",children:t.total.toLocaleString("en-US",{style:"currency",currency:"USD"})})]})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"mb-2 font-medium",children:"Line items"}),e.jsx("div",{className:"divide-y rounded-md border",children:t.line_items.map(r=>e.jsxs("div",{className:"flex items-center justify-between p-3 text-sm",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:r.item_name}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[t5[r.item_type]||r.item_type,r.quantity>1&&` x${r.quantity}`]})]}),e.jsx("span",{className:"font-medium",children:r.total_price.toLocaleString("en-US",{style:"currency",currency:"USD"})})]},r.id))})]}),t.discount_amount>0&&e.jsxs("div",{className:"text-right text-sm text-muted-foreground",children:["Discount: -",t.discount_amount.toLocaleString("en-US",{style:"currency",currency:"USD"})]}),t.has_receipt&&e.jsxs(g,{variant:"outline",size:"sm",onClick:()=>n(t),children:[e.jsx(vs,{className:"mr-1.5 h-4 w-4"}),"Download receipt"]}),t.stripe_payment_intent_id&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Stripe PI: ",t.stripe_payment_intent_id]})]})]})}):null}function n5(){const{enabled:t,loaded:s}=xn("commerce"),{selectedSocietyId:a}=V(),[n,r]=o.useState(1);if(s&&!t)return e.jsx(_t,{to:"/",replace:!0});const[i,l]=o.useState("paid"),[m,c]=o.useState(""),[d,u]=o.useState(""),[h,p]=o.useState(null),x=async j=>{if(a)try{const w=await Wt.downloadOrderReceipt(j.id,a),v=window.URL.createObjectURL(w),k=document.createElement("a");k.href=v,k.download=`receipt-${j.id.slice(0,8)}.pdf`,k.click(),window.URL.revokeObjectURL(v)}catch{}},{data:f,isLoading:b}=Nk({page:n,size:20,status:i||void 0,search:m||void 0}),N=()=>{c(d),r(1)};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-brand-navy
4/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(Wn,{className:"h-5 w-5"})}),e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:"Orders"})]}),e.jsxs("div",{className:"flex gap-3",children:[e.jsxs("div",{className:"flex flex-1 gap-2",children:[e.jsx(O,{placeholder:"Search by email or nameâ¦",value:d,onChange:j=>u(j.target.value),onKeyDown:j=>j.key==="Enter"&&N()}),e.jsx(g,{variant:"outline",onClick:N,children:e.jsx(ya,{className:"h-4 w-4"})})]}),e.jsxs(qe,{value:i,onValueChange:j=>{l(j==="all"?"":j),r(1)},children:[e.jsx(Le,{className:"w-36",children:e.jsx(Ie,{placeholder:"All statuses"})}),e.jsxs($e,{children:[e.jsx(q,{value:"all",children:"All statuses"}),e.jsx(q,{value:"paid",children:"Paid"}),e.jsx(q,{value:"pending",children:"Abandoned"}),e.jsx(q,{value:"refunded",children:"Refunded"}),e.jsx(q,{value:"failed",children:"Failed"})]})]})]}),b?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(j=>e.jsx(Y,{className:"h-16 w-full"},j))}):f?.items.length?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"space-y-2",children:f.items.map(j=>e.jsx(L,{className:"min-w-0 overflow-hidden",children:e.jsx($,{className:"p-4",children:e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium",children:j.member_name||j.guest_name||"Unknown"}),e.jsx(Wf,{status:Vf(j)})]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[Be(pt(j.created_at),"MMM d, yyyy h:mm a")," â ",j.line_items.length," item",j.line_items.length!==1?"s":""]})]}),e.jsx("div",{className:"text-right",children:e.jsx("div",{className:"font-semibold tracking-tight",children:j.total.toLocaleString("en-US",{style:"currency",currency:"USD"})})}),j.has_receipt&&e.jsx(g,{variant:"ghost",size:"sm",onClick:()=>x(j),title:"Download receipt",children:e.jsx(vs,{className:"h-4 w-4"})}),e.jsx(g,{variant:"ghost",size:"sm",onClick:()=>p(j),children:e.jsx(ca,{className:"h-4 w-4"})})]})})},j.id))}),f.pages>1&&e.jsxs("div",{className:"flex items-center justify-center gap-2",children:[e.jsx(g,{variant:"outline",size:"sm",disabled:n===1,onClick:()=>r(n-1),children:e.jsx(Gs,{className:"h-4 w-4"})}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:["Page ",n," of ",f.pages]}),e.jsx(g,{variant:"outline",size:"sm",disabled:n>=f.pages,onClick:()=>r(n+1),children:e.jsx(ts,{className:"h-4 w-4"})})]})]}):e.jsx(L,{className:"min-w-0 overflow-hidden",children:e.jsx($,{className:"py-8 text-center text-muted-foreground",children:"No orders found."})}),e.jsx(a5,{order:h,open:!!h,onOpenChange:j=>{j||p(null)},onDownloadReceipt:x})]})}function r5({promo:t,open:s,onOpenChange:a,onSave:n,isSaving:r}){const[i,l]=o.useState(t?.code||""),[m,c]=o.useState(t?.description||""),[d,u]=o.useState(t?.discount_type||"percentage"),[h,p]=o.useState(t?.discount_value?.toString()||""),[x,f]=o.useState(t?.applies_to||"all"),[b,N]=o.useState(t?.max_uses?.toString()||""),[j,w]=o.useState(t?.valid_from||""),[v,k]=o.useState(t?.valid_until||""),[S,_]=o.useState(t?.is_active??!0),y=C=>{C.preventDefault(),n({code:i.trim().toUpperCase(),description:m||null,discount_type:d,discount_value:parseFloat(h)||0,applies_to:x,max_uses:b?parseInt(b):null,valid_from:j||null,valid_until:v||null,is_active:S})};return e.jsx(Fe,{open:s,onOpenChange:a,children:e.jsxs(Te,{className:"max-w-lg",children:[e.jsx(Ae,{children:e.jsx(Ee,{children:t?"Edit promo code":"Create promo code"})}),e.jsxs("form",{onSubmit:y,className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(T,{children:"Code"}),e.jsx(O,{value:i,onChange:C=>l(C.target.value.toUpperCase()),placeholder:"e.g. EARLYBIRD",required:!0,maxLength:50,className:"font-mono uppercase"})]}),e.jsxs("div",{children:[e.jsx(T,{children:"Description (admin notes)"}),e.jsx(O,{value:m,onChange:C=>c(C.target.value),placeholder:"e.g. Early bird 10% off for spring event",maxLength:255})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(T,{children:"Discount type"}),e.jsxs(qe,{value:d,onValueChange:C=>u(C),children:[e.jsx(Le,{children:e.jsx(Ie,{})}),e.jsxs($e,{children:[e.jsx(q,{value:"percentage",children:"Percentage (%)"}),e.jsx(q,{value:"fixed",children:"Fixed ($)"})]})]})]}),e.jsxs("div",{children:[e.jsx(T,{children:d==="percentage"?"Discount (%)":"Discount ($)"}),e.jsx(O,{type:"number",value:h,onChange:C=>p(C.target.value),min:"0.01",max:d==="percentage"?"100":void 0,step:"0.01",required:!0})]})]}),e.jsxs("div",{children:[e.jsx(T,{children:"Applies to"}),e.jsxs(qe,{value:x,onValueChange:C=>f(C),children:[e.jsx(Le,{children:e.jsx(Ie,{})}),e.jsxs($e,{children:[e.jsx(q,{value:"all",children:"All commerce"}),e.jsx(q,{value:"events",children:"Events only"}),e.jsx(q,{value:"products",children:"Products only"})]})]}),e.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:[e.jsx("strong",{children:"All commerce"})," discounts events, products, donations, and initial dues at signup (e.g. referral codes). Renewal dues at portal checkout are never discounted â for $0 first-year dues, use the Free Membership Offer on an event."]})]}),e.jsxs("div",{children:[e.jsx(T,{children:"Max uses (leave empty for unlimited)"}),e.jsx(O,{type:"number",value:b,onChange:C=>N(C.target.value),min:"1",placeholder:"Unlimited"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(T,{children:"Valid from"}),e.jsx(O,{type:"date",value:j,onChange:C=>w(C.target.value)})]}),e.jsxs("div",{children:[e.jsx(T,{children:"Valid until"}
4),e.jsx(O,{type:"date",value:v,onChange:C=>k(C.target.value)})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ss,{checked:S,onCheckedChange:_}),e.jsx(T,{children:"Active"})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(g,{type:"button",variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(g,{type:"submit",disabled:r||!i.trim()||!h,children:r?"Savingâ¦":t?"Save changes":"Create"})]})]})]})})}function i5({code:t}){const[s,a]=o.useState(!1),n=()=>{navigator.clipboard.writeText(t),a(!0),setTimeout(()=>a(!1),2e3)};return e.jsx("button",{onClick:n,className:"inline-flex items-center gap-1 text-xs text-muted-foreground transition-colors hover:text-foreground",title:"Copy code",children:s?e.jsx(Xt,{className:"h-3 w-3 text-emerald-500"}):e.jsx(za,{className:"h-3 w-3"})})}function l5(){const{data:t,isLoading:s}=kk(),a=_k(),n=Sk(),r=Ck(),[i,l]=o.useState(!1),[m,c]=o.useState(null),[d,u]=o.useState(null),{enabled:h,loaded:p}=xn("commerce");if(p&&!h)return e.jsx(_t,{to:"/",replace:!0});const x=()=>{c(null),l(!0)},f=y=>{c(y),l(!0)},b=y=>{m?n.mutate({id:m.id,data:y},{onSuccess:()=>l(!1)}):a.mutate(y,{onSuccess:()=>l(!1)})},N=y=>{r.mutate(y,{onSuccess:()=>u(null)})},j=y=>{n.mutate({id:y.id,data:{is_active:!y.is_active}})},w=y=>y.discount_type==="percentage"?`${y.discount_value}%`:`$${y.discount_value.toFixed(2)}`,v={all:"All commerce",events:"Events",products:"Products"},k=kd(),S=y=>y.is_active?y.valid_until&&y.valid_until<k?{label:"Expired",tone:"danger"}:y.valid_from&&y.valid_from>k?{label:"Scheduled",tone:"warning"}:y.max_uses&&y.current_uses>=y.max_uses?{label:"Maxed out",tone:"danger"}:{label:"Active",tone:"success"}:{label:"Inactive",tone:"neutral"},_=(y,C)=>{const P={success:{pill:"bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400",dot:"bg-emerald-500"},warning:{pill:"bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400",dot:"bg-amber-500"},danger:{pill:"bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400",dot:"bg-red-500"},neutral:{pill:"bg-muted text-muted-foreground",dot:"bg-muted-foreground/60"}}[C];return e.jsxs("span",{className:`inline-flex items-center gap-1.5 rounded-full px-2.5 py-0.5 text-[11px] font-medium ${P.pill}`,children:[e.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${P.dot}`,"aria-hidden":"true"}),y]})};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(xa,{className:"h-5 w-5"})}),e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:"Promo codes"})]}),e.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"Create and manage discount codes for events, products, donations, and signup dues."})]}),e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:e.jsxs(g,{onClick:x,children:[e.jsx(Rt,{className:"mr-2 h-4 w-4"}),"Create code"]})})]}),s?e.jsx(L,{className:"min-w-0 overflow-hidden",children:e.jsx($,{className:"space-y-4 py-6",children:[...Array(3)].map((y,C)=>e.jsx(Y,{className:"h-16 w-full"},C))})}):t?.length?e.jsx(L,{className:"min-w-0 overflow-hidden",children:e.jsx($,{className:"p-0",children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full",children:[e.jsx("thead",{className:"bg-muted/30",children:e.jsxs("tr",{className:"border-b hover:bg-transparent",children:[e.jsx("th",{className:"h-10 p-3 text-left text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Code"}),e.jsx("th",{className:"h-10 p-3 text-left text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Discount"}),e.jsx("th",{className:"h-10 p-3 text-left text-[11px] font-semibold uppercase tracking-wider text-muted-foreground
4/80",children:"Applies to"}),e.jsx("th",{className:"h-10 p-3 text-left text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Usage"}),e.jsx("th",{className:"h-10 p-3 text-left text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Valid period"}),e.jsx("th",{className:"h-10 p-3 text-left text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Status"}),e.jsx("th",{className:"h-10 p-3 text-right text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Actions"})]})}),e.jsx("tbody",{children:t.map(y=>{const C=S(y);return e.jsxs("tr",{className:"border-b last:border-0 hover:bg-brand-navy/[0.04] dark:hover:bg-brand-navy/10",children:[e.jsxs("td",{className:"p-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("code",{className:"font-mono text-sm font-semibold",children:y.code}),e.jsx(i5,{code:y.code})]}),y.description&&e.jsx("p",{className:"mt-0.5 text-xs text-muted-foreground",children:y.description})]}),e.jsxs("td",{className:"p-3",children:[e.jsx("span",{className:"font-medium",children:w(y)}),e.jsx("span",{className:"ml-1 text-xs text-muted-foreground",children:(y.discount_type==="percentage","off")})]}),e.jsx("td",{className:"p-3",children:e.jsxs("span",{className:"inline-flex items-center gap-1.5 whitespace-nowrap",children:[e.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-muted-foreground/60"}),e.jsx("span",{className:"text-xs font-medium",children:v[y.applies_to]||y.applies_to})]})}),e.jsxs("td",{className:"p-3 text-sm",children:[y.current_uses,y.max_uses?` / ${y.max_uses}`:""]}),e.jsx("td",{className:"p-3 text-sm text-muted-foreground",children:y.valid_from||y.valid_until?e.jsxs(e.Fragment,{children:[y.valid_from||"..."," â ",y.valid_until||"..."]}):e.jsx("span",{className:"text-xs",children:"No limit"})}),e.jsx("td",{className:"p-3",children:_(C.label,C.tone)}),e.jsx("td",{className:"p-3",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[e.jsx(ss,{checked:y.is_active,onCheckedChange:()=>j(y),className:"mr-2"}),e.jsx(g,{variant:"ghost",size:"icon",onClick:()=>f(y),children:e.jsx(wr,{className:"h-4 w-4"})}),e.jsx(g,{variant:"ghost",size:"icon",onClick:()=>u(y.id),children:e.jsx(Ft,{className:"h-4 w-4 text-destructive"})})]})})]},y.id)})})]})})})}):e.jsx(L,{className:"min-w-0 overflow-hidden",children:e.jsxs($,{className:"py-12 text-center",children:[e.jsx(xa,{className:"mx-auto mb-4 h-12 w-12 text-muted-foreground/30"}),e.jsx("h3",{className:"mb-1 text-lg font-medium",children:"No promo codes yet"}),e.jsx("p",{className:"mb-4 text-sm text-muted-foreground",children:"Create your first discount code to offer promotions to members."}),e.jsxs(g,{onClick:x,children:[e.jsx(Rt,{className:"mr-2 h-4 w-4"}),"Create code"]})]})}),i&&e.jsx(r5,{promo:m,open:i,onOpenChange:l,onSave:b,isSaving:a.isPending||n.isPending}),d&&e.jsx(Fe,{open:!!d,onOpenChange:()=>u(null),children:e.jsxs(Te,{className:"max-w-sm",children:[e.jsx(Ae,{children:e.jsx(Ee,{children:"Delete promo code"})}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"This will deactivate the promo code. It won't affect existing orders that used this code."}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(g,{variant:"outline",onClick:()=>u(null),children:"Cancel"}),e.jsx(g,{variant:"destructive",onClick:()=>N(d),disabled:r.isPending,children:r.isPending?"Deletingâ¦":"Delete"})]})]})})]})}function ju({field:t,open:s,onOpenChange:a,profileFields:n=[]}){const r=w2(),i=wf(),{selectedSocietyId:l}=V(),m=Vx(l??""),[c,d]=o.useState(!1),[u,h]=o.useState({field_key:t?.field_key||"",label:t?.label||"",field_type:t?.field_type||"text",is_required:t?.is_required||!1,options:t?.options||null,help_text:t?.help_text||null,placeholder:t?.placeholder||null}),[p,x]=o.useState(t?.options?.join(", ")||""),[f,b]=o.useState(null),[N,j]=o.useState(!1),w=/^[a-z][a-z0-9_]*$/,v=!t&&u.field_key.length>0&&!w.test(u.field_key)?"Must start with a lowercase letter and contain only lowercase letters, numbers, and underscores.":null,k=t?void 0:n.find(_=>{const y=A=>A.trim().toLowerCase().replace(/\s+/g," "),C=u.label&&y(_.label)===y(u.label),P=u.field_key&&_.field_key===u.field_key;return C||P}),S=async _=>{if(_.preventDefault(),b(null),!t&&!w.test(u.field_key)){b("Field key must start with a lowercase letter and contain only lowercase letters, numbers, and underscores.");return}if(k&&!N){b(`Use the existing "${k.label}" profile field instead, or confirm below to create a separate event-only field.`);return}const y=["dropdown","multi_select"].includes(u.field_type)&&p?p.split(",").map(P=>
4P.trim()).filter(Boolean):null,C={...u,options:y};try{t?await i.mutateAsync({fieldId:t.id,data:C}):c?await m.mutateAsync({field_key:u.field_key,label:u.label,field_type:u.field_type,is_required:u.is_required,options:y,help_text:u.help_text??null,placeholder:u.placeholder??null,display_order:0,show_on_signup:!1,show_in_directory:!1,show_on_profile:!0,applicable_membership_type_ids:null}):await r.mutateAsync(C),a(!1)}catch(P){const E=P?.response?.data?.detail;typeof E=="string"?b(E):Array.isArray(E)&&E.length>0?b(E.map(Q=>Q.msg??"").filter(Boolean).join("; ")):b("Could not save the field. Please check your input and try again.")}};return e.jsx(Fe,{open:s,onOpenChange:a,children:e.jsxs(Te,{className:"max-w-md",children:[e.jsx(Ae,{children:e.jsx(Ee,{children:t?"Edit Field":"Create Field"})}),e.jsxs("form",{onSubmit:S,className:"space-y-3",children:[!t&&e.jsxs("div",{className:"space-y-2 rounded-md border bg-muted/30 p-3",children:[e.jsx("div",{className:"text-xs font-semibold",children:"Where should answers be saved?"}),e.jsxs("div",{className:"space-y-1.5 text-sm",children:[e.jsxs("label",{className:"flex cursor-pointer items-start gap-2",children:[e.jsx("input",{type:"radio",name:"save-target",className:"mt-0.5",checked:!c,onChange:()=>d(!1)}),e.jsxs("span",{children:[e.jsx("span",{className:"font-medium",children:"Event-only field"}),e.jsx("span",{className:"block text-xs text-muted-foreground",children:"Answers stay scoped to this registration. Use for things specific to one event (dietary needs, session preferences)."})]})]}),e.jsxs("label",{className:"flex cursor-pointer items-start gap-2",children:[e.jsx("input",{type:"radio",name:"save-target",className:"mt-0.5",checked:c,onChange:()=>d(!0)}),e.jsxs("span",{children:[e.jsx("span",{className:"font-medium",children:"Profile field"}),e.jsx("span",{className:"block text-xs text-muted-foreground",children:"Pre-fills from the member's saved value and writes answers back to their profile. Use for things you want to know about the member as a whole (highest degree, board certification)."})]})]})]})]}),e.jsxs("div",{children:[e.jsx(T,{children:"Label"}),e.jsx(O,{value:u.label,onChange:_=>h(y=>({...y,label:_.target.value,...t?{}:{field_key:(()=>{const C=_.target.value.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"");return C?/^[a-z]/.test(C)?C:`field_${C}`:""})()}})),required:!0})]}),e.jsxs("div",{children:[e.jsx(T,{children:"Field key"}),e.jsx(O,{value:u.field_key,onChange:_=>h(y=>({...y,field_key:_.target.value})),required:!0,disabled:!!t,"aria-invalid":v?!0:void 0}),e.jsx("p",{className:"mt-0.5 text-xs text-muted-foreground",children:"Lowercase, letters/numbers/underscores only. Must start with a letter."}),v&&e.jsx("p",{className:"mt-0.5 text-xs text-destructive",children:v})]}),e.jsxs("div",{children:[e.jsx(T,{children:"Type"}),e.jsxs(qe,{value:u.field_type,onValueChange:_=>h(y=>({...y,field_type:_})),children:[e.jsx(Le,{children:e.jsx(Ie,{})}),e.jsxs($e,{children:[e.jsx(q,{value:"text",children:"Text"}),e.jsx(q,{value:"textarea",children:"Textarea"}),e.jsx(q,{value:"dropdown",children:"Dropdown"}),e.jsx(q,{value:"multi_select",children:"Multi Select"}),e.jsx(q,{value:"checkbox",children:"Checkbox"}),e.jsx(q,{value:"number",children:"Number"}),e.jsx(q,{value:"date",children:"Date"}),e.jsx(q,{value:"email",children:"Email"}),e.jsx(q,{value:"phone",children:"Phone"}),e.jsx(q,{value:"url",children:"URL"})]})]})]}),["dropdown","multi_select"].includes(u.field_type)&&e.jsxs("div",{children:[e.jsx(T,{children:"Options (comma-separated)"}),e.jsx(O,{value:p,onChange:_=>x(_.target.value),placeholder:"Option A, Option B, Option C"})]}),e.jsxs("div",{children:[e.jsx(T,{children:"Help text"}),e.jsx(O,{value:u.help_text||"",onChange:_=>h(y=>({...y,help_text:_.target.value||null})),placeholder:"Optional helper text"})]}),e.jsxs("div",{children:[e.jsx(T,{children:"Placeholder"}),e.jsx(O,{value:u.placeholder||"",onChange:_=>h(y=>({...y,placeholder:_.target.value||null})),placeholder:"Optional placeholder"})]}),k&&!c&&e.jsxs("div",{role:"alert",className:"space-y-2 rounded-md border border-amber-300 bg-amber-50 px-3 py-2 text-sm text-amber-900 dark:border-amber-700 dark:bg-amber-900/20 dark:text-amber-100",children:[e.jsxs("p",{className:"font-medium",children:['A profile field named "',k.label,'" already exists.']}),e.jsx("p",{className:"text-xs",children:"Profile fields pre-fill from the member's saved value and write any answer back to their profile. Creating a separate event-only field will collect the same information without pre-filling and without updating the profile."}),e.jsxs("label",{className:"flex items-start gap-2 text-xs",children:[e.jsx("input",{type:"checkbox",className:"mt-0.5 h-3.5 w-3.5",checked:N,onChange:_=>j(_.target.checked)}),e.jsx("span",{children:"Yes, create a separate event-only field anyway"})]})]}),k&&c&&e.jsxs("div",{role:"alert",className:"space-y-1 rounded-md border border-amber-300 bg-amber-50 px-3 py-2 text-sm text-amber-900 dark:border-amber-700 dark:bg-amber-900/20 dark:text-amber-100",children:[e.jsxs("p",{className:"font-medium",children:['A profile field named "',k.label,'" already exists.']}),e.jsx("p",{className:"text-xs",children:'Use the existing field instead â duplicating it as a new profile field will fail with a unique-key conflict. Pick the existing field from "Available fields" instead.'})]}),f&&e.jsx("div",{role:"alert",className:"rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive",children:f}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(g,{type:"button",variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(g,{type:"submit",disabled:r.isPending||i.isPending||m.isPending||!t&&!w.test(u.field_key)||!!k&&!N&&!c,children:t?"Save Changes":c?"Create Profile Field":"Create Event Field"})]})]})]})})}const o5=[{label:"Name",icon:gc,keys:["first_name","last_name","full_name","name","prefix","suffix","middle_name"],description:"Name fields"},{label:"Contact Info",icon:Jc,keys:["first_name","last_name","full_name","name","email","phone","mobile","telephone"],description:"Name + email + phone"}
4,{label:"Address",icon:Fa,keys:["address","street","city","state","zip","postal","country","province","region"],description:"Location fields"},{label:"Professional",icon:Gl,keys:["organization","company","employer","title","job_title","department","specialty","position","occupation","institution","practice","affiliation"],description:"Work & org fields"}],c5=[{value:"equals",label:"is equal to"},{value:"not_equals",label:"is not equal to"},{value:"contains",label:"contains"},{value:"is_empty",label:"is empty"},{value:"is_not_empty",label:"is not empty"}];function d5({value:t,onChange:s,availableTriggers:a}){const n=t!==null,r=a.length===0,i=t&&t.operator!=="is_empty"&&t.operator!=="is_not_empty",l=t?a.find(c=>c.field_key===t.field_key):null,m=!!l&&(l.field_type==="dropdown"||l.field_type==="multi_select")&&Array.isArray(l.options)&&l.options.length>0;return e.jsxs("div",{className:"space-y-2 rounded-md border bg-background p-2 text-xs",children:[e.jsxs("label",{className:"flex items-center gap-2",children:[e.jsx(ss,{checked:n,disabled:r&&!n,onCheckedChange:c=>{if(!c)s(null);else{if(a.length===0)return;s({field_key:a[0].field_key,operator:"equals",value:"",action:"show"})}}}),e.jsx("span",{children:"Show this field conditionally"}),r&&!n&&e.jsx("span",{className:"text-[11px] text-muted-foreground",children:"(add another field first)"})]}),n&&t&&e.jsx("div",{className:"space-y-2 pl-7",children:e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[e.jsxs(qe,{value:t.action,onValueChange:c=>s({...t,action:c}),children:[e.jsx(Le,{className:"h-7 w-[88px] text-xs","aria-label":"Action",children:e.jsx(Ie,{})}),e.jsxs($e,{children:[e.jsx(q,{value:"show",children:"Show"}),e.jsx(q,{value:"hide",children:"Hide"})]})]}),e.jsx("span",{children:"when"}),e.jsxs(qe,{value:t.field_key,onValueChange:c=>s({...t,field_key:c}),children:[e.jsx(Le,{className:"h-7 w-[160px] text-xs","aria-label":"Trigger field",children:e.jsx(Ie,{placeholder:"Select a fieldâ¦"})}),e.jsx($e,{children:a.map(c=>e.jsx(q,{value:c.field_key,children:c.label},c.field_key))})]}),e.jsxs(qe,{value:t.operator,onValueChange:c=>s({...t,operator:c}),children:[e.jsx(Le,{className:"h-7 w-[140px] text-xs","aria-label":"Operator",children:e.jsx(Ie,{})}),e.jsx($e,{children:c5.map(c=>e.jsx(q,{value:c.value,children:c.label},c.value))})]}),i&&m&&e.jsxs(qe,{value:t.value??"",onValueChange:c=>s({...t,value:c}),children:[e.jsx(Le,{className:"h-7 w-[140px] text-xs","aria-label":"Value",children:e.jsx(Ie,{placeholder:"Select valueâ¦"})}),e.jsx($e,{children:l.options.map(c=>e.jsx(q,{value:c,children:c},c))})]}),i&&!m&&e.jsx(O,{className:"h-7 w-[120px] text-xs",value:t.value??"",onChange:c=>s({...t,value:c.target.value}),placeholder:"value"})]})})]})}function Ko({cfg:t,field:s,sections:a,availableTriggers:n,dependentCount:r,onToggleRequired:i,onRemove:l,onMoveToSection:m,onSetConditionalLogic:c}){const{attributes:d,listeners:u,setNodeRef:h,transform:p,transition:x,isDragging:f}=id({id:t.field_id}),[b,N]=o.useState(!1),j={transform:ld.Transform.toString(p),transition:x,opacity:f?.5:void 0,zIndex:f?10:void 0},w=t.conditional_logic!=null;return e.jsxs("div",{ref:h,style:j,className:"rounded-md border bg-card text-sm",children:[e.jsxs("div",{className:"group flex items-center gap-2 p-2.5",children:[e.jsx("button",{type:"button",className:"shrink-0 cursor-grab touch-none p-0.5 text-muted-foreground hover:text-foreground active:cursor-grabbing",...d,...u,children:e.jsx(Tr,{className:"h-3.5 w-3.5"})}),e.jsx("span",{className:"min-w-0 flex-1 truncate font-medium",children:s.label}),e.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1.5 whitespace-nowrap",children:[e.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-muted-foreground/60"}),e.jsx("span",{className:"text-xs font-medium",children:s.field_type})]}),t.source==="custom_field"&&e.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1.5 whitespace-nowrap",children:[e.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-muted-foreground/60"}),e.jsx("span",{className:"text-xs font-medium",children:"Profile"})]}),r>0&&e.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1.5 whitespace-nowrap",title:`${r} other field${r===1?"":"s"} show conditionally based on this field`,children:[e.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-amber-500"}),e.jsx(Bp,{className:"h-3 w-3"}),e.jsxs("span",{className:"text-xs font-medium",children:["Used by ",r]})]}),a.length>0&&e.jsx(Ss,{value:t.section_id??null,onChange:v=>m(t.field_id,v),noneLabel:"â Unsectioned",className:"h-7 w-32 shrink-0 text-xs",ariaLabel:"Section",children:a.map(v=>e.jsx(q,{value:v.id,children:v.name},v.id))}),e.jsxs("label",{className:"flex shrink-0 cursor-pointer items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(ot,{checked:t.required,onCheckedChange:()=>i(t.field_id)}),"Required"]}),e.jsx("button",{type:"button",onClick:()=>N(v=>!v),className:"shrink-0 text-xs "+(w?"font-semibold text-blue-600":"text-muted-foreground hover:text-foreground"),title:w?"Conditional rule active":"Add conditional rule",children:w?"â¡ Conditional":"Conditional"}),e.jsx("button",{type:"button",onClick:()=>l(t.field_id),className:"shrink-0 text-muted-foreground opacity-0 transition-opacity hover:text-destructive group-hover:opacity-100","aria-label":"Remove field",children:e.jsx(ms,{className:"h-3.5 w-3.5"})})]}),b&&e.jsx("div",{className:"border-t bg-muted/30 p-2",children:e.jsx(d5,{value:t.conditional_logic??null,onChange:v=>c(t.field_id,v),availableTriggers:n})})]})}function m5(t,s){const a=t.field_key.toLowerCase(),n=t.label.toLowerCase();return s.some(r=>a===r||a.includes(r)||n.includes(r))}function u5({template:t,fields:s,customFields:a,onClose:n}
4){const r=vf(),i=j2(),[l,m]=o.useState(t?.name||""),[c,d]=o.useState(t?.description||""),[u,h]=o.useState(t?.form_config||[]),[p,x]=o.useState(t?.form_sections||[]),[f,b]=o.useState(!1),[N,j]=o.useState(""),[w,v]=o.useState(!1),k=od(kr(ud,{activationConstraint:{distance:5}}),kr(md,{coordinateGetter:dd})),S=M=>{const{active:I,over:R}=M;!R||I.id===R.id||h(X=>{const Se=X.findIndex(ve=>ve.field_id===I.id),ce=X.findIndex(ve=>ve.field_id===R.id);if(Se===-1||ce===-1)return X;const ke=X[ce].section_id??null;return cd(X,Se,ce).map((ve,Ne)=>({...ve,order:Ne,...ve.field_id===I.id?{section_id:ke}:{}}))})},_=new Map;for(const M of s)_.set(M.id,{id:M.id,label:M.label,field_key:M.field_key,field_type:M.field_type,is_required:M.is_required,is_active:M.is_active,source:"form_field",options:M.options??null});for(const M of a)_.set(M.id,{id:M.id,label:M.label,field_key:M.field_key,field_type:M.field_type,is_required:M.is_required,is_active:M.is_active,source:"custom_field",options:M.options??null});const y=u.map(M=>({cfg:M,field:_.get(M.field_id)})).filter(M=>M.field),C=u.map(M=>{const I=M.source==="custom_field"?a.find(R=>R.id===M.field_id):s.find(R=>R.id===M.field_id);return I?{field_id:I.id,field_key:I.field_key,label:I.label,field_type:I.field_type,required:M.required,options:I.options??null,help_text:I.help_text??null,placeholder:I.placeholder??null,order:M.order,source:M.source??"form_field",section_id:M.section_id??null,conditional_logic:M.conditional_logic??null}:null}).filter(M=>M!==null).sort((M,I)=>M.order-I.order),P=new Set(u.map(M=>M.field_id)),A=s.filter(M=>M.is_active&&!P.has(M.id)),E=a.filter(M=>M.is_active&&!P.has(M.id)),Q=N.toLowerCase().trim(),U=Q?A.filter(M=>M.label.toLowerCase().includes(Q)||M.field_key.toLowerCase().includes(Q)||M.field_type.toLowerCase().includes(Q)):A,D=Q?E.filter(M=>M.label.toLowerCase().includes(Q)||M.field_key.toLowerCase().includes(Q)||M.field_type.toLowerCase().includes(Q)):E,K=[...A.map(M=>_.get(M.id)),...E.map(M=>_.get(M.id))].filter(Boolean),xe=M=>{h(I=>[...I,{field_id:M.id,order:I.length,required:M.is_required,source:M.source}])},z=M=>{h(I=>{const R=M.map((X,Se)=>({field_id:X.id,order:I.length+Se,required:X.is_required,source:X.source}));return[...I,...R]})},ae=M=>{const I=_.get(M)?.field_key;h(R=>{const X=R.filter(ce=>ce.field_id!==M),Se=I!=null&&X.some(ce=>_.get(ce.field_id)?.field_key===I);return X.map(ce=>I&&!Se&&ce.conditional_logic?.field_key===I?{...ce,conditional_logic:null}:ce).map((ce,ke)=>({...ce,order:ke}))})},ue=M=>{h(I=>I.map(R=>R.field_id===M?{...R,required:!R.required}:R))},_e=(M,I)=>zf(h,M,I),ee=(M,I)=>{h(R=>R.map(X=>X.field_id===M?{...X,conditional_logic:I}:X))},se=M=>y.filter(({cfg:I,field:R})=>I.field_id!==M&&R).map(({field:I})=>({field_key:I.field_key,label:I.label,field_type:I.field_type,options:I.options??null})),le=M=>u.filter(I=>I.conditional_logic?.field_key===M).length,oe=async()=>{if(l.trim()){b(!0);try{const M={name:l,description:c||null,form_config:u,form_sections:p};t?await i.mutateAsync({templateId:t.id,data:M}):await r.mutateAsync(M),n()}finally{b(!1)}}},Pe=(M,I)=>e.jsxs("button",{type:"button",onClick:()=>xe({...M,source:I}),className:"flex w-full items-center gap-2 rounded-md border border-dashed p-2.5 text-left text-sm transition-colors hover:border-primary hover:bg-accent",children:[e.jsx(Rt,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),e.jsx("span",{className:"flex-1 font-medium",children:M.label}),e.jsxs("span",{className:"inline-flex items-center gap-1.5 whitespace-nowrap",children:[e.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-muted-foreground/60"}),e.jsx("span",{className:"text-xs font-medium",children:M.field_type})]}),I==="custom_field"?e.jsxs("span",{className:"inline-flex items-center gap-1.5 whitespace-nowrap rounded-full bg-emerald-100 px-2 py-0.5 text-[10px] font-medium text-emerald-800 dark:bg-emerald-900/30 dark:text-emerald-300",title:"Pre-fills from the member's saved value; answers update the member profile.",children:[e.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-emerald-600 dark:bg-emerald-400"}),"Saves to profile · Pre-fills from member"]}):e.jsxs("span",{className:"inline-flex items-center gap-1.5 whitespace-nowrap rounded-full bg-slate-100 px-2 py-0.5 text-[10px] font-medium text-slate-700 dark:bg-slate-800 dark:text-slate-300",title:"Stored only on this event registration. Not pre-filled and not written back to the member profile.",children:[e.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-slate-500"}),"Event-only"]})]},`${I}-${M.id}`);return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(g,{variant:"ghost",size:"sm",onClick:n,children:[e.jsx(es,{className:"mr-1 h-4 w-4"}),"Back"]}),e.jsx("h2",{className:"flex-1 text-lg font-semibold",children:t?"Edit Template":"New Template"}),e.jsxs(g,{variant:"outline",onClick:()=>v(!0),disabled:C.length===0,title:C.length===0?"Add at least one field to preview":"See what members will see",children:[e.jsx(ca,{className:"mr-2 h-4 w-4"}),"Preview"]}),e.jsxs(g,{onClick:oe,disabled:f||!l.trim(),children:[e.jsx(Np,{className:"mr-2 h-4 w-4"}),f?"Saving...":"Save Template"]})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx(T,{children:"Template name"}
4),e.jsx(O,{value:l,onChange:M=>m(M.target.value),placeholder:"e.g. Standard Registration"})]}),e.jsxs("div",{children:[e.jsx(T,{children:"Description"}),e.jsx(O,{value:c,onChange:M=>d(M.target.value),placeholder:"Optional"})]})]}),e.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[e.jsxs("div",{children:[e.jsxs("h3",{className:"mb-2 flex items-center gap-1.5 text-sm font-semibold",children:[e.jsx(cs,{className:"h-4 w-4"}),"Form Fields",y.length>0&&e.jsx(Ts,{variant:"secondary",className:"ml-1 text-xs",children:y.length})]}),e.jsx(Bf,{className:"mb-3",formSections:p,setFormSections:x,formConfig:u,setFormConfig:h}),e.jsx("p",{className:"mb-2 text-xs text-muted-foreground",children:p.length>0?"Use the section dropdown on each field to assign it to a page.":"These fields appear on the registration form. Click a field from the library to add it."}),y.length===0?e.jsx(L,{children:e.jsx($,{className:"py-8 text-center text-sm text-muted-foreground",children:"No fields added yet. Click fields from the library or use a quick block to add them."})}):p.length===0?e.jsx(jl,{sensors:k,collisionDetection:vl,onDragEnd:S,children:e.jsx(wl,{items:y.map(({cfg:M})=>M.field_id),strategy:Nl,children:e.jsx("div",{className:"space-y-1.5",children:y.map(({cfg:M,field:I})=>e.jsx(Ko,{cfg:M,field:I,sections:p,availableTriggers:se(M.field_id),dependentCount:le(I.field_key),onToggleRequired:ue,onRemove:ae,onMoveToSection:_e,onSetConditionalLogic:ee},M.field_id))})})}):e.jsx(jl,{sensors:k,collisionDetection:vl,onDragEnd:S,children:e.jsx(wl,{items:y.map(({cfg:M})=>M.field_id),strategy:Nl,children:e.jsxs("div",{className:"space-y-3",children:[p.map(M=>{const I=y.filter(({cfg:R})=>R.section_id===M.id);return e.jsxs("div",{className:"rounded-md border bg-muted/20 p-2",children:[e.jsxs("div",{className:"mb-1.5 flex items-center gap-2 text-xs font-semibold text-muted-foreground",children:[e.jsx(ts,{className:"h-3 w-3"}),M.name||"Untitled page"]}),I.length===0?e.jsx("p",{className:"px-1 py-2 text-xs text-muted-foreground",children:"No fields on this page yet. Use the dropdown on a field to move it here."}):e.jsx("div",{className:"space-y-1.5",children:I.map(({cfg:R,field:X})=>e.jsx(Ko,{cfg:R,field:X,sections:p,availableTriggers:se(R.field_id),dependentCount:le(X.field_key),onToggleRequired:ue,onRemove:ae,onMoveToSection:_e,onSetConditionalLogic:ee},R.field_id))})]},M.id)}),(()=>{const M=y.filter(({cfg:I})=>!I.section_id);return M.length===0?null:e.jsxs("div",{className:"rounded-md border border-dashed bg-muted/10 p-2",children:[e.jsxs("div",{className:"mb-1.5 flex items-center gap-2 text-xs font-semibold text-muted-foreground",children:[e.jsx(ts,{className:"h-3 w-3"}),"Unsectioned",e.jsxs("span",{className:"inline-flex items-center gap-1.5 whitespace-nowrap",children:[e.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-muted-foreground/60"}),e.jsx("span",{className:"text-xs font-medium",children:"Shows after pages"})]})]}),e.jsx("div",{className:"space-y-1.5",children:M.map(({cfg:I,field:R})=>e.jsx(Ko,{cfg:I,field:R,sections:p,availableTriggers:se(I.field_id),dependentCount:le(R.field_key),onToggleRequired:ue,onRemove:ae,onMoveToSection:_e,onSetConditionalLogic:ee},I.field_id))})]})})()]})})})]}),e.jsxs("div",{className:"space-y-4",children:[(()=>{const M=o5.map(I=>({...I,matches:K.filter(R=>m5(R,I.keys))})).filter(I=>I.matches.length>0);return M.length===0?null:e.jsxs("div",{children:[e.jsxs("h3",{className:"mb-2 flex items-center gap-1.5 text-sm font-semibold",children:[e.jsx(Ar,{className:"h-4 w-4"}),"Quick Add"]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:M.map(I=>{const R=I.icon;return e.jsxs("button",{type:"button",onClick:()=>z(I.matches),className:"inline-flex items-center gap-1.5 rounded-full border bg-card px-3 py-1.5 text-sm font-medium transition-colors hover:border-primary hover:bg-accent",title:`Add ${I.matches.length} field${I.matches.length!==1?"s":""}: ${I.matches.map(X=>X.label).join(", ")}`,children:[e.jsx(R,{className:"h-3.5 w-3.5 text-muted-foreground"}),I.label,e.jsx(Ts,{variant:"secondary",className:"px-1.5 py-0 text-[10px]",children:I.matches.length})]},I.label)})})]})})(),e.jsxs("div",{className:"relative",children:[e.jsx(ya,{className:"absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground"}),e.jsx(O,{value:N,onChange:M=>
4j(M.target.value),placeholder:"Search fieldsâ¦",className:"h-9 pl-8 text-sm"}),N&&e.jsx("button",{type:"button",onClick:()=>j(""),className:"absolute right-2.5 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground",children:e.jsx(ms,{className:"h-3.5 w-3.5"})})]}),e.jsxs("div",{children:[e.jsxs("h3",{className:"mb-2 flex items-center gap-1.5 text-sm font-semibold",children:[e.jsx(yc,{className:"h-4 w-4"}),"Available fields",U.length+D.length>0&&e.jsx(Ts,{variant:"outline",className:"ml-1 text-xs",children:U.length+D.length})]}),e.jsx("p",{className:"mb-2 text-xs text-muted-foreground",children:"Profile fields pre-fill from the member's saved value and write answers back to the member profile. Event-only fields stay scoped to this registration."}),U.length+D.length===0?e.jsx("p",{className:"text-xs text-muted-foreground",children:Q?"No matching fields.":"All available fields added."}):e.jsxs("div",{className:"space-y-1",children:[D.map(M=>Pe(M,"custom_field")),D.length>0&&U.length>0&&e.jsxs("div",{className:"my-2 flex items-center gap-2 text-[10px] uppercase tracking-wide text-muted-foreground",children:[e.jsx("span",{className:"h-px flex-1 bg-border"}),e.jsx("span",{children:"Event-only fields"}),e.jsx("span",{className:"h-px flex-1 bg-border"})]}),U.map(M=>Pe(M,"form_field"))]})]})]})]}),w&&e.jsx(_f,{open:w,onOpenChange:v,fields:C,sections:p,eventName:`${l||"Untitled template"} (preview)`,onSubmit:()=>v(!1)})]})}function h5(){const{enabled:t,loaded:s}=xn("commerce"),{data:a,isLoading:n}=jf(),{data:r,isLoading:i}=go(),{data:l}=er(),{data:m}
4=Qs(),c=v2(),d=N2(),u=wf(),h=vf(),[p,x]=ws(),[f,b]=o.useState(null),[N,j]=o.useState(!1),[w,v]=o.useState(void 0),[k,S]=o.useState(null),[_,y]=o.useState(null),C=m?.settings?.template_event_1to1_enabled===!0,P=p.get("duplicate_from");o.useEffect(()=>{if(!P||!a)return;const D=a.find(K=>K.id===P);if(x({},{replace:!0}),!D){y({message:"That template is no longer available. Pick another to duplicate.",ok:!1});return}h.mutate({name:`${D.name} (Copy)`,description:D.description,form_config:D.form_config,form_sections:D.form_sections},{onSuccess:K=>{b(K.id),y({message:"Template duplicated. Edit the name and fields, then save.",ok:!0})},onError:()=>{y({message:"Failed to duplicate template. Please try again.",ok:!1})}})},[P,a]);const A=p.get("edit");o.useEffect(()=>{if(!A||!a)return;x({},{replace:!0});const D=a.find(K=>K.id===A);D&&b(D.id)},[A,a]);const E=D=>{h.mutate({name:`${D.name} (Copy)`,description:D.description,form_config:D.form_config,form_sections:D.form_sections})};if(s&&!t)return e.jsx(_t,{to:"/",replace:!0});const Q=f&&f!=="new"?a?.find(D=>D.id===f):void 0;if(f)return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(vr,{className:"h-5 w-5"})}),e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:"Registration forms"})]}),e.jsx(u5,{template:Q,fields:r||[],customFields:(l||[]).filter(D=>D.is_active),onClose:()=>b(null)},f),e.jsxs("div",{className:"border-t pt-6",children:[e.jsxs("div",{className:"mb-3 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"flex items-center gap-2 text-lg font-semibold",children:[e.jsx(yc,{className:"h-5 w-5"}),"Field Library"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Create new fields here, then add them to the template above."})]}),e.jsxs(g,{onClick:()=>{v(void 0),j(!0)},children:[e.jsx(Rt,{className:"mr-2 h-4 w-4"}),"Create Field"]})]}),U()]}),N&&e.jsx(ju,{field:w,open:N,onOpenChange:D=>{j(D),D||v(void 0)},profileFields:(l||[]).filter(D=>D.is_active)},w?.id||"new-field")]});function U(){return i?e.jsx("div",{className:"space-y-2",children:[1,2,3].map(D=>e.jsx(Y,{className:"h-12 w-full"},D))}):r?.length?e.jsx("div",{className:"space-y-2",children:r.map(D=>e.jsx(L,{className:D.is_active?"":"opacity-60",children:e.jsxs($,{className:"flex items-center justify-between gap-4 p-3",children:[e.jsx("div",{className:"flex min-w-0 flex-1 items-center gap-3",children:e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium",children:D.label}),e.jsxs("span",{className:"inline-flex items-center gap-1.5 whitespace-nowrap",children:[e.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-muted-foreground/60"}),e.jsx("span",{className:"text-xs font-medium",children:D.field_type})]}),D.is_required&&e.jsxs("span",{className:"inline-flex items-center gap-1.5 whitespace-nowrap",children:[e.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-amber-500"}),e.jsx("span",{className:"text-xs font-medium",children:"Required"})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:D.field_key})]})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ss,{checked:D.is_active,onCheckedChange:()=>u.mutate({fieldId:D.id,data:{is_active:!D.is_active}}),"aria-label":`${D.is_active?"Deactivate":"Activate"} field`}),e.jsx(g,{variant:"ghost",size:"sm","aria-label":"Edit field",onClick:()=>{v(D),j(!0)},children:e.jsx(wr,{className:"h-4 w-4"})}),e.jsx(g,{variant:"ghost",size:"sm","aria-label":"Delete field",disabled:d.isPending,onClick:()=>{confirm(`Delete field "${D.label}"?`)&&d.mutate(D.id)},children:e.jsx(Ft,{className:"h-4 w-4"})})]})]})},D.id))}):e.jsx(L,{children:e.jsx($,{className:"py-6 text-center text-muted-foreground",children:"No fields yet. Create one to get started."})})}return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-brand-navy
4/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(vr,{className:"h-5 w-5"})}),e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:"Registration forms"})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"mb-3 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"flex items-center gap-2 text-lg font-semibold",children:[e.jsx(cs,{className:"h-5 w-5"}),"Form Templates"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Reusable form configurations for event registration."})]}),e.jsxs(g,{onClick:()=>b("new"),children:[e.jsx(Rt,{className:"mr-2 h-4 w-4"}),"Create Template"]})]}),n?e.jsx("div",{className:"space-y-2",children:[1,2].map(D=>e.jsx(Y,{className:"h-16 w-full"},D))}):a?.length?e.jsxs(e.Fragment,{children:[_&&e.jsx("p",{className:`mb-2 text-sm ${_.ok?"text-emerald-600":"text-destructive"}`,children:_.message}),e.jsx("div",{className:"space-y-2",children:a.map(D=>e.jsx(L,{className:"cursor-pointer transition-shadow hover:ring-1 hover:ring-ring",onClick:()=>b(D.id),children:e.jsxs($,{className:"flex items-center justify-between gap-4 p-4",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"font-medium",children:D.name}),e.jsxs(Ts,{variant:"secondary",className:"text-xs",children:[D.form_config.length," field",D.form_config.length!==1?"s":""]}),C&&(D.owning_event_id&&D.owning_event_name?e.jsxs("span",{className:"inline-flex items-center gap-1.5 whitespace-nowrap text-xs",children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-amber-500"}),e.jsxs("span",{className:"font-medium text-muted-foreground",children:["Used by â",D.owning_event_name,"â"]})]}):e.jsxs("span",{className:"inline-flex items-center gap-1.5 whitespace-nowrap text-xs",children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-muted-foreground/60"}),e.jsx("span",{className:"font-medium text-muted-foreground",children:"Available"})]}))]}),D.description&&e.jsx("p",{className:"mt-0.5 truncate text-sm text-muted-foreground",children:D.description}),e.jsxs("p",{className:"mt-0.5 text-xs text-muted-foreground",children:["Created ",Ct(D.created_at).toLocaleDateString()]})]}),e.jsxs("div",{className:"flex items-center gap-1",onClick:K=>K.stopPropagation(),children:[e.jsx(g,{variant:"ghost",size:"sm","aria-label":"Duplicate template",disabled:h.isPending,onClick:()=>E(D),children:e.jsx(za,{className:"h-4 w-4"})}),e.jsx(g,{variant:"ghost",size:"sm","aria-label":"Delete template",disabled:c.isPending,onClick:()=>{C&&D.owning_event_id&&D.owning_event_name?S(D):confirm(`Delete template "${D.name}"?`)&&c.mutate(D.id)},children:e.jsx(Ft,{className:"h-4 w-4"})}),e.jsx(ts,{className:"h-4 w-4 text-muted-foreground"})]})]})},D.id))}),e.jsx(Fe,{open:k!==null,onOpenChange:D=>!D&&S(null),children:e.jsxs(Te,{className:"max-w-md",children:[e.jsx(Ae,{children:e.jsxs(Ee,{children:["Delete template â",k?.name,"â?"]})}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["This template is currently used by event â",k?.owning_event_name,"â. Deleting it will copy its current fields onto the event so existing registrations stay valid. The event will no longer sync from a template â you can edit fields directly on the event afterward."]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(g,{type:"button",variant:"outline",onClick:()=>S(null),children:"Cancel"}),e.jsx(g,{type:"button",variant:"destructive",disabled:c.isPending,onClick:()=>{k&&c.mutate(k.id,{onSuccess:()=>S(null)})},children:"Delete template"})]})]})})]}):e.jsx(L,{children:e.jsx($,{className:"py-6 text-center text-muted-foreground",children:"No templates yet. Create one to get started."})})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"mb-3 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"flex items-center gap-2 text-lg font-semibold",children:[e.jsx(yc,{className:"h-5 w-5"}),"Field Library"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Individual field definitions available for use in templates."})]}),e.jsxs(g,{onClick:()=>{v(void 0),j(!0)},children:[e.jsx(Rt,{className:"mr-2 h-4 w-4"}),"Create Field"]})]}),U()]}),N&&e.jsx(ju,{field:w,open:N,onOpenChange:D=>{j(D),D||v(void 0)}},w?.id||"new-field")]})}const Ka={getPolls:async t=>(await F.get("/polls",{params:{society_id:t}})).data,getPoll:async(t,s)=>(await F.get(`/polls/${t}`,{params:{society_id:s}})).data,createPoll:async(t,s)=>(await F.post("/polls",t,{params:{society_id:s}})).data,updatePoll:async(t,s,a)=>(await F.patch(`/polls/${t}`,s,{params:{society_id:a}})).data,deletePoll:async(t,s)=>{await F.delete(`/polls/${t}`,{params:{society_id:s}})},publishPoll:async(t,s)=>(await F.post(`/polls/${t}/publish`,null,{params:{society_id:s}})).data,closePoll:async(t,s)=>(await F.post(`/polls/${t}/close`,null,{params:{society_id:s}})).data,getPollResults:async(t,s)=>(await F.get(`/polls/${t}/results`,{params:{society_id:s}})).data,getPollResponses:async(t,s)=>(await F.get(`/polls/${t}/responses`,{params:{society_id:s}}
4)).data,exportPollCsv:(t,s)=>`${F.defaults.baseURL||"/api/v1"}/polls/${t}/export?society_id=${s}`},Ti={getAnnouncements:async t=>(await F.get("/announcements",{params:{society_id:t}})).data,getAnnouncement:async(t,s)=>(await F.get(`/announcements/${t}`,{params:{society_id:s}})).data,createAnnouncement:async(t,s)=>(await F.post("/announcements",t,{params:{society_id:s}})).data,updateAnnouncement:async(t,s,a)=>(await F.patch(`/announcements/${t}`,s,{params:{society_id:a}})).data,deleteAnnouncement:async(t,s)=>{await F.delete(`/announcements/${t}`,{params:{society_id:s}})},toggleAnnouncement:async(t,s)=>(await F.patch(`/announcements/${t}/toggle`,null,{params:{society_id:s}})).data};function p5(){const{selectedSocietyId:t}=V();return re({queryKey:["admin","polls",t],queryFn:()=>Ka.getPolls(t),enabled:!!t})}function x5(){const{selectedSocietyId:t}=V(),s=J();return W({mutationFn:a=>Ka.createPoll(a,t),onSuccess:()=>s.invalidateQueries({queryKey:["admin","polls"]})})}function g5(){const{selectedSocietyId:t}=V(),s=J();return W({mutationFn:({pollId:a,data:n})=>Ka.updatePoll(a,n,t),onSuccess:()=>s.invalidateQueries({queryKey:["admin","polls"]})})}function f5(){const{selectedSocietyId:t}=V(),s=J();return W({mutationFn:a=>Ka.deletePoll(a,t),onSuccess:()=>s.invalidateQueries({queryKey:["admin","polls"]})})}function y5(){const{selectedSocietyId:t}=V(),s=J();return W({mutationFn:a=>Ka.publishPoll(a,t),onSuccess:()=>s.invalidateQueries({queryKey:["admin","polls"]})})}function b5(){const{selectedSocietyId:t}=V(),s=J();return W({mutationFn:a=>Ka.closePoll(a,t),onSuccess:()=>s.invalidateQueries({queryKey:["admin","polls"]})})}function j5(t){const{selectedSocietyId:s}=V();return re({queryKey:["admin","poll-results",t,s],queryFn:()=>Ka.getPollResults(t,s),enabled:!!s&&!!t})}function v5(t){const{selectedSocietyId:s}=V();return re({queryKey:["admin","poll-responses",t,s],queryFn:()=>Ka.getPollResponses(t,s),enabled:!!s&&!!t})}function w5(){const{selectedSocietyId:t}=V();return re({queryKey:["admin","announcements",t],queryFn:()=>Ti.getAnnouncements(t),enabled:!!t})}function N5(){const{selectedSocietyId:t}=V(),s=J();return W({mutationFn:a=>Ti.createAnnouncement(a,t),onSuccess:()=>s.invalidateQueries({queryKey:["admin","announcements"]})})}function k5(){const{selectedSocietyId:t}=V(),s=J();return W({mutationFn:({announcementId:a,data:n})=>Ti.updateAnnouncement(a,n,t),onSuccess:()=>s.invalidateQueries({queryKey:["admin","announcements"]})})}function _5(){const{selectedSocietyId:t}=V(),s=J();return W({mutationFn:a=>Ti.deleteAnnouncement(a,t),onSuccess:()=>s.invalidateQueries({queryKey:["admin","announcements"]})})}function S5(){const{selectedSocietyId:t}=V(),s=J();return W({mutationFn:a=>Ti.toggleAnnouncement(a,t),onSuccess:()=>s.invalidateQueries({queryKey:["admin","announcements"]})})}function C5({status:t}){return t==="published"?e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full bg-emerald-100 px-2.5 py-0.5 text-[11px] font-medium text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400",children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-emerald-500","aria-hidden":"true"}),t]}):t==="draft"?e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full bg-muted px-2.5 py-0.5 text-[11px] font-medium text-muted-foreground",children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-muted-foreground/60","aria-hidden":"true"}),t]}):e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full bg-muted px-2.5 py-0.5 text-[11px] font-medium text-muted-foreground",children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-muted-foreground/60","aria-hidden":"true"}),t]})}const Gf={text:"Free text",rating:"Rating (1-5)",single_choice:"Single choice",multi_choice:"Multiple choice",scale:"Scale"};function Qo(t){return{question_text:"",type:"text",options:null,order:t,is_required:!0}}function P5(){const{data:t,isLoading:s}=p5(),a=x5(),n=g5(),r=f5(),i=y5(),l=b5(),[m,c]=o.useState(!1),[d,u]=o.useState(null),[h,p]=o.useState(!1),[x,f]=o.useState(),[b,N]=o.useState(!1),[j,w]=o.useState(null),[v,k]=o.useState(""),[S,_]=o.useState(""),[y,C]=o.useState(!1),[P,A]=o.useState(!0),[E,Q]=o.use
4State(""),[U,D]=o.useState(""),[K,xe]=o.useState([Qo(0)]),z=()=>{u(null),k(""),_(""),C(!1),A(!0),Q(""),D(""),xe([Qo(0)]),c(!0)},ae=R=>{u(R),k(R.title),_(R.description||""),c(!0),_e(R.id)},{selectedSocietyId:ue}=V(),_e=async R=>{if(ue)try{const X=await Ka.getPoll(R,ue);C(X.is_anonymous),A(X.show_results_to_members),Q(X.opens_at?X.opens_at.slice(0,16):""),D(X.closes_at?X.closes_at.slice(0,16):""),xe(X.questions.map(Se=>({question_text:Se.question_text,type:Se.type,options:Se.options,order:Se.order,is_required:Se.is_required})))}catch{}},ee=R=>{R.preventDefault();const X={title:v,description:S||null,is_anonymous:y,show_results_to_members:P,opens_at:E||null,closes_at:U||null,questions:K.filter(Se=>Se.question_text.trim())};if(d){const Se={...X};n.mutate({pollId:d.id,data:Se},{onSuccess:()=>c(!1)})}else a.mutate(X,{onSuccess:()=>c(!1)})},se=()=>{xe([...K,Qo(K.length)])},le=R=>{xe(K.filter((X,Se)=>Se!==R))},oe=(R,X)=>{xe(K.map((Se,ce)=>{if(ce!==R)return Se;const ke={...Se,...X};return X.type&&X.type!==Se.type&&(["single_choice","multi_choice"].includes(X.type)?ke.options=["Option 1","Option 2"]:X.type==="scale"?ke.options={min:1,max:10}:ke.options=null),ke}))},Pe=(R,X,Se)=>{const ce=K[R];if(!Array.isArray(ce.options))return;const ke=[...ce.options];ke[X]=Se,oe(R,{options:ke})},M=R=>{const X=K[R];Array.isArray(X.options)&&oe(R,{options:[...X.options,`Option ${X.options.length+1}`]})},I=(R,X)=>{const Se=K[R];Array.isArray(Se.options)&&oe(R,{options:Se.options.filter((ce,ke)=>ke!==X)})};return s?e.jsxs("div",{className:"space-y-4",children:[e.jsx(Y,{className:"h-10 w-48"}),e.jsx(Y,{className:"h-64 w-full"})]}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(Sa,{className:"h-5 w-5"})}),e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:"Polls"})]}),e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:e.jsxs(g,{onClick:z,children:[e.jsx(Rt,{className:"mr-2 h-4 w-4"}),"Create poll"]})})]}),!t||t.length===0?e.jsx(L,{className:"min-w-0 overflow-hidden",children:e.jsxs($,{className:"flex flex-col items-center justify-center py-12",children:[e.jsx(Sa,{className:"mb-4 h-12 w-12 text-muted-foreground"}),e.jsx("p",{className:"text-muted-foreground",children:"No polls yet. Create your first poll to engage members."})]})}):e.jsx("div",{className:"space-y-3",children:t.map(R=>e.jsx(L,{className:"min-w-0 overflow-hidden",children:e.jsx($,{className:"p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"min-w-0 flex-1 space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"truncate font-semibold",children:R.title}),e.jsx(C5,{status:R.status})]}),e.jsxs("div",{className:"flex items-center gap-4 text-sm text-muted-foreground",children:[e.jsxs("span",{children:[R.question_count," question",R.question_count!==1?"s":""]}),e.jsxs("span",{children:[R.response_count," response",R.response_count!==1?"s":""]}),e.jsxs("span",{children:["Created ",Be(pt(R.created_at),"MMM d, yyyy")]}),R.closes_at&&e.jsxs("span",{children:["Closes ",Be(pt(R.closes_at),"MMM d, yyyy")]})]})]}),e.jsxs("div",{className:"ml-4 flex items-center gap-2",children:[R.status==="draft"&&e.jsxs(e.Fragment,{children:[e.jsx(g,{variant:"outline",size:"sm","aria-label":"Edit poll",onClick:()=>ae(R),children:e.jsx(Hs,{className:"h-4 w-4"})}),e.jsxs(g,{size:"sm",onClick:()=>i.mutate(R.id),disabled:i.isPending,children:[e.jsx(Pr,{className:"mr-1 h-4 w-4"}),"Publish"]})]}),R.status==="published"&&e.jsxs(g,{variant:"outline",size:"sm",onClick:()=>l.mutate(R.id),disabled:l.isPending,children:[e.jsx(Ys,{className:"mr-1 h-4 w-4"}),"Close"]}),R.response_count>0&&e.jsxs(e.Fragment,{children:[e.jsxs(g,{variant:"outline",size:"sm",onClick:()=>{f(R.id),N(R.is_anonymous),p(!0)},children:[e.jsx(Sa,{className:"mr-1 h-4 w-4"}),"Results"]}),e.jsx(g,{variant:"ghost",size:"sm","aria-label":"Download CSV",asChild:!0,children:e.jsx("a",{href:Ka.exportPollCsv(R.id,ue),target:"_blank",rel:"noopener noreferrer",children:e.jsx(vs,{className:"h-4 w-4"})})})]}),e.jsx(g,{variant:"ghost",size:"sm","aria-label":"Delete poll",onClick:()=>w(R.id),children:e.jsx(Ft,{className:"h-4 w-4 text-destructive"})})]})]})})},R.id))}),e.jsx(Fe,{open:m,onOpenChange:c,children:e.jsxs(Te,{className:"max-h-[90vh] max-w-2xl overflow-y-auto",children:[e.jsx(Ae,{children:e.jsx(Ee,{children:d?"Edit poll":"Create poll"})}),e.jsxs("form",{onSubmit:ee,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"title",children:"Title"}
4),e.jsx(O,{id:"title",value:v,onChange:R=>k(R.target.value),placeholder:"e.g. Vote on next conference location",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"description",children:"Description"}),e.jsx(It,{id:"description",value:S,onChange:R=>_(R.target.value),placeholder:"Optional descriptionâ¦",rows:2})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"opens_at",children:"Opens at"}),e.jsx(O,{id:"opens_at",type:"datetime-local",value:E,onChange:R=>Q(R.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"closes_at",children:"Closes at"}),e.jsx(O,{id:"closes_at",type:"datetime-local",value:U,onChange:R=>D(R.target.value)})]})]}),e.jsxs("div",{className:"flex items-center gap-6",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ss,{checked:y,onCheckedChange:C}),e.jsx(T,{children:"Anonymous responses"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ss,{checked:P,onCheckedChange:A}),e.jsx(T,{children:"Show results to members"})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(T,{className:"text-base font-semibold",children:"Questions"}),e.jsxs(g,{type:"button",variant:"outline",size:"sm",onClick:se,children:[e.jsx(Rt,{className:"mr-1 h-4 w-4"}),"Add question"]})]}),K.map((R,X)=>e.jsx(L,{className:"space-y-3 p-4",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Tr,{className:"mt-2 h-5 w-5 shrink-0 text-muted-foreground"}),e.jsxs("div",{className:"flex-1 space-y-3",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(O,{value:R.question_text,onChange:Se=>oe(X,{question_text:Se.target.value}),placeholder:"Question textâ¦",className:"flex-1"}),e.jsxs(qe,{value:R.type,onValueChange:Se=>oe(X,{type:Se}),children:[e.jsx(Le,{className:"w-40",children:e.jsx(Ie,{})}),e.jsx($e,{children:Object.entries(Gf).map(([Se,ce])=>e.jsx(q,{value:Se,children:ce},Se))})]})]}),["single_choice","multi_choice"].includes(R.type)&&Array.isArray(R.options)&&e.jsxs("div",{className:"space-y-2 pl-2",children:[R.options.map((Se,ce)=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(O,{value:Se,onChange:ke=>Pe(X,ce,ke.target.value),placeholder:`Option ${ce+1}`,className:"flex-1"}),e.jsx(g,{type:"button",variant:"ghost",size:"sm",onClick:()=>I(X,ce),disabled:R.options.length<=2,children:e.jsx(Ft,{className:"h-4 w-4"})})]},ce)),e.jsxs(g,{type:"button",variant:"ghost",size:"sm",onClick:()=>M(X),children:[e.jsx(Rt,{className:"mr-1 h-4 w-4"}),"Add option"]})]}),R.type==="scale"&&e.jsxs("div",{className:"flex items-center gap-4 pl-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(T,{className:"text-sm",children:"Min:"}),e.jsx(O,{type:"number",className:"w-20",value:R.options?.min??1,onChange:Se=>oe(X,{options:{...R.options||{},min:Number(Se.target.value)}})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(T,{className:"text-sm",children:"Max:"}),e.jsx(O,{type:"number",className:"w-20",value:R.options?.max??10,onChange:Se=>oe(X,{options:{...R.options||{},max:Number(Se.target.value)}})})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ss,{checked:R.is_required??!0,onCheckedChange:Se=>oe(X,{is_required:Se})}),e.jsx(T,{className:"text-sm",children:"Required"})]})]}),e.jsx(g,{type:"button",variant:"ghost",size:"sm",onClick:()=>le(X),disabled:K.length<=1,children:e.jsx(Ft,{className:"h-4 w-4 text-destructive"})})]})},X))]}),e.jsxs(Ge,{children:[e.jsx(g,{type:"button",variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsx(g,{type:"submit",disabled:a.isPending||n.isPending,children:d?"Save changes":"Create poll"})]})]})]})}),e.jsx(A5,{open:h,onOpenChange:p,pollId:x,isAnonymous:b}),e.jsx(Fe,{open:!!j,onOpenChange:()=>w(null),children:e.jsxs(Te,{children:[e.jsx(Ae,{children:e.jsx(Ee,{children:"Delete poll?"})}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"This will permanently delete the poll and all responses. This action cannot be undone."}),e.jsxs(Ge,{children:[e.jsx(g,{variant:"outline",onClick:()=>w(null),children:"Cancel"}),e.jsx(g,{variant:"destructive",disabled:r.isPending,onClick:()=>{j&&(r.mutate(j),w(null))},children:r.isPending?"Deletingâ¦":"Delete"})]})]})})]})}
4function A5({open:t,onOpenChange:s,pollId:a,isAnonymous:n}){const{data:r,isLoading:i}=j5(t?a:void 0),{data:l,isLoading:m}=v5(t?a:void 0);return e.jsx(Fe,{open:t,onOpenChange:s,children:e.jsxs(Te,{className:"max-h-[90vh] max-w-4xl overflow-y-auto",children:[e.jsx(Ae,{children:e.jsxs(Ee,{children:["Poll results",r?`: ${r.title}`:""]})}),e.jsxs(Ur,{defaultValue:"responses",className:"w-full",children:[e.jsxs(ir,{className:"grid w-full grid-cols-2",children:[e.jsxs(bs,{value:"responses",children:[e.jsx(Lt,{className:"mr-1.5 h-4 w-4"}),"Responses"]}),e.jsxs(bs,{value:"summary",children:[e.jsx(Sa,{className:"mr-1.5 h-4 w-4"}),"Summary"]})]}),e.jsxs(js,{value:"responses",className:"mt-4",children:[n&&e.jsxs("div",{className:"mb-4 flex items-center gap-2 rounded-lg border border-amber-200 bg-amber-50 px-4 py-3 dark:border-amber-800 dark:bg-amber-900/20",children:[e.jsx(Er,{className:"h-4 w-4 shrink-0 text-amber-600 dark:text-amber-400"}),e.jsx("p",{className:"text-sm text-amber-800 dark:text-amber-200",children:"This poll is anonymous. Respondent identities are hidden."})]}),m?e.jsxs("div",{className:"space-y-3",children:[e.jsx(Y,{className:"h-10 w-full"}),e.jsx(Y,{className:"h-10 w-full"}),e.jsx(Y,{className:"h-10 w-full"})]}):l&&l.length>0?e.jsx(E5,{responses:l,questions:r?.questions||[],isAnonymous:n}):e.jsx("p",{className:"py-8 text-center text-muted-foreground",children:"No responses yet."})]}),e.jsx(js,{value:"summary",className:"mt-4",children:i?e.jsxs("div",{className:"space-y-4",children:[e.jsx(Y,{className:"h-8 w-48"}),e.jsx(Y,{className:"h-48 w-full"})]}):r?e.jsxs("div",{className:"space-y-6",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:[r.total_responses," total response",r.total_responses!==1?"s":""]}),r.questions.map(c=>e.jsx(T5,{question:c},c.question_id))]}):e.jsx("p",{className:"text-muted-foreground",children:"No results available."})})]})]})})}function E5({responses:t,questions:s,isAnonymous:a}){return e.jsx("div",{className:"max-h-[60vh] overflow-auto rounded-lg border",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"sticky top-0 bg-muted/30",children:e.jsxs("tr",{className:"hover:bg-transparent",children:[!a&&e.jsxs(e.Fragment,{children:[e.jsx("th",{className:"h-10 whitespace-nowrap px-3 text-left text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Name"}),e.jsx("th",{className:"h-10 whitespace-nowrap px-3 text-left text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Email"})]}),e.jsx("th",{className:"h-10 whitespace-nowrap px-3 text-left text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Submitted"}),s.map(n=>e.jsx("th",{className:"h-10 max-w-[200px] truncate px-3 text-left text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",title:n.question_text,children:n.question_text},n.question_id))]})}),e.jsx("tbody",{className:"divide-y",children:t.map(n=>e.jsxs("tr",{className:"hover:bg-brand-navy/[0.04] dark:hover:bg-brand-navy/10",children:[!a&&e.jsxs(e.Fragment,{children:[e.jsx("td",{className:"whitespace-nowrap px-3 py-2 font-medium",children:n.member_name||e.jsx("span",{className:"italic text-muted-foreground",children:"Unknown"})}),e.jsx("td",{className:"whitespace-nowrap px-3 py-2 text-muted-foreground",children:n.member_email||"â"})]}),e.jsx("td",{className:"whitespace-nowrap px-3 py-2 text-muted-foreground",children:Be(pt(n.submitted_at),"MMM d, yyyy h:mm a")}),s.map(r=>e.jsx("td",{className:"max-w-[200px] px-3 py-2",children:e.jsx("span",{className:"line-clamp-2",title:n.answers[r.question_id]||"",children:n.answers[r.question_id]||e.jsx("span",{className:"text-muted-foreground",children:"â"})})},r.question_id))]},n.id))})]})})}function T5({question:t}){const{question_text:s,type:a,total_answers:n,data:r}=t;return e.jsxs(L,{children:[e.jsxs(ne,{className:"pb-2",children:[e.jsxs(ie,{className:"flex items-center gap-2.5",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy
4/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(zl,{className:"h-4 w-4"})}),s]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[n," answer",n!==1?"s":""," ·"," ",Gf[a]||a]})]}),e.jsxs($,{children:[a==="text"&&Array.isArray(r)&&e.jsx("div",{className:"max-h-48 space-y-1 overflow-y-auto",children:r.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No responses"}):r.map((i,l)=>e.jsx("p",{className:"border-b pb-1 text-sm last:border-0",children:i},l))}),(a==="single_choice"||a==="multi_choice")&&r&&typeof r=="object"&&"counts"in r&&e.jsx("div",{className:"h-48",children:e.jsx(nn,{width:"100%",height:"100%",children:e.jsxs(mi,{data:Object.entries(r.counts).map(([i,l])=>({name:i,value:l})),layout:"vertical",children:[e.jsx(_n,{type:"number"}),e.jsx(rn,{type:"category",dataKey:"name",width:120,tick:{fontSize:12}}),e.jsx(ln,{}),e.jsx(Nr,{dataKey:"value",fill:"#3b82f6",radius:[0,4,4,0]})]})})}),(a==="rating"||a==="scale")&&r&&typeof r=="object"&&"average"in r&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-2xl font-semibold tracking-tight",children:r.average}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Average"}),r.distribution&&e.jsx("div",{className:"h-32",children:e.jsx(nn,{width:"100%",height:"100%",children:e.jsxs(mi,{data:Object.entries(r.distribution).sort(([i],[l])=>Number(i)-Number(l)).map(([i,l])=>({name:i,value:l})),children:[e.jsx(_n,{dataKey:"name"}),e.jsx(rn,{}),e.jsx(ln,{}),e.jsx(Nr,{dataKey:"value",fill:"#8b5cf6",radius:[4,4,0,0]})]})})})]})]})]})}function F5(){const{data:t,isLoading:s}=w5(),a=N5(),n=k5(),r=_5(),i=S5(),[l,m]=o.useState(!1),[c,d]=o.useState(null),[u,h]=o.useState(null),[p,x]=o.useState(""),[f,b]=o.useState(""),[N,j]=o.useState(0),[w,v]=o.useState(!0),[k,S]=o.useState(""),_=()=>{d(null),x(""),b(""),j(0),v(!0),S(""),m(!0)},y=P=>{d(P),x(P.title),b(P.content||""),j(P.priority),v(P.is_active),S(P.expires_at?P.expires_at.slice(0,16):""),m(!0)},C=P=>{if(P.preventDefault(),c){const A={title:p,content:f||null,priority:N,is_active:w,expires_at:k||null};n.mutate({announcementId:c.id,data:A},{onSuccess:()=>m(!1)})}else{const A={title:p,content:f||null,priority:N,is_active:w,expires_at:k||null};a.mutate(A,{onSuccess:()=>m(!1)})}};return s?e.jsxs("div",{className:"space-y-4",children:[e.jsx(Y,{className:"h-10 w-48"}),e.jsx(Y,{className:"h-64 w-full"})]}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(Vn,{className:"h-5 w-5"})}),e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:"Announcements"})]}),e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:e.jsxs(g,{onClick:_,children:[e.jsx(Rt,{className:"mr-2 h-4 w-4"}),"Create announcement"]})})]}),!t||t.length===0?e.jsx(L,{className:"min-w-0 overflow-hidden",children:e.jsxs($,{className:"flex flex-col items-center justify-center py-12",children:[e.jsx(Vn,{className:"mb-4 h-12 w-12 text-muted-foreground"}),e.jsx("p",{className:"text-muted-foreground",children:"No announcements yet. Create one to share news with members."})]})}):e.jsx("div",{className:"space-y-3",children:t.map(P=>e.jsx(L,{className:"min-w-0 overflow-hidden",children:e.jsx($,{className:"p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"min-w-0 flex-1 space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"truncate font-semibold",children:P.title}),P.is_active?e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full bg-emerald-100 px-2.5 py-0.5 text-[11px] font-medium text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400",children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-emerald-500","aria-hidden":"true"}),"Active"]}):e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full bg-muted px-2.5 py-0.5 text-[11px] font-medium text-muted-foreground",children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-muted-foreground
4/60","aria-hidden":"true"}),"Inactive"]}),P.priority>0&&e.jsxs("span",{className:"inline-flex items-center gap-1.5 whitespace-nowrap",children:[e.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-amber-500"}),e.jsxs("span",{className:"text-xs font-medium",children:["Priority: ",P.priority]})]})]}),e.jsxs("div",{className:"flex items-center gap-4 text-sm text-muted-foreground",children:[P.content&&e.jsxs("span",{className:"max-w-md truncate",children:[P.content.slice(0,100),P.content.length>100?"â¦":""]}),e.jsxs("span",{children:["Created ",Be(pt(P.created_at),"MMM d, yyyy")]}),P.expires_at&&e.jsxs("span",{children:["Expires ",Be(pt(P.expires_at),"MMM d, yyyy")]})]})]}),e.jsxs("div",{className:"ml-4 flex items-center gap-2",children:[e.jsx(ss,{checked:P.is_active,onCheckedChange:()=>i.mutate(P.id)}),e.jsx(g,{variant:"outline",size:"sm","aria-label":"Edit announcement",onClick:()=>y(P),children:e.jsx(Hs,{className:"h-4 w-4"})}),e.jsx(g,{variant:"ghost",size:"sm","aria-label":"Delete announcement",onClick:()=>h(P.id),children:e.jsx(Ft,{className:"h-4 w-4 text-destructive"})})]})]})})},P.id))}),e.jsx(Fe,{open:l,onOpenChange:m,children:e.jsxs(Te,{className:"max-w-lg",children:[e.jsx(Ae,{children:e.jsx(Ee,{children:c?"Edit announcement":"Create announcement"})}),e.jsxs("form",{onSubmit:C,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"a-title",children:"Title"}),e.jsx(O,{id:"a-title",value:p,onChange:P=>x(P.target.value),placeholder:"e.g. Committee opening - apply by March 1",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"a-content",children:"Content"}),e.jsx(It,{id:"a-content",value:f,onChange:P=>b(P.target.value),placeholder:"Announcement detailsâ¦",rows:4}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"URLs starting with https:// are automatically linked in the portal. For custom link text, use [Link text](https://example.com)."})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"a-priority",children:"Priority (0 = normal)"}),e.jsx(O,{id:"a-priority",type:"number",min:0,max:100,value:N,onChange:P=>j(Number(P.target.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"a-expires",children:"Expires at"}),e.jsx(O,{id:"a-expires",type:"datetime-local",value:k,onChange:P=>S(P.target.value)})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ss,{checked:w,onCheckedChange:v}),e.jsx(T,{children:"Active"})]}),e.jsxs(Ge,{children:[e.jsx(g,{type:"button",variant:"outline",onClick:()=>m(!1),children:"Cancel"}),e.jsx(g,{type:"submit",disabled:a.isPending||n.isPending,children:c?"Save changes":"Create"})]})]})]})}),e.jsx(Fe,{open:!!u,onOpenChange:()=>h(null),children:e.jsxs(Te,{children:[e.jsx(Ae,{children:e.jsx(Ee,{children:"Delete announcement?"})}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"This will permanently delete this announcement. This action cannot be undone."}),e.jsxs(Ge,{children:[e.jsx(g,{variant:"outline",onClick:()=>h(null),children:"Cancel"}),e.jsx(g,{variant:"destructive",disabled:r.isPending,onClick:()=>{u&&(r.mutate(u),h(null))},children:r.isPending?"Deletingâ¦":"Delete"})]})]})})]})}function R5({status:t}){return t==="active"?e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full bg-emerald-100 px-2.5 py-0.5 text-[11px] font-medium text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400",children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-emerald-500","aria-hidden":"true"}),t]}):e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full bg-muted px-2.5 py-0.5 text-[11px] font-medium text-muted-foreground",children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-muted-foreground/60","aria-hidden":"true"}),t]})}function vu({status:t}){return t==="open"?e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full bg-emerald-100 px-2.5 py-0.5 text-[11px] font-medium text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400",children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-emerald-500","aria-hidden":"true"}),t]}):e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full bg-muted px-2.5 py-0.5 text-[11px] font-medium text-muted-foreground",children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-muted-foreground
4/60","aria-hidden":"true"}),t]})}function M5({status:t}){const s={pending:{pill:"bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400",dot:"bg-amber-500"},accepted:{pill:"bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400",dot:"bg-emerald-500"},rejected:{pill:"bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400",dot:"bg-red-500"},withdrawn:{pill:"bg-muted text-muted-foreground",dot:"bg-muted-foreground/60"}}[t]??{pill:"bg-muted text-muted-foreground",dot:"bg-muted-foreground/60"};return e.jsxs("span",{className:`inline-flex items-center gap-1.5 rounded-full px-2.5 py-0.5 text-[11px] font-medium ${s.pill}`,children:[e.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${s.dot}`,"aria-hidden":"true"}),t]})}const Wo={chair:"Chair",vice_chair:"Vice Chair",secretary:"Secretary",treasurer:"Treasurer",member:"Member"};function D5(){const{enabled:t,loaded:s}=xn("committees"),{data:a,isLoading:n}=N_();if(s&&!t)return e.jsx(_t,{to:"/",replace:!0});const r=__(),i=S_(),l=C_(),m=P_(),c=A_(),d=E_(),{selectedSocietyId:u}=V(),{data:h}=F_(),p=R_(),x=M_(),f=D_(),b=$_(),[N,j]=o.useState(!1),[w,v]=o.useState(null),[k,S]=o.useState(""),[_,y]=o.useState(""),[C,P]=o.useState(""),[A,E]=o.useState(!0),[Q,U]=o.useState(""),[D,K]=o.useState(""),[xe,z]=o.useState(""),[ae,ue]=o.useState(),{data:_e,isLoading:ee}=k_(ae),[se,le]=o.useState("members"),[oe,Pe]=o.useState(null),[M,I]=o.use
4State(!1),[R,X]=o.useState(""),[Se,ce]=o.useState([]),[ke,ve]=o.useState(!1),[Ne,Qe]=o.useState(null),[Oe,Ce]=o.useState("member"),[ze,Ze]=o.useState(null),[Re,de]=o.useState(!1),[ge,mt]=o.useState(""),[ye,Ke]=o.useState(""),[ut,De]=o.useState("member"),[he,Xe]=o.useState(),{data:rt,isLoading:yt}=L_(he),[dt,jt]=o.useState(null),[Ot,be]=o.useState("accepted"),[lt,ht]=o.useState(""),[zt,Tt]=o.useState(null),Jt=()=>{v(null),S(""),y(""),P(""),U(""),K(""),z(""),E(!0),j(!0)},is=pe=>{v(pe),S(pe.name),y(pe.description||""),P(pe.chat_link||""),U(pe.next_meeting_date||""),K(pe.next_meeting_time||""),z(pe.meeting_link||""),E(pe.status==="active"),j(!0)},Va=async()=>{try{w?await i.mutateAsync({id:w.id,data:{name:k,description:_||null,chat_link:C||null,next_meeting_date:Q||null,next_meeting_time:D||null,meeting_link:xe||null,status:A?"active":"inactive"}}):await r.mutateAsync({name:k,description:_||null,chat_link:C||null,next_meeting_date:Q||null,next_meeting_time:D||null,meeting_link:xe||null,status:A?"active":"inactive"}),j(!1)}catch{}},nt=async()=>{if(oe)try{await l.mutateAsync(oe),ae===oe&&ue(void 0),Pe(null)}catch{}};o.useEffect(()=>{if(!R.trim()||!u){ce([]);return}const pe=setTimeout(async()=>{ve(!0);try{const Z=await Gt.list({query:R,society_id:u,size:10});ce(Z.items)}catch{ce([])}ve(!1)},300);return()=>clearTimeout(pe)},[R,u]);const Vt=()=>{X(""),ce([]),Qe(null),Ce("member"),I(!0)},et=async()=>{if(!(!Ne||!ae))try{await m.mutateAsync({committeeId:ae,data:{member_id:Ne,role:Oe}}),I(!1)}catch{}},bt=async(pe,Z)=>{if(ae)try{await c.mutateAsync({committeeId:ae,cmId:pe.id,data:{role:Z}})}catch{}},qt=async()=>{if(!(!ze||!ae))try{await d.mutateAsync({committeeId:ae,cmId:ze.id}),Ze(null)}catch{}},xs=()=>{mt(""),Ke(""),De("member"),de(!0)},ns=async()=>{if(!(!ae||!ge.trim()))try{await p.mutateAsync({committeeId:ae,data:{title:ge,description:ye||null,role:ut}}),de(!1)}catch{}},ua=async pe=>{try{await x.mutateAsync({openingId:pe,data:{status:"closed"}})}catch{}},aa=async()=>{if(zt)try{await f.mutateAsync(zt),he===zt&&Xe(void 0),Tt(null)}catch{}},_s=async()=>{if(!(!dt||!he))try{await b.mutateAsync({openingId:he,appId:dt.id,data:{status:Ot,admin_notes:lt||null}}),jt(null)}catch{}},Ls=h?.filter(pe=>pe.committee_id===ae)||[];return n?e.jsxs("div",{className:"space-y-4 p-4 md:p-8",children:[e.jsx(Y,{className:"h-10 w-48"}),e.jsx("div",{className:"grid gap-4 md:grid-cols-2",children:[1,2,3,4].map(pe=>e.jsx(Y,{className:"h-32"},pe))})]}):e.jsxs("div",{className:"p-4 md:p-8",children:[e.jsxs("div",{className:"mb-6 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(Kn,{className:"h-5 w-5"})}),e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:"Committees"})]}),e.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"Manage committees, members, and open positions"})]}),e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:e.jsxs(g,{onClick:Jt,children:[e.jsx(Rt,{className:"mr-2 h-4 w-4"}),"New committee"]})})]}),e.jsxs("div",{className:"grid gap-6 lg:grid-cols-5",children:[e.jsxs("div",{className:`space-y-3 ${ae?"lg:col-span-2":"lg:col-span-5"}`,children:[!a||a.length===0?e.jsx(L,{className:"min-w-0 overflow-hidden",children:e.jsxs($,{className:"p-8 text-center",children:[e.jsx(Kn,{className:"mx-auto mb-3 h-10 w-10 text-muted-foreground"}),e.jsx("p",{className:"text-muted-foreground",children:"No committees yet. Create your first one!"})]})}):a.map(pe=>e.jsx(L,{className:`min-w-0 cursor-pointer overflow-hidden transition-colors hover:bg-brand-navy/[0.04] dark:hover:bg-brand-navy/10 ${ae===pe.id?"ring-2 ring-primary":""}`,onClick:()=>{ue(pe.id),le("members"),Xe(void 0)},children:e.jsx($,{className:"p-4",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("h3",{className:"truncate font-semibold",children:pe.name}),pe.description&&e.jsx("p",{className:"mt-0.5 line-clamp-1 text-sm text-muted-foreground",children:pe.description}),e.jsxs("div",{className:"mt-2 flex items-center gap-3 text-xs text-muted-foreground",children:[e.jsxs("span",{children:[pe.member_count," member",pe.member_count!==1?"s":""]}),e.jsxs("span",{children:["Created ",Be(pt(pe.created_at),"MMM d, yyyy")]})]})]}),e.jsxs("div",{className:"ml-2 flex items-center gap-2",children:[e.jsx(R5,{status:pe.status}),e.jsx(g,{variant:"ghost",size:"icon",className:"h-8 w-8","aria-label":"Edit committee",onClick:Z=>{Z.stopPropagation(),is(pe)},children:e.jsx(Hs,{className:"h-4 w-4"})}),e.jsx(g,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive","aria-label":"Delete committee",onClick:Z=>{Z.stopPropagation(),Pe(pe.id)},children:e.jsx(Ft,{className:"h-4 w-4"})})]})]})})},pe.id)),!ae&&h&&h.length>0&&e.jsxs(L,{className:"mt-6 min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy
4/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(Gl,{className:"h-4 w-4"})}),"All openings"]})}),e.jsx($,{children:e.jsx("div",{className:"space-y-2",children:h.map(pe=>e.jsxs("div",{className:"flex items-center justify-between rounded-md border p-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium",children:pe.title}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[pe.committee_name," · ",Wo[pe.role]||pe.role]})]}),e.jsxs("div",{className:"ml-2 flex items-center gap-2",children:[pe.application_count>0&&e.jsxs(Ts,{variant:"default",className:"text-xs",children:[pe.application_count," app",pe.application_count!==1?"s":""]}),e.jsx(vu,{status:pe.status})]})]},pe.id))})})]})]}),ae&&e.jsx("div",{className:"lg:col-span-3",children:e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsxs(ne,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ie,{className:"text-lg",children:ee?e.jsx(Y,{className:"h-6 w-32"}):_e?.name}),_e?.description&&e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:_e.description})]}),e.jsx(g,{variant:"ghost",size:"icon",className:"h-8 w-8","aria-label":"Close detail panel",onClick:()=>{ue(void 0),Xe(void 0)},children:e.jsx(ms,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex gap-1 border-b px-6",children:[e.jsx("button",{className:`border-b-2 px-3 py-2 text-sm font-medium transition-colors ${se==="members"?"border-primary text-primary":"border-transparent text-muted-foreground hover:text-foreground"}`,onClick:()=>{le("members"),Xe(void 0)},children:"Members"}),e.jsxs("button",{className:`border-b-2 px-3 py-2 text-sm font-medium transition-colors ${se==="openings"?"border-primary text-primary":"border-transparent text-muted-foreground hover:text-foreground"}`,onClick:()=>{le("openings"),Xe(void 0)},children:["Openings",Ls.filter(pe=>pe.status==="open").length>0&&e.jsx(Ts,{variant:"default",className:"ml-1.5 px-1.5 text-[10px]",children:Ls.filter(pe=>pe.status==="open").length})]})]}),e.jsxs($,{className:"pt-4",children:[se==="members"&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mb-3 flex justify-end",children:e.jsxs(g,{size:"sm",onClick:Vt,children:[e.jsx(fa,{className:"mr-1.5 h-4 w-4"}),"Add member"]})}),ee?e.jsx("div",{className:"space-y-2",children:[1,2,3].map(pe=>e.jsx(Y,{className:"h-12"},pe))}):!_e?.members||_e.members.length===0?e.jsx("p",{className:"py-6 text-center text-sm text-muted-foreground",children:"No members yet. Add members to this committee."}):e.jsxs("div",{className:"space-y-2",children:[_e.members.filter(pe=>!pe.end_date).sort((pe,Z)=>{const We=["chair","vice_chair","secretary","treasurer","member"];return We.indexOf(pe.role)-We.indexOf(Z.role)}).map(pe=>e.jsxs("div",{className:"flex items-center justify-between rounded-md border p-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:pe.member_name}),e.jsx("p",{className:"text-xs text-muted-foreground",children:pe.member_email})]}),e.jsxs("div",{className:"ml-2 flex items-center gap-2",children:[e.jsxs(qe,{value:pe.role,onValueChange:Z=>bt(pe,Z),children:[e.jsx(Le,{className:"h-8 w-[130px] text-xs",children:e.jsx(Ie,{})}),e.jsxs($e,{children:[e.jsx(q,{value:"chair",children:"Chair"}),e.jsx(q,{value:"vice_chair",children:"Vice Chair"}),e.jsx(q,{value:"secretary",children:"Secretary"}),e.jsx(q,{value:"treasurer",children:"Treasurer"}),e.jsx(q,{value:"member",children:"Member"})]})]}),e.jsx(g,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive","aria-label":"Remove member",onClick:()=>Ze(pe),children:e.jsx(Ft,{className:"h-3.5 w-3.5"})})]})]},pe.id)),_e.members.filter(pe=>pe.end_date).length>0&&e.jsxs("div",{className:"mt-3 border-t pt-3",children:[e.jsx("p",{className:"mb-2 text-xs text-muted-foreground",children:"Former Members"}),_e.members.filter(pe=>pe.end_date).map(pe=>e.jsx("div",{className:"flex items-center justify-between rounded-md border border-dashed p-2 opacity-60",children:e.jsxs("div",{children:[e.jsx("p",{className:"text-sm",children:pe.member_name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Wo[pe.role]," â ended ",pe.end_date]})]})},pe.id))]})]})]}),se==="openings"&&!he&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mb-3 flex justify-end",children:e.jsxs(g,{size:"sm",onClick:xs,children:[e.jsx(Rt,{className:"mr-1.5 h-4 w-4"}),"New opening"]})}),Ls.length===0?e.jsx("p",{className:"py-6 text-center text-sm text-muted-foreground",children:"No openings yet. Create one to advertise a position."}):e.jsx("div",{className:"space-y-2",children:Ls.map(pe=>e.jsxs("div",{className:"flex cursor-pointer items-center justify-between rounded-md border p-3 transition-colors hover:bg-accent/50",onClick:()=>Xe(pe.id),children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium",children:pe.title}),e.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5 whitespace-nowrap",children:[e.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-muted-foreground
4/60"}),e.jsx("span",{className:"text-xs font-medium",children:Wo[pe.role]||pe.role})]}),e.jsx(vu,{status:pe.status}),pe.application_count>0&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:[pe.application_count," application",pe.application_count!==1?"s":""]})]})]}),e.jsxs("div",{className:"ml-2 flex items-center gap-1",children:[pe.status==="open"&&e.jsx(g,{variant:"ghost",size:"icon",className:"h-8 w-8",title:"Close opening","aria-label":"Close opening",onClick:Z=>{Z.stopPropagation(),ua(pe.id)},children:e.jsx(wp,{className:"h-3.5 w-3.5"})}),e.jsx(g,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive",title:"Delete opening","aria-label":"Delete opening",onClick:Z=>{Z.stopPropagation(),Tt(pe.id)},children:e.jsx(Ft,{className:"h-3.5 w-3.5"})})]})]},pe.id))})]}),se==="openings"&&he&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"mb-4 flex items-center gap-2",children:[e.jsxs(g,{variant:"ghost",size:"sm",onClick:()=>Xe(void 0),children:[e.jsx(Gs,{className:"mr-1 h-4 w-4"}),"Back"]}),e.jsx("span",{className:"text-sm font-medium",children:Ls.find(pe=>pe.id===he)?.title||"Applications"})]}),yt?e.jsx("div",{className:"space-y-2",children:[1,2,3].map(pe=>e.jsx(Y,{className:"h-12"},pe))}):!rt||rt.length===0?e.jsx("p",{className:"py-6 text-center text-sm text-muted-foreground",children:"No applications yet."}):e.jsx("div",{className:"space-y-2",children:rt.map(pe=>e.jsx("div",{className:"rounded-md border p-3",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium",children:pe.member_name}),e.jsx("p",{className:"text-xs text-muted-foreground",children:pe.member_email}),pe.message&&e.jsxs("p",{className:"mt-2 text-sm italic text-muted-foreground",children:['"',pe.message,'"']}),e.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:["Applied ",Be(pt(pe.applied_at),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"ml-2 flex items-center gap-2",children:[e.jsx(M5,{status:pe.status}),pe.status==="pending"&&e.jsxs(e.Fragment,{children:[e.jsxs(g,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:()=>{jt(pe),be("accepted"),ht("")},children:[e.jsx(Xt,{className:"mr-1 h-3 w-3"}),"Accept"]}),e.jsxs(g,{size:"sm",variant:"outline",className:"h-7 text-xs text-destructive",onClick:()=>{jt(pe),be("rejected"),ht("")},children:[e.jsx(Ca,{className:"mr-1 h-3 w-3"}),"Reject"]})]})]})]})},pe.id))})]})]})]})})]}),e.jsx(Fe,{open:N,onOpenChange:j,children:e.jsxs(Te,{className:"sm:max-w-md",children:[e.jsx(Ae,{children:e.jsx(Ee,{children:w?"Edit committee":"New committee"})}),e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{children:[e.jsx(T,{children:"Name"}),e.jsx(O,{value:k,onChange:pe=>S(pe.target.value),placeholder:"e.g. Finance Committee"})]}),e.jsxs("div",{children:[e.jsx(T,{children:"Description"}),e.jsx(It,{value:_,onChange:pe=>y(pe.target.value),placeholder:"Optional descriptionâ¦",rows:3})]}),e.jsxs("div",{children:[e.jsx(T,{children:"Group chat link"}),e.jsx(O,{value:C,onChange:pe=>P(pe.target.value),placeholder:"https://chat.whatsapp.com/â¦"}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"WhatsApp, Slack, Teams, or any group chat invite link. Shown to committee members in the portal."})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(T,{children:"Next meeting date"}),e.jsx(O,{type:"date",value:Q,onChange:pe=>U(pe.target.value)})]}),e.jsxs("div",{children:[e.jsx(T,{children:"Meeting time"}),e.jsx(O,{type:"time",value:D,onChange:pe=>K(pe.target.value)})]})]}),e.jsxs("div",{children:[e.jsx(T,{children:"Meeting link"}),e.jsx(O,{value:xe,onChange:pe=>z(pe.target.value),placeholder:"https://zoom.us/j/â¦"})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(T,{children:"Active"}),e.jsx(ss,{checked:A,onCheckedChange:E})]})]}),e.jsxs(Ge,{children:[e.jsx(g,{variant:"outline",onClick:()=>j(!1),children:"Cancel"}),e.jsx(g,{onClick:Va,disabled:!k.trim()||r.isPending||i.isPending,children:r.isPending||i.isPending?"Savingâ¦":"Save"})]})]})}),e.jsx(Fe,{open:!!oe,onOpenChange:()=>Pe(null),children:e.jsxs(Te,{className:"sm:max-w-sm",children:[e.jsx(Ae,{children:e.jsx(Ee,{children:"Delete committee?"})}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"This will remove the committee. Member records will be preserved."}),e.jsxs(Ge,{children:[e.jsx(g,{variant:"outline",onClick:()=>Pe(null),children:"Cancel"}),e.jsx(g,{variant:"destructive",onClick:nt,disabled:l.isPending,children:l.isPending?"Deletingâ¦":"Delete"})]})]})}),e.jsx(Fe,{open:M,onOpenChange:I,children:e.jsxs(Te,{className:"sm:max-w-md",children:[e.jsx(Ae,{children:e.jsx(Ee,{children:"Add member to committee"})}),e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{children:[e.jsx(T,{children:"Search members"}),e.jsx(O,{value:R,onChange:pe=>{X(pe.target.value),Qe(null)},placeholder:"Type to search by name or emailâ¦"})]}),ke&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Searchingâ¦"}),Se.length>0&&e.jsx("div",{className:"max-h-48 space-y-1 overflow-y-auto rounded-md border p-1",children:Se.map(pe=>e.jsxs("button",{className:`w-full rounded px-3 py-2 text-left text-sm transition-colors ${Ne===pe.id?"bg-primary text-primary-foreground":"hover:bg-accent"}`,onClick:()=>Qe(pe.id),children:[e.jsxs("span",{className:"font-medium",children:[pe.first_name," ",pe.last_name]}),e.jsx("span",{className:"ml-2 text-xs opacity-75",children:pe.email})]},pe.id))}),R&&!ke&&Se.length===0&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"No members found"}),e.jsxs("div",{children:[e.jsx(T,{children:"Role"}),e.jsxs(qe,{value:Oe,onValueChange:Ce,children:[e.jsx(Le,{children:e.jsx(Ie,{})}),e.jsxs($e,{children:[e.jsx(q,{value:"chair",children:"Chair"}),e.jsx(q,{value:"vice_chair",children:"Vice Chair"}),e.jsx(q,{value:"secretary",children:"Secretary"}),e.jsx(q,{value:"treasurer",children:"Treasurer"}),e.jsx(q,{value:"member",children:"Member"})]})]})]})]}),e.jsxs(Ge,{children:[e.jsx(g,{variant:"outline",onClick:()=>I(!1),children:"Cancel"}),e.jsx(g,{onClick:et,disabled:!Ne||m.isPending,children:m.isPending?"Addingâ¦":"Add member"})]})]})}),e.jsx(Fe,{open:!!ze,onOpenChange:()=>Ze(null),children:e.jsxs(Te,{className:"sm:max-w-sm",children:[e.jsx(Ae,{children:e.jsx(Ee,{children:"Remove member?"})}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Remove ",e.jsx("strong",{children:ze?.member_name})," from this committee?"]}),e.jsxs(Ge,{children:[e.jsx(g,{variant:"outline",onClick:()=>Ze(null),children:"Cancel"}),e.jsx(g,{variant:"destructive",onClick:qt,disabled:d.isPending,children:d.isPending?"Removingâ¦":"Remove"})]})]})}),e.jsx(Fe,{open:Re,onOpenChange:de,children:e.jsxs(Te,{className:"sm:max-w-md",children:[e.jsx(Ae,{children:e.jsx(Ee,{children:"New opening"})}),e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{children:[e.jsx(T,{children:"Title"}),e.jsx(O,{value:ge,onChange:pe=>mt(pe.target.value),placeholder:"e.g. Treasurer Position"})]}),e.jsxs("div",{children:[e.jsx(T,{children:"Description"}),e.jsx(It,{value:ye,onChange:pe=>Ke(pe.target.value),placeholder:"What does this role involve?",rows:3})]}),e.jsxs("div",{children:[e.jsx(T,{children:"Role"}),e.jsxs(qe,{value:ut,onValueChange:De,children:[e.jsx(Le,{children:e.jsx(Ie,{})}),e.jsxs($e,{children:[e.jsx(q,{value:"chair",children:"Chair"}),e.jsx(q,{value:"vice_chair",children:"Vice Chair"}),e.jsx(q,{value:"secretary",children:"Secretary"}),e.jsx(q,{value:"treasurer",children:"Treasurer"}),e.jsx(q,{value:"member",children:"Member"})]})]})]})]}),e.jsxs(Ge,{children:[e.jsx(g,{variant:"outline",onClick:()=>de(!1),children:"Cancel"}),e.jsx(g,{onClick:ns,disabled:!ge.trim()||p.isPending,children:p.isPending?"Creatingâ¦":"Create opening"})]})]})}),e.jsx(Fe,{open:!!zt,onOpenChange:()=>Tt(null),children:e.jsxs(Te,{className:"sm:max-w-sm",children:[e.jsx(Ae,{children:e.jsx(Ee,{children:"Delete opening?"})}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"This will remove the opening and its applications from view."}),e.jsxs(Ge,{children:[e.jsx(g,{variant:"outline",onClick:()=>Tt(null),children:"Cancel"}),e.jsx(g,{variant:"destructive",onClick:aa,disabled:f.isPending,children:f.isPending?"Deletingâ¦":"Delete"})]})]})}),e.jsx(Fe,{open:!!dt,onOpenChange:()=>jt(null),children:e.jsxs(Te,{className:"sm:max-w-md",children:[e.jsx(Ae,{children:e.jsxs(Ee,{children:[Ot==="accepted"?"Accept":"Reject"," application"]})}),e.jsxs("div",{className:"space-y-3 py-2",children:[e.jsx("p",{className:"text-sm",children:Ot==="accepted"?e.jsxs(e.Fragment,{children:["Accept ",e.jsx("strong",{children:dt?.member_name}),"? They will be added to the committee automatically."]}):e.jsxs(e.Fragment,{children:["Reject ",e.jsx("strong",{children:dt?.member_name}),"'s application?"]})}),e.jsxs("div",{children:[e.jsx(T,{children:"Admin notes (optional)"}),e.jsx(It,{value:lt,onChange:pe=>ht(pe.target.value),placeholder:"Internal notesâ¦",rows:2})]})]}),e.jsxs(Ge,{children:[e.jsx(g,{variant:"outline",onClick:()=>jt(null),children:"Cancel"}),e.jsx(g,{variant:Ot==="accepted"?"default":"destructive",onClick:_s,disabled:b.isPending,children:b.isPending?"Processingâ¦":Ot==="accepted"?"Accept":"Reject"})]})]})})]})}const L5={needs_response:{label:"Needs response",pill:"bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400",dot:"bg-red-500"}
4,under_review:{label:"Under review",pill:"bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400",dot:"bg-amber-500"},won:{label:"Won",pill:"bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400",dot:"bg-emerald-500"},lost:{label:"Lost",pill:"bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400",dot:"bg-red-500"}},$5={bank_cannot_process:"Bank cannot process",credit_not_processed:"Credit not processed",customer_initiated:"Customer initiated",debit_not_authorized:"Debit not authorized",duplicate:"Duplicate",fraudulent:"Fraudulent",general:"General",incorrect_account_details:"Incorrect account details",insufficient_funds:"Insufficient funds",product_not_received:"Product not received",product_unacceptable:"Product unacceptable",subscription_canceled:"Subscription canceled",unrecognized:"Unrecognized"};function wu(t){return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD"}).format(Number(t))}function Nu(t){return t?Ct(t).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):"â"}function q5(){const[t,s]=o.useState(1),{data:a,isLoading:n}=zN(t),{data:r}=Dg();return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-amber-100 text-amber-600 dark:bg-amber-900/30 dark:text-amber-400",children:e.jsx(Bt,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:"Disputes"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Chargebacks and payment disputes from Stripe. Respond to disputes in your Stripe Dashboard."})]})]}),r&&r.open_count>0&&e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-2",children:e.jsxs(ie,{className:"flex items-center gap-2.5",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(Dt,{className:"h-4 w-4"})}),"Open disputes"]})}),e.jsx($,{children:e.jsx("div",{className:"text-2xl font-semibold tracking-tight text-red-600 dark:text-red-400",children:r.open_count})})]}),e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-2",children:e.jsxs(ie,{className:"flex items-center gap-2.5",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(Ua,{className:"h-4 w-4"})}),"Total at risk"]})}),e.jsx($,{children:e.jsx("div",{className:"text-2xl font-semibold tracking-tight text-red-600 dark:text-red-400",children:wu(r.total_disputed)})})]})]}),e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx($,{className:"p-0",children:e.jsxs(Pt,{children:[e.jsx(At,{className:"bg-muted/30",children:e.jsxs(Ue,{className:"hover:bg-transparent",children:[e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Date"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Member"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Amount"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Reason"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Status"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Evidence due"}),e.jsx(H,{className:"h-10 w-[80px]"})]})}),e.jsx(Et,{children:n?e.jsx(Ue,{children:e.jsx(G,{colSpan:7,className:"py-8 text-center text-muted-foreground",children:"Loading disputesâ¦"})}):a?.items.length?a.items.map(i=>{const l=L5[i.status]||{label:i.status,pill:"bg-muted text-muted-foreground",dot:"bg-muted-foreground
4/60"},m=i.status==="needs_response"&&i.evidence_due_by&&Ct(i.evidence_due_by)<new Date;return e.jsxs(Ue,{className:"hover:bg-brand-navy/[0.04] dark:hover:bg-brand-navy/10",children:[e.jsx(G,{className:"whitespace-nowrap",children:Nu(i.created_at)}),e.jsx(G,{children:i.member_name?e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:i.member_name}),e.jsx("div",{className:"text-sm text-muted-foreground",children:i.member_email})]}):e.jsx("span",{className:"text-muted-foreground",children:"Unknown"})}),e.jsx(G,{className:"font-medium",children:wu(i.amount)}),e.jsx(G,{children:$5[i.reason||""]||i.reason||"â"}),e.jsx(G,{children:e.jsxs("span",{className:me("inline-flex items-center gap-1.5 rounded-full px-2.5 py-0.5 text-[11px] font-medium",l.pill),children:[e.jsx("span",{className:me("h-1.5 w-1.5 rounded-full",l.dot),"aria-hidden":"true"}),l.label]})}),e.jsxs(G,{className:m?"font-medium text-red-600 dark:text-red-400":void 0,children:[Nu(i.evidence_due_by),m&&" (overdue)"]}),e.jsx(G,{children:e.jsx(g,{variant:"ghost",size:"icon",asChild:!0,children:e.jsx("a",{href:`https://dashboard.stripe.com/disputes/${i.stripe_dispute_id}`,target:"_blank",rel:"noopener noreferrer",title:"View in Stripe",children:e.jsx(Rs,{className:"h-4 w-4"})})})})]},i.id)}):e.jsx(Ue,{children:e.jsx(G,{colSpan:7,className:"py-8 text-center text-muted-foreground",children:"No disputes found"})})})]})}),a&&a.pages>1&&e.jsxs("div",{className:"flex items-center justify-between border-t px-4 py-3",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Page ",a.page," of ",a.pages," (",a.total," total)"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(g,{variant:"outline",size:"sm",disabled:t<=1,onClick:()=>s(i=>i-1),children:"Previous"}),e.jsx(g,{variant:"outline",size:"sm",disabled:t>=a.pages,onClick:()=>s(i=>i+1),children:"Next"})]})]})]})]})}function I5({value:t,onChange:s,resultCount:a}){return e.jsxs("div",{className:"relative",children:[e.jsx(ya,{className:"absolute left-4 top-1/2 h-5 w-5 -translate-y-1/2 text-muted-foreground"}),e.jsx(O,{type:"text",placeholder:"Search help articlesâ¦",value:t,onChange:n=>s(n.target.value),className:"h-12 pl-12 text-base"}),t&&a!==void 0&&e.jsxs("span",{className:"absolute right-4 top-1/2 -translate-y-1/2 text-sm text-muted-foreground",children:[a," ",a===1?"result":"results"]})]})}const Bn={"getting-started":{label:"Getting Started",icon:"Rocket",description:"First-time setup and dashboard overview"},members:{label:"Members",icon:"Users",description:"Adding, managing, and organizing members"},membership:{label:"Membership",icon:"IdCard",description:"Renewals, lapsed recovery, account merging, and member-status lifecycle"},payments:{label:"Payments",icon:"CreditCard",description:"Recording payments and auto-renewal"},invoices:{label:"Invoices",icon:"FileText",description:"Creating and sending invoice batches"},email:{label:"Email",icon:"Mail",description:"Templates and automated sequences"},commerce:{label:"Commerce",icon:"ShoppingBag",description:"Events, products, and donations"},engagement:{label:"Engagement",icon:"Megaphone",description:"Polls, announcements, and committees"},settings:{label:"Settings",icon:"Settings",description:"Society configuration, users, reports, and audit"},integrations:{label:"Integrations",icon:"Plug",description:"Stripe, email providers, member sync, event app, video library, WordPress, custom domains"}},Dl=[{id:"1",slug:"dashboard-overview",title:"Dashboard Overview",category:"getting-started",summary:"Understanding your admin dashboard and key metrics at a glance.",keywords:["dashboard","overview","stats","metrics","home","start"],order:1,tourId:"dashboard",content:`Your dashboard gives you a quick overview of your society's membership health and recent activity. 5 6## Stats Cards 7 8The four cards at the top show key metrics: 9 10- **Current roster** â Everyone on your roster today: active, pending, grace, lapsed, and expired members. Excludes cancelled, suspended, rejected, and archived records, and event-only/non-member accounts. 11- **Revenue This Month** â Total payments received in the current month 12- **Pending Approvals** â Applications awaiting your review 13- **Expiring Soon** â Members whose memberships expire in the next 30 days 14 15## Recent Activity 16 17Below the stats, you'll see recent activity including: 18 19- New member signups 20- Payment receipts 21- Status changes 22- Email notifications sent 23 24## Quick Actions 25
26Use the quick action buttons to jump to common tasks: 27 28- Add a new member 29- Create an invoice batch 30- Send a broadcast email 31- View pending applications 32 33## Charts 34 35The dashboard charts show: 36 37- **Membership trends** â How your member count has changed over time 38- **Revenue breakdown** â Payment sources and amounts 39- **Member distribution** â Breakdown by membership type 40 41## Onboarding Checklist 42 43If you're new, the onboarding checklist guides you through essential setup steps. Complete each item to ensure your society is fully configured. 44 45## Dispute Alert 46 47If you have any open payment disputes (chargebacks), a red alert banner appears below the demo data card showing the count and total dollar amount at risk. Click **View Disputes** to go to the Disputes page. 48 49## Demo Data 50 51To see the dashboard with realistic data, go to **Settings** and click **Load Demo Data**. This creates ~200 sample members with payments, events, and other records. When demo data is loaded, an amber banner appears at the top of the dashboard with a **Clear Demo Data** button to remove everything before going live. Demo data can only be loaded before the society has real member data.`},{id:"2",slug:"first-time-setup-guide",title:"First-Time Setup Guide",category:"getting-started",summary:"Step-by-step guide to configure your society for the first time.",keywords:["setup","configure","new","first","onboarding","stripe","branding","favicon"],order:2,content:`Get your society up and running with this complete setup guide. 52 53## 1. Connect Stripe 54 55First, connect your Stripe account to accept payments: 56 571. Go to **Settings** in the sidebar 582. Find the **Stripe Configuration** section 593. Enter your Publishable Key and Secret Key from the Stripe Dashboard 604. Click **Save Keys**, then **Test Connection** 615. Once connected, you'll see the Stripe account name 62 63Without Stripe, you can still record manual payments but won't be able to accept online payments. 64 65## 2. Create Membership Types 66 67Define the membership options for your society: 68 691. Go to **Membership types** in the sidebar (under the Members group) 702. Click **Add Membership Type** 713. Set the name, price, and duration 724. Configure renewal settings 735. Save and repeat for additional types 74 75Common examples: Annual, Student, Lifetime, Corporate. 76 77## 3. Configure Email Templates 78 79Customize the emails your members receive: 80 811. Go to **Emails** in the sidebar (under the Engagement group) 822. Review each template type 833. Edit the subject and body as needed 844. Use merge fields to personalize (e.g., {{member.firstName}}) 855. Send test emails to yourself 86 87## 4. Set Up Renewal Sequence 88 89Configure automatic renewal reminders: 90 911. Go to **Renewals** in the sidebar (under the Engagement group) 922. Review the default 9-touchpoint sequence 933. Adjust timing and content as needed 944. Enable or disable individual touchpoints 95 96## 5. Configure Email Provider 97 98Set up your email sending credentials so the system can send emails: 99 1001. Korevera sets up your email sender (the provider and the From address) on your society's platform settings, under **Integrations** â **Email sender**. Contact support to set or change it. 1012. In your workspace, **Emails** â **Sending** shows the current sender. 1023. Use **Send test email** there to check that mail is delivered 1034. Once verified, the system can send all automated emails 104 105Without an email provider configured, no emails (welcome, renewal, invoices, password reset) will be sent. 106 107## 6. Upload Logo, Favicon & Branding 108 109Add your society's branding: 110 1111. Go to **Settings** â **Branding** 1122. Upload your logo (recommended: 200x200px PNG) 1133. Upload a favicon / browser icon (square, at least 192x192px PNG) â this replaces the default browser tab icon and mobile homescreen icon with your society's brand 1144. Set your primary color 1155. Preview how it appears in emails and the member portal 116 117## 7. Add Your First Member 118 119Finally, add a test member to verify everything works: 120 1211. Go to **Members** â **Add Member** 1222. Fill in the member details 1233. Select a membership type 1244. Choose whether to send a welcome email 1255. Save the member 126 127You're now ready to start managing your society!`},{id:"3",slug:"adding-members-manually",title:"Adding Members Manually",category:"members",summary:"How to add new members through the admin panel.",keywords:["add","create","new member","manual","form","register"],order:1,content:`Add members directly through the admin panel when they sign up offline or need to be imported. 128 129## Accessing the Add Member Form 130 1311. Go to **Members** in the sidebar 1322. Click the **Add Member** button in the top right 1333. The new member form will open 134 135## Required Fields 136 137Every member needs: 138 139- **Email** â Must be unique, used for login and communications 140- **First Name** and **Last Name** 141- **Membership Type** â Select from your configured types 142 143## Optional Fields 144 145You can also provide: 146 147- **Phone Number** â For contact purposes 148- **Address** â Full mailing address (city, state, county, postal code, country) 149- **County** â Auto-fills from postal code using a built-in ZIP-to-county lookup 150- **Company/Organization** â If applicable 151- **Custom Fields** â Any society-specific fields you've configured 152 153## Setting Initial Status 154 155Choose the member's starting status: 156 157- **Active** â Full member, ready to go 158- **Pending** â Requires approval before becoming active 159 160## Membership Dates 161 162- **Start Date** â When the membership begins (defaults to today) 163- **Expiry Date** â Calculated automatically based on membership type duration 164 165## Welcome Email 166 167Check the **Send welcome email** box to automatically notify the member. The welcome email includes: 168 169- Login credentials 170- Link to the member portal 171- Getting started information 172 173## Saving the Member 174 175Click **Save** to create the member. They'll appear in your member list immediately and can log in to the member portal if you sent the welcome email.`},{id:"4",slug:"understanding-member-statuses",title:"Understanding Member Statuses",category:"members",summary:"Learn what each member status means and how transitions work.",keywords:["status","active","pending","lapsed","grace","suspended","expired"],order:2,content:`Member statuses track where each person is in their membership lifecycle. 176 177## Status Types 178 179### PENDING 180Member has applied but hasn't been approved yet. They: 181- Cannot access member-only content 182- Are waiting for admin review 183- Will receive approval/rejection notification 184 185### ACTIVE 186Current, paid-up member with full access. They: 187- Can log in to the member portal 188- Receive member communications 189- Have access to all member benefits 190 191### GRACE
192Membership has expired but they're in the grace period. They: 193- Still have member access (configurable) 194- Receive renewal reminders 195- Can renew without penalty 196 197The grace period length is set by Korevera on your society's settings (the **Membership** tab); contact support to change it. 198 199### LAPSED 200Grace period has ended without renewal. They: 201- Lose member access 202- Continue receiving re-engagement emails 203- Can rejoin by paying 204- **Recover at event checkout:** When *Renewal at event checkout* is enabled in your society's Membership settings, LAPSED members registering for an event are prompted to renew dues during checkout. Opting in pays dues + event in one transaction and flips them back to ACTIVE. See [Renewal at Event Checkout](/help/paid-renewal-at-event-checkout). 205 206### EXPIRED 207Same access posture as LAPSED but the member has been inactive long enough to be considered fully expired. Behaves identically to LAPSED for the renewal-at-checkout prompt â same panel, same flow. 208 209### SUSPENDED 210Admin has manually suspended the member. They: 211- Cannot access member benefits 212- Don't receive automated emails 213- Remain suspended until admin changes status 214 215## Automatic Transitions 216 217The system automatically changes statuses based on: 218 219| Trigger | Status Change | 220|---------|--------------| 221| Expiry date passes | Active â Grace | 222| Grace period ends | Grace â Lapsed | 223| Payment received | Any â Active | 224| Admin approves | Pending â Active | 225 226## Manual Status Changes 227 228Admins can change status anytime: 2291. Open the member's profile 2302. Click the status badge 2313. Select the new status 2324. Confirm the change 233 234Some status changes (like Suspended) can only be done manually.`},{id:"5",slug:"processing-member-applications",title:"Processing Member Applications",category:"members",summary:"How to review, approve, or reject pending member applications.",ke
234ywords:["approve","reject","application","pending","review","approval"],order:3,content:`When members apply through your public signup form, they start as Pending and need your approval. 235 236## Finding Pending Members 237 238Several ways to find applications awaiting review: 239 2401. **Dashboard** â The "Pending Approvals" stat card shows the count; click to see the list 2412. **Members list** â Filter by Status â Pending 2423. **Notifications** â You'll receive email alerts for new applications (if enabled) 243 244## Reviewing an Application 245 246Click on a pending member to see their full application: 247 248- Contact information they provided 249- Answers to any custom questions 250- Membership type they selected 251- Application date and time 252 253## Approving a Member 254 255To approve: 256 2571. Open the member's profile 2582. Click **Approve** (or change status to Active) 2593. Confirm the action 260 261What happens next: 262- Status changes to Active 263- Member receives approval email with login details 264- Membership start date is set 265- They can now access the member portal 266 267## Rejecting a Member 268 269To reject: 270 2711. Open the member's profile 2722. Click **Reject** (or change status to Rejected) 2733. Optionally add a reason 2744. Confirm the action 275 276What happens: 277- Member receives rejection email (if configured) 278- Their record remains for your reference 279- They can apply again if appropriate 280 281## Bulk Processing 282 283For multiple applications: 284 2851. Go to Members list, filter by Pending 2862. Check the boxes for members to process 2873. Use bulk actions to Approve All or Reject All 288 289## Auto-Approval 290 291If you don't need to review applications, enable auto-approval: 292 2931. Go to **Membership Types** 2942. Edit a free type and turn off **Requires admin approval** (it applies to free types only) 2953. New signups for that type will become Active immediately. Paid types become Active once the payment completes`},{id:"6",slug:"bulk-member-actions",title:"Bulk Member Actions",category:"members",summary:"Select multiple members to make changes efficiently.",keywords:["bulk","batch","multiple","mass","select all","group"],order:4,content:`Bulk actions let you make changes to many members at once. 296 297## Selecting Members 298 299In the Members list: 300 3011. Check the box next to each member you want to include 3022. Or check the header checkbox to select all visible members 3033. The selection count appears in the toolbar 304 305## Available Bulk Actions 306 307Once you've selected members, the bulk action toolbar appears: 308 309### Change Status 310Change all selected members to a new status: 311- Useful for suspending inactive members 312- Or reactivating a group 313 314### Change Membership Type 315Move members to a different membership tier: 316- Upgrade or downgrade in bulk 317- Migrate to new membership structure 318 319### Export 320Download selected members as CSV: 321- For external analysis 322- Mail merge purposes 323- Backup 324 325### Send Email 326Send a one-time email to selected members: 327- Announcements 328- Targeted communications 329 330### Delete 331Permanently remove selected members: 332- Use with caution 333- Cannot be undone 334 335## When to Use Bulk Actions 336 337Common scenarios: 338 339- **Annual cleanup** â Lapse all expired members at year-end 340- **Membership restructure** â Move members to renamed types 341- **Targeted outreach** â Email members in a specific region 342- **Data cleanup** â Remove duplicate or test records 343 344## Tips 345 346- Use the field filter, status filter, and search bar to narrow down your selection before using bulk actions 347- Click column headers to sort members and find the ones you need 348- Preview the count before confirming actions 349- Some actions trigger emails â check settings first 350- Large bulk actions may take a moment to process`},{id:"28",slug:"searching-filtering-sorting-members",title:"Searching, Filtering & Sorting Members",category:"members",summary:"Find members quickly using search, field filters, sortable columns, and column customization.",keywords:["search","filter","sort","column","city","state","county","phone","zip","postal","find","organize","table"],order:5,content:`The Members list provides powerful tools to find, filter, and organize your members. 351 352## Searching Members 353 354The search bar at the top searches across member **name** and **email** with partial matching. Start typing and results update immediately. 355 356## Field Filter 357 358Use the **Filter by...** dropdown to filter by a specific field: 359 360| Field | Matches | 361|-------|---------| 362| City | Partial match on member's city |
363| State | Partial match on state | 364| County | Partial match on county | 365| Phone | Partial match on phone number | 366| Postal Code | Partial match on ZIP/postal code | 367 3681. Select a field from the "Filter by..." dropdown 3692. Type a value in the text box that appears 3703. Results update as you type 3714. Click the **X** button to clear the filter value 372 373## Status and Type Filters 374 375Use the dedicated dropdowns to filter by: 376 377- **Status** â Active, Pending, Expired, Cancelled, Rejected, or Suspended 378- **Membership Type** â Any of your configured membership types 379 380## Sorting by Column 381 382Click any **column header** to sort the table by that column: 383 384- First click sorts **ascending** (AâZ, oldest first) 385- Click again to sort **descending** (ZâA, newest first) 386- A small arrow icon shows the current sort direction 387- Unsorted columns show a faint up/down arrow 388 389All columns are sortable: Name, Email, Phone, City, State, County, Type, Status, Joined, Expires, and Auto-Renew. 390 391## Column Customizer 392 393Not every column needs to be visible. Click the **Columns** button to toggle which columns appear in the table: 394 395- Check or uncheck columns to show or hide them 396- Your column preferences are saved and persist across sessions 397- Default columns: Email, Type, Status, Expires 398 399## County Auto-Fill 400 401The **County** column is automatically populated from the member's postal code using a built-in ZIP-to-county lookup. County is set when: 402 403- A new member is created (admin or signup) 404- A member's postal code is updated 405- Members are imported via CSV (if county isn't already provided) 406 407## Combining Filters 408 409All filters work together. For example: 4101. Set Status to **Active** 4112. Set Filter by to **County** and type "Miami-Dade" 4123. Click the **Expires** column header to sort by expiration date 413 414This gives you all active members in Miami-Dade County, sorted by when they expire.`},{id:"30",slug:"managing-member-badges",title:"Managing Member Badges",category:"members",summary:"Create badge types, upload icons, assign badges to members, and control display order.",keywords:["badge","award","icon","recognition","speaker","instructor","officer","president","drag","reorder"],order:6,content:`Badges are visual recognition awards displayed on member profiles and the portal dashboard. Platform admins configure badge types per society, then society admins assign them to members. 415 416## Badge Types (Platform Admin) 417 418Badge types are configured in **Platform > Societies > [Society] > Settings > Customization**, in the **Badge types** section. 419 420### Creating a Badge Type 421 4221. Click **Add Badge Type** 4232. Fill in: 424 - **Name** â Display name (e.g., "Speaker", "Past President") 425 - **Color** â Used as fallback when no icon is uploaded 4263. Optionally upload an **icon** (PNG, JPEG, or WebP â max 5 MB, auto-compressed to 512x512) 4274. Click **Create** 428 429### Drag-and-Drop Ordering 430 431Badge types display left-to-right on the portal in priority order. To reorder: 432 4331. Grab the **drag handle** (â®â®) on any row 4342. Drag it to the desired position 4353. Drop â the new order saves automatically 436 437The **#** column shows the current display position (1 = leftmost on portal). 438 439### Managing Badge Types 440 441- **Edit** â Click the badge name to open the edit dialog 442- **Upload Icon** â Click the upload button (â) in the Actions column 443- **Remove Icon** â Click the image button (ð¼) to delete the current icon 444- **Toggle Active** â Use the switch to show/hide a badge type without deleting it 445- **Delete** â Deactivates the badge type. If members have the badge, you'll be asked to confirm 446 447### Icon Best Practices 448 449- Use square images with transparent backgrounds (PNG recommended) 450- Icons are auto-resized to 512Ã512 and optimized 451- Badges display at 112Ã112px on the portal â keep designs simple and bold 452- The badge name appears as a text label below the icon, so avoid text in the image itself 453 454## Assigning Badges to Members 455 456Badges are assigned from the member detail page: 457 4581. Open a member's profile 4592. Find the **Badges** section 4603. Click **Add Badge** and select a badge type 4614. Optionally add a note (e.g., "2024 Annual Conference") 462 463### Auto-Detected Badges 464 465Some badges are assigned automatically: 466- **Officer** â Automatically assigned when a member holds a committee role (chair, vice chair, secretary, treasurer) 467 468## Portal Display 469 470Members see their badges on the portal dashboard as large icons (112Ã112px) with the badge name below. Badges appear in the order set by the platform admin's drag-and-drop arrangement.`},{id:"31",slug:"tagging-segmenting-members",title:"Tagging & Segmenting Members",category:"members",summary:"Use tags to organize and segment members for targeted actions.",ke
470ywords:["tag","segment","group","label","organize","bulk","filter","category"],order:7,content:`Tags let you organize members into flexible groups for targeted communications and analysis. 471 472## Adding Tags to Individual Members 473 4741. Open a member's profile 4752. Find the **Tags** section 4763. Type a tag name and press Enter 4774. The tag is saved immediately 478 479## Bulk Tagging 480 481Tag multiple members at once: 482 4831. Go to the **Members** list 4842. Select members using the checkboxes 4853. Click the **Tag** button in the bulk action toolbar 4864. Type or select tags to add 4875. Click **Apply** 488 489The tag dialog shows autocomplete suggestions based on existing tags in your society. 490 491## Removing Tags 492 493- **Individual:** Click the X on any tag pill in the member's profile 494- **Bulk:** Select members, open the tag dialog, and remove tags 495 496## Filtering by Tag 497 498Use the field filter dropdown on the Members list to filter by tag. This shows only members with the selected tag. 499 500## Use Cases 501 502- **Event attendees** â Tag members who attended a specific event 503- **Volunteers** â Track members who've volunteered 504- **Board candidates** â Group potential board nominees 505- **Regional groups** â Organize by chapter or region 506- **Email targeting** â Filter by tag before sending broadcast emails 507 508## Tips 509 510- Keep tag names short and consistent (e.g., "2025-conference" not "Attended the 2025 Annual Conference") 511- Tags are case-insensitive 512- There's no limit on the number of tags per member 513- Tags appear as colored pills on member profiles and in the member list`},{id:"7",slug:"recording-manual-payments",title:"Recording Manual Payments",category:"payments",summary:"How to record check, cash, wire, and other offline payments.",keywords:["manual","payment","check","cash","wire","offline","record"],order:1,content:`When members pay outside of Stripe (check, cash, wire transfer), record the payment manually. 514 515## When to Use Manual Payments 516 517Record a manual payment when you receive: 518- Physical checks 519- Cash payments 520- Wire or bank transfers 521- Payments through other systems 522 523## Recording a Payment 524 5251. Find the member in the Members list 5262. Open their profile 5273. Click **Record Payment** (or go to their Payments tab) 5284. Fill in the payment details: 529 - **Amount** â The payment amount 530 - **Payment Method** â Check, Cash, Wire, Other 531 - **Reference** â Check number, transfer ID, etc. 532 - **Date** â When payment was received 533 - **Notes** â Optional additional details 5345. Click **Save** 535 536## What Happens Next 537 538When you record a manual payment: 539 540- Payment is logged in the member's history 541- If they have an open invoice, it's marked as paid 542- If no invoice exists, one is auto-generated 543- Member status updates if payment renews membership 544- Receipt email is sent (if configured) 545 546## Partial Payments 547 548To record a partial payment: 549 5501. Enter the partial amount 5512. Add a note explaining it's partial 5523. The invoice will show remaining balance 5534. Record additional payments as received 554 555## Viewing Payment History 556 557All payments (manual and online) appear in: 558 559- Member's profile â Payments tab 560- Reports â Payments section 561- Dashboard revenue stats 562 563## Member Receipt Downloads 564 565In the member portal, payments that have an associated invoice show a download icon. Members can click any payment row to download their receipt/invoice PDF directly from the Payments page.`},{id:"8",slug:"how-auto-renewal-works",title:"How Auto-Renewal Works",category:"payments",summary:"Understand the automatic renewal process for online members.",keywords:["auto","automatic","renewal","recurring","subscription","charge"],order:2,content:`Members who sign up online can opt into automatic renewal. Here's how it works. 566 567## The Auto-Renewal Process 568 569### 7 Days Before Expiry 570The system checks for members expiring in the next 7 days who have auto-renewal enabled. 571 572### Charge Attempt 573For each eligible member: 5741. The saved card is charged for the renewal amount 5752. If successful, membership extends by the standard duration 5763. Member receives a payment confirmation email 577 578### Card on File 579The card used for auto-renewal is: 580- Saved during initial signup (Stripe securely stores it)
581- Updated if member changes payment method in portal 582- Never visible to admins (only last 4 digits shown) 583 584## Member Notifications 585 586Members receive emails at key points: 587 588- **7 days before** â Reminder that renewal will be charged 589- **On renewal** â Payment confirmation and new expiry date 590- **If payment fails** â Notification with link to update card 591 592## What Members See 593 594In the member portal, members can: 595- View their auto-renewal status 596- See the next renewal date 597- Update their payment method 598- Cancel auto-renewal 599 600## Admin Visibility 601 602In the admin panel, you can see: 603- Auto-renewal status on member profile 604- Upcoming renewals in reports 605- Failed renewal attempts in payment history 606 607## Disabling Auto-Renewal 608 609Members can cancel anytime in their portal. Admins can also: 6101. Open member profile 6112. Go to Payment Settings 6123. Toggle off auto-renewal 613 614The member's access continues until their current expiry date. 615 616## Auto-Renewal Discount 617 618Each membership type can offer a discount when the member opts into auto-renewal (default 10%). Configure on the membership type: 619 620- **Auto-renew enabled** â master toggle 621- **Auto-renew discount percent** â the percentage off 622 623The discount applies to: 624- Initial signup (when the member checks "enable auto-renew" at signup) 625- Renewal at event checkout (auto-renew sub-toggle inside the renewal panel) 626- Standalone renewal from the portal 627 628When a member toggles auto-renew off mid-cycle, the discount doesn't get clawed back â they keep their current cycle and the next renewal charges at full price. 629 630## Auto-Renewal at Event Checkout 631 632If your society has *Renewal at event checkout* enabled, LAPSED members renewing during event checkout see a sub-toggle for auto-renew: 633 634> â Enable auto-renew (10% off â save $25/yr) 635 636Opting in does two things: 6371. Applies the auto-renew discount to the renewal price they're paying now 6382. Sets Stripe's saved card as the default payment method for the upcoming cycles 639 640Toggling auto-renew off in the panel does NOT change the event's pricing â the event still drops to the member rate as soon as they opt into renewal at all. The auto-renew toggle only affects the renewal's price + future-payment-method behavior. 641 642See [Renewal at Event Checkout](/help/paid-renewal-at-event-checkout) for the full panel behavior.`},{id:"9",slug:"failed-payments-dunning",title:"Failed Payments & Dunning",category:"payments",summary:"What happens when payments fail and how the retry process works.",keywords:["failed","decline","retry","dunning","card","error"],order:3,content:`When a payment fails, the system automatically attempts recovery through the dunning process. 643 644## What Triggers Dunning 645 646Dunning starts when: 647- An auto-renewal charge fails 648- A card is declined 649- Payment processing errors occur 650 651## The 3-Attempt Retry Sequence 652 653### Attempt 1 (Day 0) 654- Initial charge fails 655- Member receives "payment failed" email 656- Email includes link to update payment method 657 658### Attempt 2 (Day 3) 659- System retries the charge 660- If still failing, another notification sent 661- More urgent messaging 662 663### Attempt 3 (Day 7) 664- Final retry attempt 665- If fails, member is marked for manual follow-up 666- Urgent "last chance" notification 667 668## Emails Members Receive 669 670Each failed attempt triggers an email with: 671- Clear explanation of the issue 672- Link to update payment method 673- Deadline before access is affected 674 675## Viewing Dunning Status 676 677On a member's profile, you can see: 678- Current dunning stage (if active) 679- Number of retry attempts 680- Last failure reason (e.g., "card_declined", "insufficient_funds") 681- Next retry date 682 683## What Happens After 3 Failures 684 685If all three attempts fail: 686- Auto-renewal is paused for that member 687- Member enters Grace period (if configured) 688- Admin notification is sent 689- Manual intervention may be needed 690 691## Admin Actions 692 693For members in dunning, you can: 694- Wait for automatic retries 695- Contact the member directly 696- Record a manual payment if received 697- Cancel their membership if appropriate 698 699## Preventing Failed Payments 700 701Tips to reduce failures: 702- Encourage members to update cards before expiry 703- Send advance renewal reminders 704- Offer multiple payment methods`},{id:"29",slug:"handling-chargebacks-disputes",title:"Handling Chargebacks & Disputes",category:"payments",summary:"What happens when a member disputes a payment and how to respond.",keywords:["chargeback","dispute","refund","stripe","evidence","reversal","fraud"],order:4,content:`When a cardholder disputes a charge with their bank, Stripe notifies the system automatically. Here's how disputes work and what you need to do. 705 706## How Disputes Arrive 707 708When a member (or their bank) files a chargeback: 709 7101. Stripe sends a webhook notification to your system 7112. A **Dispute** record is created automatically 7123. The dispute is linked to the original payment and member 7134. You receive an **email alert** at your society's contact email with: 714 - Member name and email 715 - Disputed amount
716 - Reason for the dispute 717 - Evidence submission deadline 718 - Link to the Stripe Dashboard 719 720## Dashboard Alert 721 722When you have open disputes, a **red alert banner** appears at the top of your Dashboard showing: 723- Number of open disputes 724- Total dollar amount at risk 725- A **View Disputes** button to see full details 726 727## Disputes Page 728 729Go to **Disputes** in the sidebar (under the Finance group) to see all disputes: 730 731| Column | Description | 732|--------|-------------| 733| Date | When the dispute was filed | 734| Member | Who the disputed payment belongs to | 735| Amount | How much is being disputed | 736| Reason | Why the cardholder disputed (e.g., fraudulent, duplicate, product not received) | 737| Status | Current state of the dispute | 738| Evidence Due | Deadline to submit evidence | 739 740Each row has a **link icon** that opens the dispute directly in your Stripe Dashboard. 741 742## Dispute Statuses 743 744| Status | Meaning | 745|--------|---------| 746| **Needs Response** | You must submit evidence before the deadline | 747| **Under Review** | Evidence submitted, Stripe/bank is reviewing | 748| **Won** | Dispute resolved in your favor â funds retained | 749| **Lost** | Dispute resolved against you â funds reversed | 750 751## Responding to a Dispute 752 753Disputes are managed in the **Stripe Dashboard**, not in this admin panel: 754 7551. Click the **link icon** on any dispute to open it in Stripe 7562. Review the dispute reason and cardholder's claim 7573. Gather evidence: 758 - Payment receipt or invoice 759 - Communication with the member 760 - Proof of service/delivery 761 - Membership agreement or terms of service 7624. Submit your evidence before the deadline 7635. Wait for the bank's decision (typically 60-75 days) 764 765## What Happens When You Lose 766 767If a dispute is resolved against you (status: **Lost**): 768- The disputed amount is reversed by the bank 769- The original payment is automatically marked as **Refunded** in your system 770- An audit log entry records the loss 771 772## What Happens When You Win 773
774If a dispute is resolved in your favor (status: **Won**): 775- The funds are released back to you 776- An audit log entry records the win 777- No changes to the original payment 778 779## Common Dispute Reasons 780 781| Reason | Description | Best Evidence | 782|--------|-------------|---------------| 783| Fraudulent | Cardholder claims they didn't make the charge | Proof of member login, IP address, communication | 784| Duplicate | Cardholder claims they were charged twice | Show the charges are for different items/periods | 785| Product Not Received | Cardholder claims they didn't receive what they paid for | Proof of membership activation, event attendance | 786| Subscription Canceled | Cardholder claims they canceled | Show cancellation policy, renewal terms | 787| Unrecognized | Cardholder doesn't recognize the charge | Show your billing descriptor matches your society name | 788 789## Tips to Prevent Disputes 790 791- Use a clear **billing descriptor** in Stripe so members recognize charges 792- Send **payment confirmation emails** immediately after every charge 793- Send **renewal reminders** before auto-charging 794- Make it easy for members to **cancel or request refunds** before disputing â see [Issuing Refunds](/help/issuing-refunds) 795- Keep records of all member communications 796 797## Audit Trail 798 799All dispute events are logged: 800- **Dispute Created** â when a new dispute arrives 801- **Dispute Won** â when resolved in your favor 802- **Dispute Lost** â when resolved against you 803 804View these in the **Audit Log** (under the Admin group) by filtering for dispute actions.`},{id:"41",slug:"issuing-refunds",title:"Issuing Refunds",category:"payments",summary:"How to issue full or partial refunds for Stripe payments.",keywords:["refund","partial refund","stripe","reverse","return","money back","cancel payment"],order:7,content:`Issue full or partial refunds for any Stripe payment directly from the admin panel. Refunds are processed through Stripe and reflected in your dashboard automatically. 805 806## Where to Find the Refund Button 807 808You can issue a refund from two places: 809 8101. **Payments page** â Go to **Payments** in the sidebar. Find the payment row and click the **three-dot menu** (â®) on the right â **Refund**. 8112. **Member detail page** â Open a member â go to the **Payments** tab â click the **three-dot menu** (â®) on any payment â **Refund**. 812 813The Refund option only appears for payments that: 814- Were processed through **Stripe** (not manual cash/check payments) 815- Have a status of **Succeeded** or **Partially Refunded** 816- Have remaining refundable balance 817 818## Issuing a Full Refund 819 8201. Click **Refund** on the payment 8212. The dialog shows the payment amount and a pre-filled refund amount 8223. Enter a **reason** for the refund (required) 8234. Type **REFUND** in the confirmation box 8245. Click **Issue Full Refund** 825 826The payment status changes to **Refunded** and the member's card is credited. 827 828## Issuing a Partial Refund 829 8301. Click **Refund** on the payment 8312. Change the **Amount** to the partial amount you want to refund 8323. Enter a **reason** (required) 8334. Type **REFUND** to confirm 8345. Click **Issue Partial Refund** 835 836The payment status changes to **Partially Refunded**. You can issue additional refunds on the same payment until the full amount has been returned. 837 838## After a Refund 839 840- The payment's **status** updates to Refunded or Partially Refunded 841- The refunded amount appears in **amber text** on the payment row 842- The refund is logged in the **Audit Log** with the amount, reason, and who issued it 843- The **MTD Revenue** card on the dashboard shows a refund summary (e.g., "$150.00 refunded (2 refunds)") 844- Stripe processes the refund â funds typically return to the member's card within 5-10 business days 845 846## Stripe Dashboard Sync 847 848If someone issues a refund directly in the **Stripe Dashboard** (not through this admin panel), the system automatically syncs: 849 850- The payment status updates to Refunded or Partially Refunded 851- The refunded amount is tracked 852- An audit log entry is created (marked as "stripe_webhook" source) 853 854This means your records stay accurate regardless of where the refund was initiated. 855 856## Important Notes 857 858- **Refunds are irreversible** â once processed, they cannot be undone 859- **Manual payments** (cash, check, wire) cannot be refunded through this system â handle those offline 860- **Partial refunds** can be issued multiple times on the same payment
861- **Refunds do not automatically change membership status** â deactivate the member separately if needed (BUT renewal payments from event checkout are an exception â see below) 862- All refund activity is recorded in the **Audit Log** for compliance and record-keeping 863 864## Renewal-Payment Refunds (special handling) 865 866If you refund a \`MEMBERSHIP_RENEWAL\` line item from an order that included a renewal at event checkout, the system automatically retracts the membership benefits â you don't need to manually flip the status. 867 868How it works: 869 870- The system snapshots the member's previous state (status, dates, auto_renew) when the renewal was applied at checkout 871- On full refund: the snapshot is restored â the member goes back to LAPSED/EXPIRED with their original end date â UNLESS a later renewal already covers the cycle, in which case the snapshot is NOT restored (the later renewal stays in effect) 872- On partial refund: the membership stays active, only \`Payment.refunded_amount\` updates 873 874This works regardless of where the refund was initiated (admin UI, Stripe Dashboard, or auto-refund from the confirm flow). All three paths route through the same retraction service. 875 876Three audit events on these refunds: 877- \`MEMBERSHIP_RENEWAL_REFUNDED\` â admin or webhook-initiated 878- \`MEMBERSHIP_RENEWAL_AUTO_REFUNDED\` â confirm-flow auto refund 879- \`MEMBERSHIP_RENEWAL_AUTO_REFUND_FAILED\` â Stripe error during auto refund 880 881See [Renewal at Event Checkout](/help/paid-renewal-at-event-checkout) for the full lifecycle. 882 883## Mixed-Order Refunds 884
885An order that combines a renewal with an event has TWO Payment rows â one for the event, one for the renewal. They share a single Stripe Charge / PaymentIntent. Refunding the renewal portion via Stripe Dashboard or admin UI does NOT cascade to the event line; refunding the event portion does NOT cascade to the renewal. They're independent in terms of accounting AND consequences. 886 887If you want to refund the entire order, you need to refund both line items separately.`},{id:"10",slug:"creating-invoice-batches",title:"Creating Invoice Batches",category:"invoices",summary:"Generate invoices for multiple members at once.",keywords:["invoice","batch","bulk","create","generate","wizard"],order:1,content:`Invoice batches let you create invoices for many members simultaneously. 888 889## Starting the Batch Wizard 890 8911. Go to **Invoices** in the sidebar 8922. Click **Create Batch** 8933. The batch wizard opens 894 895## Step 1: Select Members 896 897Choose which members to invoice: 898 899### Filter Options 900- **Membership Type** â Invoice only specific types 901- **Status** â Usually Active or Grace members 902- **Expiring Between** â Members expiring in a date range 903- **Custom Filter** â Advanced filtering options 904 905### Preview 906See the count of members who match your filters before proceeding. 907 908## Step 2: Set Invoice Details 909 910Configure the invoices: 911 912- **Amount** â Invoice amount (can default to membership price) 913- **Due Date** â When payment is due 914- **Description** â Line item description 915- **Notes** â Optional notes appearing on invoice 916 917## Step 3: Review and Create 918 919Before creating: 920- Review the total number of invoices 921- Check the total amount 922- Verify a few sample invoices 923 924Click **Create Invoices** to generate the batch. 925 926## What Happens Next 927 928When you create a batch: 929- Individual invoices are created for each member 930- PDF versions are generated 931- Invoices appear in each member's profile 932- Batch is logged for your records 933 934## After Creation 935 936The batch summary shows: 937- Number of invoices created 938- Total amount 939- Options to send emails or download PDFs 940 941Note: Creating invoices doesn't automatically send them. Use the Send function to email invoices to members.`},{id:"11",slug:"sending-invoice-emails",title:"Sending Invoice Emails",category:"invoices",summary:"Email invoices to members individually or in batches.",keywords:["send","email","invoice","notify","deliver"],order:2,content:`After creating invoices, send them to members via email. 942 943## Sending a Batch 944 945After creating an invoice batch: 946 9471. On the batch summary, click **Send Emails** 9482. Review the email template preview 9493. Confirm the send 950 951All members in the batch receive their invoice email with PDF attached. 952 953## Sending Individual Invoices 954 955To send (or resend) a single invoice: 956 9571. Find the invoice in the Invoices list or member profile 9582. Click the **Send** button 9593. Confirm the send 960 961## Forwarding to Different Address 962 963If a member needs their invoice sent elsewhere: 964 9651. Open the invoice 9662. Click **Forward** 9673. Enter the alternate email address 9684. Add an optional message 9695. Send 970 971The invoice is sent to the new address while the record remains on the member's profile. 972 973## Tracking Sent Status 974 975Each invoice shows its email status: 976- **Not sent** â Created but not emailed 977- **Sent** â Email delivered 978- **Opened** â Member opened the email (if tracking enabled) 979 980## Email Template 981 982Invoice emails use the "Invoice" template from the Emails page. Customize it to include: 983- Your society branding 984- Payment instructions 985- Contact information 986 987## Resending Invoices 988 989To resend an invoice: 9901. Open the invoice 9912. Click **Resend** 9923. Confirm 993 994The member receives another copy. Use this for: 995- Members who didn't receive the original 996- Updated invoice information 997- Payment reminders`},{id:"12",slug:"marking-invoices-paid",title:"Marking Invoices Paid",category:"invoices",summary:"Record payment against invoices for offline payments.",keywords:["paid","payment","mark","record","complete","void"],order:3,content:`When members pay outside of the online system, mark their invoices as paid manually. 998 999## When Member Pays Outside System 1000 1001If a member sends a check, wire, or pays another way: 1002 10031. Find their invoice (Invoices list or member profile) 10042. Click **Mark as Paid** 10053. Enter payment details: 1006 - Payment method (Check, Wire, Cash, Other) 1007 - Reference number (check number, transfer ID) 1008 - Payment date 1009 - Notes (optional) 10104. Save 1011 1012## What Happens 1013 1014When you mark an invoice paid: 1015- Invoice status changes to Paid 1016- Payment is recorded in member's history
1017- If it's a renewal invoice, membership extends 1018- Receipt email is sent (if configured) 1019 1020## Partial Payments 1021 1022For partial payments: 1023 10241. Open the invoice 10252. Click **Record Payment** 10263. Enter the partial amount 10274. Save 1028 1029The invoice shows: 1030- Amount paid so far 1031- Remaining balance 1032- Payment history 1033 1034Continue recording payments until the balance is zero. 1035 1036## Voiding Invoices 1037 1038To void an invoice (cancel it): 1039 10401. Open the invoice 10412. Click **Void** 10423. Enter a reason 10434. Confirm 1044 1045Voided invoices: 1046- Are marked as Void (not deleted) 1047- Don't count toward revenue 1048- Remain visible for audit purposes 1049 1050## Common Scenarios 1051 1052**Member overpaid:** Record the actual amount; note the overpayment and apply to next invoice or refund. 1053 1054**Wrong amount invoiced:** Void the incorrect invoice and create a new one with the correct amount. 1055 1056**Member disputes:** Add notes to the invoice documenting the dispute before resolution.`},{id:"13",slug:"customizing-email-templates",title:"Customizing Email Templates",category:"email",summary:"Edit the emails your system sends to members.",keywords:["template","customize","edit","email","merge","variable"],order:1,content:`Customize the automated emails your system sends to match your society's voice. 1057 1058## Available Template Types 1059 1060Your system includes templates for: 1061 1062- **Welcome Email** â Sent when new members are approved 1063- **Payment Confirmation** â After successful payment 1064- **Invoice Email** â When invoices are sent 1065- **Password Reset** â For login recovery 1066- **Magic Link** â Passwordless login link 1067- **Renewal Reminder** â Part of renewal sequence 1068- **Expiry Notice** â When membership expires 1069- **Application Approved/Rejected** â Application decision notifications 1070- **Pending Approval (Member)** â Confirms application receipt to the applicant 1071- **Pending Approval (Admin)** â Notifies admin of a new pending application 1072- **Payment Failed (1/2/3)** â Escalating dunning emails for failed auto-renewals 1073- **Order Confirmation** â Commerce order receipt with line items breakdown 1074 1075## Editing a Template 1076 10771. Go to **Emails** in the sidebar (under the Engagement group) 10782. Click on the template you want to edit 10793. Use the **rich text editor** to modify the subject line and body â the toolbar includes formatting (bold, italic, underline), text alignment, links, and template variable insertion 10804. Toggle **Source Mode** to edit the raw HTML directly for advanced layouts 10815. Preview your changes 10826. Save 1083 1084## Template Variables (Merge Fields) 1085 1086Insert dynamic content using merge fields: 1087 1088| Variable | Inserts | 1089|----------|---------| 1090| \`{{member.firstName}}\` | Member's first name | 1091| \`{{member.lastName}}\` | Member's last name | 1092| \`{{member.email}}\` | Member's email | 1093| \`{{membership.type}}\` | Membership type name | 1094| \`{{membership.expiryDate}}\` | Expiry date | 1095| \`{{society.name}}\` | Your society name | 1096| \`{{invoice.amount}}\` | Invoice amount | 1097| \`{{payment.amount}}\` | Payment amount | 1098| \`{{portal_url}}\` | Member portal login URL | 1099| \`{{magic_link_url}}\` | Magic link login URL (magic link template) | 1100| \`{{reset_url}}\` | Password reset URL (password reset template) | 1101| \`{{update_payment_url}}\` | Update payment method URL (dunning templates) | 1102 1103## Testing Emails 1104 1105Before going live with changes: 1106 11071. Click **Send Test** 11082. Enter your email address 11093. Review the email you receive 11104. Make adjustments if needed 1111 1112## Restoring Defaults 1113 1114If you want to start over: 1115 11161. Open the template 11172. Click **Restore Default** (or **Restore All Defaults** to reset every template at once) 11183. Confirm 1119 1120This resets to the original system template. Your current version is replaced immediately. 1121 1122## Best Practices 1123 1124- Keep subject lines under 50 characters 1125- Use the member's first name for personalization 1126- Include clear calls to action 1127- Test on mobile devices 1128- Proofread carefully`},{id:"14",slug:"renewal-reminder-sequence",title:"Renewal Reminder Sequence",category:"email",summary:"Configure the automated series of renewal reminder emails.",keywords:["renewal","reminder","sequence","automation","drip","touchpoint"],order:2,content:`The renewal sequence automatically reminds members to renew before and after expiry. 1129 1130## How the Sequence Works 1131 1132The system sends a series of emails based on each member's expiry date: 1133- Emails before expiry encourage timely renewal 1134- Emails after expiry (during grace) urge quick action 1135- Final emails target lapsed members for re-engagement 1136 1137## Default 9 Touchpoints 1138 1139| # | Timing | Purpose | 1140|---|--------|---------| 1141| 1 | 60 days before | Early heads-up | 1142| 2 | 30 days before | Renewal reminder | 1143| 3 | 14 days before | Two-week warning | 1144| 4 | 7 days before | One-week warning | 1145| 5 | 1 day before | Final reminder | 1146| 6 | On expiry | Expiry notification |
1147| 7 | 7 days after | Grace period reminder | 1148| 8 | 14 days after | Urgent renewal request | 1149| 9 | 30 days after | Re-engagement attempt | 1150 1151## Editing the Sequence 1152 11531. Go to **Renewals** in the sidebar (under the Engagement group) 11542. Click on any touchpoint to edit 11553. Adjust timing, subject, or content 11564. Enable or disable individual touchpoints 11575. Save changes 1158 1159## Audience Targeting 1160 1161Each touchpoint can target specific audiences: 1162 1163- **All members** â Everyone in the renewal window 1164- **Manual renewal only** â Members without auto-renewal 1165- **Auto-renewal only** â Members with auto-renewal enabled 1166- **Lapsed only** â Members who've passed grace period 1167 1168## Viewing Notification History 1169 1170To see what emails a member has received: 1171 11721. Open their profile 11732. Go to **Communications** tab 11743. View the list of sent notifications 1175 1176This helps you understand where they are in the sequence. 1177 1178## Disabling the Sequence 1179 1180To stop all automated renewals: 11811. Go to **Renewals** in the sidebar 11822. Toggle off **Enable Renewal Sequence** 1183 1184## Restoring Defaults 1185 1186If you've heavily customized the sequence and want to start fresh: 1187 11881. Go to **Renewals** in the sidebar 11892. Click **Restore Defaults** in the top-right 11903. Confirm â this replaces all 9 touchpoints with the original timing and content 1191 1192Individual members can be excluded via their profile settings.`},{id:"44",slug:"pausing-email-automations",title:"Pausing Email Automations (Kill Switch)",category:"email",summary:"Temporarily stop all outgoing emails with the email automation toggle.",keywords:["pause","stop","kill switch","disable","email","automation","emergency","block","circuit breaker","suppression","bounce"],order:3,content:`Instantly pause all automated emails if something goes wrong â a single toggle that blocks every outgoing email. 1193 1194## What It Controls 1195 1196When paused, **all** outgoing emails are blocked: 1197 1198- Welcome emails 1199- Payment receipts 1200- Invoice emails 1201- Renewal reminders (entire sequence) 1202- Dunning notices (payment failed 1/2/3) 1203- Password reset and magic link emails 1204- Application status notifications 1205- Order confirmations 1206 1207## How to Pause Emails 1208 12091. Go to **Settings** in the sidebar 12102. The **Email Automations** card is at the top of the General tab 12113. Toggle the switch **off** to pause all emails 1212 1213When paused: 1214- The card displays an amber warning border 1215- The label changes to "Email automations paused" 1216- A warning message confirms all outgoing emails are blocked 1217 1218## How to Resume 1219 1220Toggle the switch **on** to resume normal email sending. Emails will start flowing immediately. 1221 1222## What Happens to Blocked Emails 1223 1224Emails triggered while paused are logged as **FAILED** with the message "Email sending is paused for this society." They are **not** queued or retried â they are skipped permanently. This means: 1225 1226- Renewal reminders skipped during pause won't be re-sent (the cron moves past them) 1227- Welcome emails for members approved during pause are lost 1228- Password resets and magic links will fail â members will need to request again after resuming 1229 1230## When to Use It 1231 1232- You discover a template has wrong content going out to members 1233- SES is having deliverability issues and you want to stop accumulating failures 1234- You're doing bulk data operations and don't want triggered emails 1235- Testing or debugging email issues in production 1236 1237## Important Notes 1238 1239- This is a **per-society** setting â it only affects the society you're configuring 1240- The toggle saves immediately (no separate Save button needed) 1241- The renewal sequence cron skips paused societies entirely â no notifications are logged 1242- Test emails from the template editor are also blocked when paused 1243 1244## Hourly Send Cap (Circuit Breaker) 1245 1246As an additional safety net, the system enforces an hourly send cap of **200 emails per society per hour**. If a runaway process or misconfiguration tries to blast emails, the cap blocks further sends for the remainder of the hour. Blocked emails are logged as FAILED with an "hourly email send cap" message. The email health monitor checks for cap hits every 5 minutes. 1247 1248## Email Suppression List 1249 1250The system automatically suppresses emails to addresses that hard-bounce or file spam complaints. Suppressed addresses are blocked from receiving any future emails. You can view and manage the suppression list from **Emails > Suppression List**. See the **Email Logs & Suppression List** article for details.`},{id:"15",slug:"managing-events",title:"Managing Events",category:"commerce",summary:"Create events with pricing tiers and manage registrations.",ke
1250ywords:["event","registration","ticket","pricing","early bird","conference"],order:1,content:`Create and manage events with flexible pricing and registration. 1251 1252## Creating an Event 1253 12541. Go to **Events** in the sidebar (under the Commerce group) 12552. Click **Create Event** 12563. Fill in event details: 1257 - **Name** â Event title 1258 - **Description** â Full event description (markdown supported) 1259 - **Date/Time** â When the event occurs 1260 - **Location** â Venue or "Online" for virtual events 1261 - **Event Website URL** â Link to the event's meeting page (optional, shown in the portal dashboard widget) 1262 - **Capacity** â Maximum registrations (optional) 1263 1264## Setting Up Pricing Tiers 1265 1266Events can have multiple price points: 1267 1268### Early Bird Pricing 1269- Lower price for early registrants 1270- Set start and end dates for the early bird window 1271- Automatically switches to regular pricing 1272 1273### Member Pricing 1274- Special rate for society members 1275- System verifies membership at checkout 1276- Encourages membership signups 1277 1278### Regular Pricing 1279- Standard price for non-members 1280- Available throughout registration period 1281 1282## Example Pricing Setup 1283 1284| Tier | Price | Availability | 1285|------|-------|--------------| 1286| Early Bird | $50 | Until March 1 | 1287| Member | $75 | March 1 - Event | 1288| Regular | $100 | March 1 - Event | 1289 1290## Per-Role Non-Member Pricing 1291 1292If you want to charge different rates by professional role (e.g., Resident < Physician), use the per-role price matrix. See [Per-Role Non-Member Event Pricing](/help/per-role-non-member-event-pricing) for the full setup. 1293 1294## Child Events (Add-Ons) 1295 1296Events can have child events (workshops, breakouts, optional dinners) that members register for as add-ons during the main event flow: 1297 12981. Create the parent event first 12992. Create each child with **Parent Event** set to the parent's ID 13003. Each child has its own price, capacity, registration form, and child-event roles 13014. In the portal, members see children as checkboxes on the main event's registration wizard 1302 1303Children with their own \`external_registration_url\` (legacy URL-only events) bypass the wizard and link out directly. 1304 1305## Registration Form Fields 1306 1307Each event can attach a registration form built from your society's field library. See [Event Form Field Configuration](/help/event-form-field-configuration) for the field-library setup, sync-to-event-app controls, and the "Hidden in portal" warning chip. 1308 1309## Free Membership Offer 1310 1311To use the event as a member-recruitment tool, enable the free-membership offer in the event's edit page. See [Free Membership Offer at Event Registration](/help/free-membership-offer-at-events). 1312 1313## Renewal at Event Checkout 1314 1315If your society has *Renewal at event checkout* enabled, LAPSED/EXPIRED members registering for the event see a renewal panel and can pay dues alongside their event registration. See [Renewal at Event Checkout](/help/paid-renewal-at-event-checkout). 1316 1317## Publishing Your Event 1318 1319Events have two states: 1320 1321- **Draft** â Only visible to admins, not on public site 1322- **Published** â Live and accepting registrations 1323 1324Click **Publish** when ready to go live. 1325 1326## Managing Registrations 1327 1328Click **Registration quickview** on the event page to: 1329 1330- See who's registered 1331- Check payment status 1332- Export attendee list 1333- Send emails to registrants 1334 1335For registration pace, revenue, refunds, and per-child breakdowns, click the event's **name** to open its [Event dashboard](/help/event-dashboard). 1336 1337## Event Check-In 1338 1339On the event day: 1340- Open Registration quickview from mobile 1341- Mark attendees as checked in 1342- Track attendance in real-time 1343 1344## Event-App Integration 1345 1346If you use an event app: 1347- Sync registrations automatically 1348- Push updates to attendees 1349- Integration status shown on event page 1350 1351## Portal Dashboard Widget 1352 1353Upcoming events automatically appear on the member portal dashboard: 1354- Shows up to 3 upcoming events with registration status 1355- Registered members can open the event app directly (auto-logged in via SSO) 1356- Unregistered members see a "Register Now" link 1357- Events with a website URL show a "Meeting Page" link 1358- Event location links to Google Maps`},{id:"16",slug:"managing-products",title:"Managing Products",category:"commerce",summary:"Create and sell products through the member portal.",keywords:["product","shop","store","inventory","merchandise","sell"],order:2,content:`Sell merchandise, publications, and other items to your members and visitors. 1359 1360## Creating a Product 1361 13621. Go to **Products** in the sidebar (under the Commerce group) 13632. Click **Add Product** 13643. Fill in the details: 1365 - **Name** â Product title 1366 - **Description** â What the product is (optional) 1367 - **Price** â Cost in dollars 1368 - **Inventory** â Number in stock (leave blank for unlimited) 1369 - **Image URL** â Link to a product image (optional) 1370 - **Active** â Toggle to show or hide from the portal 1371 1372## Inventory Tracking 1373 1374- If you set an inventory count, the system tracks stock automatically 1375- When stock reaches zero, the product becomes unavailable for purchase 1376- Leave inventory blank for items with unlimited availability (e.g., digital goods, subscriptions) 1377 1378## Display Order 1379 1380Use the **Display Order** field to control how products appear in the portal shop. Lower numbers appear first. 1381 1382## Editing and Deleting 1383 1384- Click the **Edit** icon on any product to update details or pricing 1385- Click **Delete** to permanently remove a product 1386- Toggle the **Active** switch to temporarily hide a product without deleting it 1387 1388## Member Purchases 1389 1390Members buy products through the portal shop. Products are added to the cart and purchased together with events or donations in a single checkout.`},{id:"17",slug:"running-donation-campaigns",title:"Running Donation Campaigns",category:"commerce",summary:"Set up donation campaigns with optional fundraising goals.",keywords:["donation","campaign","fundraise","giving","contribute","goal"],order:3,content:`Create campaigns to accept donations from your members and supporters. 1391 1392## Creating a Campaign 1393 13941. Go to **Donations** in the sidebar (under the Commerce group) 13952. Click **Create Campaign** 13963. Fill in: 1397 - **Name** â Campaign title (e.g., "Annual Fund", "Building Renovation")
1398 - **Description** â What the donations support (optional) 1399 - **Goal Amount** â Optional fundraising target 1400 - **Active** â Toggle to accept or stop donations 1401 1402## Goal Tracking 1403 1404If you set a goal amount: 1405- Progress is tracked automatically as donations come in 1406- Members can see how close the campaign is to its goal 1407- Reaching the goal does not automatically close the campaign â donations continue unless you deactivate it 1408 1409## Managing Campaigns 1410 1411- **Edit** any campaign to update its name, description, or goal 1412- **Deactivate** a campaign to stop accepting donations (existing donations are preserved) 1413- **Delete** removes the campaign permanently 1414 1415## How Members Donate 1416 1417Members donate through the portal: 14181. They browse active campaigns on the Donations page 14192. Choose a campaign and enter a custom amount 14203. Add the donation to their cart 14214. Complete checkout (can combine with event registrations and product purchases) 1422 1423## Viewing Donations 1424 1425All donations appear as orders. Go to **Orders** in the sidebar to see donation line items, amounts, and donor details.`},{id:"18",slug:"viewing-orders",title:"Viewing & Managing Orders",category:"commerce",summary:"Track commerce orders for events, products, and donations.",ke
1425ywords:["order","purchase","transaction","checkout","receipt"],order:4,content:`The Orders page gives you a centralized view of all commerce transactions. 1426 1427## Accessing Orders 1428 1429Go to **Orders** in the sidebar (under the Finance group). 1430 1431## Order Information 1432 1433Each order shows: 1434- **Order Number** â Unique identifier 1435- **Member/Guest** â Who placed the order 1436- **Date** â When the order was placed 1437- **Total** â Order amount 1438- **Status** â Pending, Paid, Refunded, or Failed 1439- **Line Items** â Events, products, and/or donations in the order 1440 1441## Filtering Orders 1442 1443Use the search and filter controls to find specific orders: 1444- Search by member name or email 1445- Filter by status (Paid, Pending, etc.) 1446 1447## Order Details 1448 1449Click any order to see the full breakdown: 1450- Individual line items with type (event, product, donation) 1451- Payment method and Stripe reference 1452- Member contact information 1453 1454## Order Statuses 1455 1456| Status | Meaning | 1457|--------|---------| 1458| Pending | Payment not yet confirmed | 1459| Paid | Payment successful | 1460| Refunded | Payment was refunded | 1461| Failed | Payment attempt failed | 1462 1463## Notes 1464 1465- Orders are created automatically during portal checkout 1466- Each order can contain a mix of events, products, and donations 1467- One Stripe payment is collected per order, but individual Payment records are created per line item`},{id:"19",slug:"managing-committees",title:"Managing Committees",category:"engagement",summary:"Create committees, assign members with roles, and manage open positions.",keywords:["committee","board","group","role","chair","opening","application","position"],order:1,content:`Organize your society's committees, assign members to roles, and recruit through open positions. 1468 1469## Creating a Committee 1470 14711. Go to **Committees** in the sidebar (under the Members group) 14722. Click **Create Committee** 14733. Fill in: 1474 - **Name** â Committee name (e.g., "Finance Committee", "Events Board") 1475 - **Description** â Purpose of the committee (optional) 14764. Save to create 1477 1478## Adding Members to a Committee 1479 14801. Select a committee from the list 14812. Go to the **Members** tab 14823. Click **Add Member** 14834. Search for and select a society member 14845. Assign a role: 1485 - **Chair** â Committee leader 1486 - **Vice Chair** â Deputy leader 1487 - **Secretary** â Meeting notes and communications 1488 - **Treasurer** â Financial oversight 1489 - **Member** â General committee member 14906. Save 1491 1492You can change a member's role or remove them at any time. 1493 1494## Creating Open Positions (Openings) 1495 1496Advertise committee vacancies so members can apply: 1497 14981. Select a committee 14992. Go to the **Openings** tab 15003. Click **Create Opening** 15014. Fill in: 1502 - **Title** â Position title (e.g., "Treasurer Position") 1503 - **Description** â What the role involves 1504 - **Role** â The committee role being offered 15055. Save â the opening is now visible to portal members 1506 1507## Reviewing Applications 1508 1509When members apply for an opening: 1510 15111. Click the opening to see its applications 15122. Each application shows the member's name, email, and optional message 15133. **Accept** â The member is automatically added to the committee with the opening's role 15144. **Reject** â The application is marked as rejected 1515 1516## Closing an Opening 1517 1518To stop accepting applications, click **Close** on the opening. Closed openings are no longer visible in the member portal. 1519 1520## All Openings View 1521 1522When no committee is selected, the page shows a summary of all open positions across every committee, with application counts. 1523 1524## Portal View 1525 1526Members see committees on their portal Committees page: 1527- View all active committees and their member counts 1528- See open positions and apply with an optional message 1529- Track their application status (pending, accepted, rejected) 1530- Withdraw pending applications`},{id:"20",slug:"creating-polls",title:"Creating & Managing Polls",category:"engagement",summary:"Create surveys with multiple question types and view results.",keywords:["poll","survey","vote","question","feedback","results","rating"],order:2,content:`Gather member feedback with polls that support multiple question types. 1531 1532## Creating a Poll 1533 15341. Go to **Polls** in the sidebar (under the Engagement group) 15352. Click **Create Poll** 15363. Fill in the poll details: 1537 - **Title** â Poll name 1538 - **Description** â What the poll is about (optional) 1539 - **Anonymous** â Toggle on to hide respondent identities in results
1540 - **Show Results** â Allow members to see results after responding 1541 - **Opens At / Closes At** â Optional scheduling (leave blank for manual control) 1542 1543## Adding Questions 1544 1545Each poll needs at least one question. Available question types: 1546 1547| Type | Description | 1548|------|-------------| 1549| Free Text | Open-ended text response | 1550| Rating (1-5) | Star or numeric rating | 1551| Single Choice | Select one option from a list | 1552| Multiple Choice | Select multiple options from a list | 1553| Scale | Numeric scale response | 1554 1555For choice questions, add the answer options members can pick from. You can reorder questions by dragging. 1556 1557## Poll Lifecycle 1558 1559Polls go through three stages: 1560 15611. **Draft** â Being configured, not visible to members 15622. **Published** â Live and accepting responses 15633. **Closed** â No longer accepting responses, results preserved 1564 1565## Publishing a Poll 1566 1567Click **Publish** to make a poll available to members. Published polls appear on the member portal dashboard and committees page. 1568 1569## Viewing Results 1570 1571Click the **Results** button on any poll to see: 1572- Response count 1573- Per-question aggregated results 1574- Charts for choice and rating questions 1575- Individual text responses 1576 1577You can **export results** to CSV for further analysis. 1578 1579## Anonymous Polls 1580 1581When anonymous mode is enabled: 1582- Members must still log in to respond (preventing duplicates) 1583- Results show aggregated data without identifying who answered what 1584- Admin can see response counts but not individual identities`},{id:"21",slug:"making-announcements",title:"Making Announcements",category:"engagement",summary:"Post announcements to the member portal dashboard.",keywords:["announcement","notice","news","broadcast","portal","message"],order:3,content:`Share news and updates with your members through portal announcements. 1585 1586## Creating an Announcement 1587 15881. Go to **Announcements** in the sidebar (under the Engagement group) 15892. Click **Create Announcement** 15903. Fill in: 1591 - **Title** â Announcement headline 1592 - **Content** â Full announcement text (optional, for longer messages) 1593 - **Priority** â Higher numbers appear first (use 0 for normal priority) 1594 - **Active** â Toggle to show or hide 1595 - **Expires At** â Optional expiration date/time 1596 1597## Where Announcements Appear 1598 1599Active announcements display on the member portal dashboard. Members see them when they log in, so announcements are a great way to communicate important updates. 1600 1601## Managing Announcements 1602 1603- **Edit** any announcement to update its content 1604- **Toggle active** to quickly show or hide an announcement without deleting it 1605- **Delete** to permanently remove an announcement 1606- Set an **expiration date** for time-sensitive announcements â they'll automatically stop displaying after that date 1607 1608## Priority 1609 1610Use priority to control the order of multiple announcements: 1611- Priority 0 is the default (normal) 1612- Higher priority announcements appear first 1613- Announcements with the same priority are shown newest first 1614 1615## Best Practices 1616 1617- Keep titles short and clear 1618- Use content for longer explanations 1619- Set expiration dates for event-related or deadline-based announcements 1620- Use priority for urgent notices that need to be seen first`},{id:"22",slug:"generating-reports",title:"Generating Reports",category:"settings",summary:"View revenue, membership, retention, and expiration reports.",keywords:["report","analytics","revenue","statistics","retention","chart","data"],order:1,content:`The Reports page provides analytics about your society's financial and membership health. 1621 1622## Accessing Reports 1623 1624Go to **Reports** in the sidebar (under the Admin group). 1625 1626## Date Range 1627 1628Select a time period for your reports: 1629- **This Month** â Current calendar month 1630- **Last Month** â Previous calendar month 1631- **This Quarter** â Current quarter to date 1632- **Year to Date** â January 1 through today 1633- **Last Year** â Full previous year 1634- **Custom** â Pick specific start and end dates 1635 1636## Available Reports 1637 1638### Revenue Report 1639- Total revenue for the period 1640- Revenue broken down by payment method 1641- Monthly revenue trend chart 1642- Comparison with previous period 1643 1644### Membership Report 1645- Total active members
1646- New members joined during the period 1647- Members by membership type (pie chart) 1648- Membership growth trend 1649 1650### Retention Report 1651- Renewal rate for the period 1652- Members who renewed vs. lapsed 1653- Retention by membership type 1654 1655### Expiration Forecast 1656- Members expiring in the next 30, 60, and 90 days 1657- Breakdown by membership type 1658- Helps plan renewal outreach 1659 1660## Exporting Data 1661 1662Use the export button to download report data as CSV for further analysis in a spreadsheet.`},{id:"23",slug:"managing-admin-users",title:"Managing Admin Users",category:"settings",summary:"Add and manage admin user accounts and roles.",keywords:["user","admin","role","account","permission","access","staff"],order:2,content:`Control who has access to the admin panel by managing user accounts. 1663 1664## Accessing User Management 1665 1666Go to **Users** in the sidebar (under the Admin group). 1667 1668## Adding a User 1669 16701. Click **Add User** 16712. Fill in: 1672 - **Email** â Their login email address 1673 - **Name** â Full name 1674 - **Password** â Initial password 1675 - **Role** â Their access level 16763. Save 1677 1678The new user can immediately log in with the provided credentials. 1679 1680## User Roles 1681 1682| Role | Access | 1683|------|--------| 1684| Admin | Full access to all society features | 1685| Super Admin | All admin access plus platform-level management | 1686 1687## Editing Users 1688 1689Click any user in the list to edit their: 1690- Name 1691- Email 1692- Role 1693- Password (reset) 1694 1695## Filtering 1696 1697Use the search bar to find users by name or email, or filter by role. 1698 1699## Security Notes 1700 1701- Each admin should have their own account (don't share credentials) 1702- Use strong passwords 1703- Review user access periodically and remove accounts for departed staff`},{id:"24",slug:"using-the-audit-log",title:"Using the Audit Log",category:"settings",summary:"Track all system activity and changes for accountability.",keywords:["audit","log","activity","history","track","change","security"],order:3,content:`The Audit Log records every significant action taken in the system. 1704 1705## Accessing the Audit Log 1706 1707Go to **Audit log** in the sidebar (under the Admin group). 1708 1709## What's Logged 1710 1711The audit log tracks: 1712- Member creates, updates, and status changes 1713- Payment processing and recording 1714- Invoice creation and sending 1715- Email sends 1716- Login attempts (admin and portal) 1717- Settings changes 1718- User account changes 1719- Payment method updates 1720- Committee changes 1721 1722## Log Entry Details 1723 1724Each entry shows: 1725- **Action** â What was done (e.g., "Member Created", "Payment Recorded") 1726- **User** â Who performed the action 1727- **Resource** â What was affected 1728- **Timestamp** â When it happened 1729- **Details** â Expanded view with additional data 1730 1731Click any entry to expand and see the full details including before/after values where applicable. 1732 1733## Filtering 1734 1735Narrow down the log using: 1736- **Action Type** â Filter by specific action (e.g., only payment actions) 1737- **Resource Type** â Filter by what was affected (members, payments, etc.) 1738- **Date Range** â Limit to a specific time period 1739 1740## When to Use the Audit Log 1741 1742- **Investigating issues** â See exactly what happened and when 1743- **Accountability** â Know which admin made a change 1744- **Security** â Detect unauthorized access or suspicious activity 1745- **Compliance** â Maintain a record of all data changes`},{id:"25",slug:"importing-exporting-members",title:"Importing & Exporting Members",category:"settings",summary:"Import members from CSV files and export data for external use.",keywords:["import","export","csv","upload","download","migrate","data","bulk","memberclicks","template"],order:4,content:`Transfer member data in and out of the system using CSV files. 1746 1747## Accessing Import/Export 1748 1749Go to **Import/export** in the sidebar (under the Admin group). 1750 1751## Importing Members 1752 1753### Step 1: Upload CSV 1754 17551. Switch to the **Import** tab 17562. Select a CSV file from your computer 17573. Choose whether to **update existing members** (matched by email) 17584. Click **Preview** to validate the file 1759 1760### Step 2: Preview & Configure 1761 1762The preview shows: 1763- How many new members will be created 1764- How many existing members will be updated (if enabled) 1765- Any validation errors or warnings 1766- A sample of the data 1767 1768Configure import options: 1769- **Default Membership Type** â Applied to members without a type specified 1770- **Default Status** â Starting status for new members (typically Active) 1771- **Send Welcome Emails** â Notify new members of their account 1772 1773### Step 3: Execute Import 1774 1775Review the summary and click **Import** to process. The results show: 1776- Number of members created 1777- Number updated 1778- Any errors encountered 1779 1780### CSV Format 1781 1782Your CSV should include columns for: 1783- \`email\` (required) 1784- \`first_name\`, \`last_name\` 1785- \`phone\`, \`address\`, \`city\`, \`state\`, \`county\`, \`zip\` 1786- \`company\` 1787- \`membership_type\` (name) 1788- \`status\` 1789- \`start_date\`, \`expiry_date\` 1790 1791If \`county\` is not provided in the CSV, it will be auto-filled from the member's postal code using a built-in ZIP-to-county lookup. 1792 1793## Exporting Data 1794 1795Switch to the **Export** tab: 1796 1797### Export Members 1798Download your full member list as CSV, including: 1799- Contact information 1800- Membership type and status 1801- Dates (joined, expiry) 1802- Custom fields 1803 1804### Export Payments 1805Download payment records as CSV for accounting purposes. 1806 1807## MemberClicks Import 1808 1809If your society previously used MemberClicks, you can import members directly from the MemberClicks API instead of CSV. See the **MemberClicks Integration** article for full setup and import instructions. 1810 1811## Export Templates 1812 1813Save frequently-used export configurations as templates: 1814 18151. On the **Export** tab, configure your column selection and filters 18162. Click **Save as Template** and give it a name 18173. Next time, select a saved template from the dropdown to instantly apply the same settings 18184. Templates can be renamed or deleted from the dropdown menu 1819 1820## Tips 1821 1822- Always preview before importing to catch errors 1823- Back up your data by exporting before making bulk changes 1824- Use export for mail merges, external analysis, or migration to other systems`},{id:"26",slug:"configuring-society-settings",title:"Configuring Society Settings",category:"settings",summary:"Set up Stripe payments, Mailchimp, MailerLite, MemberClicks, Event App, email provider, dues cycle, and branding.",keywords:["settings","configure","stripe","mailchimp","mailerlite","memberclicks","event app","email provider","ses","logo","favicon","icon","brand","color","integration","dues","cycle","anniversary","calendar","connect","disconnect"],order:5,content:`The Settings page is where you configure your society's integrations and branding. 1825 1826## Accessing Settings 1827 1828Go to **Settings** in the sidebar (under the Admin group). 1829 1830## Dues Cycle (Platform Admin) 1831 1832The dues cycle determines when memberships expire. This is configured by platform admins in the society edit form. 1833 1834**Calendar Year** (default): All members expire on the same date. Set the start month and day â memberships expire on the last day of the month before the start month. Example: start month October â all memberships expire September 30. 1835
1836**Anniversary**: Each member's membership expires exactly 1 year from their join or renewal date. Early renewals extend from the current end date (no lost days). Lapsed renewals start fresh from today. 1837 1838The grace period setting applies to both modes. 1839 1840## Integrations 1841 1842Integrations can be configured from **Settings** (society admins) or from the **Integrations** tab in **Platform > Societies > [Society] > Settings** (platform admins). The platform view shows every integration as a card with connect and disconnect actions; feature switches (Commerce, Mailchimp, MailerLiteâ¦) are on its **Features** tab, next to what each one needs. 1843 1844### Stripe (Payments) 1845 1846Connect Stripe to accept online payments: 1847 1848- **Settings page:** Enter your Publishable Key, Secret Key, and (optional) Webhook Secret â Save Keys â Test Connection 1849- **Platform Admin:** Click **Connect** on the Stripe card â enter credentials â the system tests automatically 1850 1851Once connected, members can pay online for memberships, events, products, and donations. Without Stripe, you can still record manual payments. 1852 1853To disconnect: use the **â¯** menu on the Stripe card â Disconnect. This clears all stored keys. 1854 1855### Mailchimp (Email Marketing) 1856 1857Sync your member list with Mailchimp: 1858 1859- **Settings page:** Enter your API Key and Server Prefix â Save & Test â select an audience 1860- **Platform Admin:** Click **Connect** on the Mailchimp card â enter credentials â the system tests and shows audiences â select one 1861 1862When connected, member data syncs to your selected Mailchimp audience. 1863 1864To disconnect: use the **â¯** menu on the Mailchimp card â Disconnect. 1865 1866### Event App 1867 1868Connect to an event-app instance to import events and push attendees: 1869 1870- **Platform Admin only:** Click **Connect** on the Event App card â enter the Base URL and Import API Key â Connect 1871 1872Once connected, you can import events from the event app, attendees are pushed automatically after event payment, and members get SSO access to the event app from their portal. 1873 1874To disconnect: use the **â¯** menu on the Event App card â Disconnect. 1875 1876### MailerLite (Email Marketing) 1877 1878Sync your member list with MailerLite as an alternative to Mailchimp: 1879 1880- **Settings page:** Enter your MailerLite API Key â Save & Test â select a subscriber group 1881- **Platform Admin:** Click **Connect** on the MailerLite card â enter credentials â select a group 1882 1883When connected, member data syncs to your selected MailerLite group. Only one email marketing integration (Mailchimp or MailerLite) can be active at a time. 1884 1885To disconnect: use the **â¯** menu on the MailerLite card â Disconnect. 1886 1887### MemberClicks (Data Import) 1888 1889Import members from a MemberClicks account: 1890 1891- **Platform Admin only:** Click **Connect** on the MemberClicks card â enter your Org ID, Client ID, and Client Secret â Connect 1892 1893Once connected, go to the **MemberClicks Import** page to map fields, configure type/status mappings, and run imports. See the **MemberClicks Integration** article for detailed instructions. 1894 1895To disconnect: use the **â¯** menu on the MemberClicks card â Disconnect. 1896 1897### Email Provider (AWS SES) 1898 1899Configure your email sending credentials: 1900 1901- **Settings page:** Enter your AWS SES Region, Access Key ID, Secret Access Key, From Email, and From Name â Save & Test 1902- **Platform Admin:** Click **Connect** on the Email Provider card â enter credentials 1903 1904The system validates the connection by sending a test email. Without a configured email provider, no automated emails will be sent. 1905 1906## Branding 1907 1908Customize your society's appearance: 1909 1910### Logo 1911- Upload your society logo (PNG, JPEG, or WebP â recommended 200x200px) 1912- Drag and drop or click to browse 1913- The logo appears in emails and the member portal 1914- Click the delete button to remove the current logo 1915 1916### Favicon / Browser Icon 1917- Upload a square image (PNG, JPEG, or WebP â at least 192x192px) 1918- Drag and drop or click to browse 1919- Replaces the default browser tab icon and mobile homescreen icon with your society's brand 1920- The favicon updates instantly across all admin and portal pages 1921- Click the delete button to revert to the default icon 1922 1923### Primary Color 1924- Set your society's brand color using the color picker 1925- This color is applied to the member portal (buttons, header, links) 1926- Click **Save Color** to apply 1927 1928## Email Automations (Kill Switch) 1929 1930The **Email Automations** card at the top of the General tab lets you instantly pause all outgoing emails. When toggled off, every automated email (renewals, receipts, welcome, dunning, etc.) is blocked. Emails triggered while paused are logged as FAILED and are not retried. Toggle back on to resume. See the **Pausing Email Automations** article for full details. 1931 1932## Invoice Settings 1933 1934Configure invoice-specific settings like:
1935- **Check Payable To** â Name that appears on invoices for check payments 1936 1937These settings are configured in the platform admin under your society's configuration. 1938 1939## Demo Data 1940 1941Load sample data to preview how the dashboard and reports look with real content: 1942 19431. On the Settings page, open the **API & demo data** tab and find the **Demo Data** card 19442. Click **Load Demo Data** â this creates ~200 sample members with payments, events, polls, committees, and announcements 19453. Visit the **Dashboard** to see all widgets populated with realistic data 19464. When you're done, click **Clear Demo Data** from the amber banner on the Dashboard (or from Settings) 1947 1948Demo data uses \`[email protected]\` emails and \`[Demo]\` prefixed names, so it never conflicts with real data. Clearing removes everything permanently. Loading demo data is only available before a society has real member data â once real members exist, the option is disabled.`},{id:"27",slug:"loading-demo-data",title:"Loading Demo Data",category:"getting-started",summary:"Populate your dashboard with sample members, payments, and events for demos.",keywords:["demo","sample","test","seed","data","preview","dashboard","widgets"],order:3,content:`Load realistic sample data to see how the dashboard looks with active members, payments, and engagement features. 1949 1950## Loading Demo Data 1951 19521. Go to **Settings** (under the Admin group in the sidebar) 19532. Find the **Demo Data** card 19543. Click **Load Demo Data** 1955 1956This creates approximately: 1957- **200 members** â distributed across Active, Grace, Lapsed, Expired, and Pending statuses with realistic names, cities, and membership dates spanning 1-5 years 1958- **Payments** â initial and renewal payments spread across the current and previous year, with ~3% failed payments for realism 1959- **Invoices** â linked to each successful payment (using DEMO- prefix numbers) 1960- **5 events** â mix of upcoming and past events with registrations from ~70 members 1961- **3 polls** â with questions and 40-80 responses each 1962- **3 committees** â with members, roles, open positions, and applications 1963- **3 announcements** â sample portal announcements 1964- **2 donation campaigns** â with goal amounts 1965 1966## Viewing Demo Data 1967 1968After loading, visit the **Dashboard** to see all widgets populated: 1969- Stats cards with year-over-year comparisons 1970- Revenue pacing chart with monthly trends 1971- Renewal progress ring 1972- Membership matrix by type and status 1973- Expiring members list 1974 1975An **amber banner** appears at the top of the Dashboard whenever demo data is active, showing counts and a Clear button. 1976 1977## Clearing Demo Data 1978 1979You can clear demo data from two places: 1980- The **amber banner** at the top of the Dashboard 1981- The **Demo Data** card on the Settings page's **API & demo data** tab 1982 1983Clicking **Clear Demo Data** shows a confirmation dialog. Once confirmed, all demo records are permanently deleted. Real data is never affected. 1984 1985## What Demo Data Does NOT Include 1986 1987- No Stripe payment intents (payments are recorded without Stripe) 1988- No emails are sent 1989- No real invoice counter incrementing (uses DEMO- prefix) 1990- No event-app pushes 1991 1992## How Demo Data Is Identified 1993 1994- Members: \`[email protected]\` through \`[email protected]\` 1995- Events, polls, committees, announcements, and campaigns: names prefixed with \`[Demo]\` 1996- Invoices: numbered \`DEMO-YYYY-NNNN\` 1997 1998This means demo data never interferes with real members or records.`},{id:"38",slug:"guided-product-tour",title:"Guided Product Tour",category:"getting-started",summary:"Take a step-by-step tour highlighting key features of your dashboard.",keywords:["tour","guided","walkthrough","onboarding","tutorial","first time","getting started","help"],order:4,content:`A guided tooltip tour walks you through the key features of your admin dashboard the first time you log in. The member portal has its own tour for members. 1999 2000## How It Works 2001 2002On your first visit to the admin dashboard, a welcome dialog asks if you'd like a quick tour. Click **Start tour** to begin, or **Skip** to dismiss it. 2003 2004The tour highlights one element at a time with a spotlight overlay and a tooltip explaining what it does. Use **Next** to advance, **Back** to revisit a step, or **Skip** to end early. You can also use keyboard shortcuts: **Arrow Right** or **Enter** to advance, **Arrow Left** to go back, and **Escape** to close. 2005 2006## Admin Tour Steps 2007
2008The admin tour covers: 2009 20101. **Dashboard Overview** â stats cards showing members, revenue, and expirations 20112. **Sidebar Navigation** â accessing Members, Finance, Commerce, Engagement, and Admin sections 20123. **Quick Member Search** â searching by name or email from the header 20134. **Society Switcher** â switching between societies (super admins only) 20145. **Members** â the member list for viewing and managing members 20156. **Settings** â society configuration, Stripe, emails, and integrations 20167. **Events & Commerce** â events, products, and donations (when commerce is enabled) 2017 2018Desktop-only elements (sidebar, search, switcher) are automatically skipped on mobile. 2019 2020## Member Portal Tour 2021 2022Portal members also see a tour on their first visit. It walks through: 2023 20241. **Membership Hub** â welcome banner and status 20252. **Stats Row** â tenure, renewal countdown, and streak 20263. **Navigation & Account Menu** â top menu and account dropdown (desktop) 20274. **News & Polls** â announcements and voting 20285. **Upcoming Events** â browsing and registering for events 20296. **Membership Details** â type, dates, and auto-renew toggle 20307. **Donations** â supporting active campaigns 20318. **Quick Actions** â profile, payments, invoices, and subscription links 2032 2033Members can retrigger the tour from **My Account â Take a Tour** in the portal header. 2034 2035## Retaking the Tour 2036 2037### Admin 2038Click the **Take a Tour** button in the top-right corner of this Help Center page. You'll be redirected to the dashboard where the tour will start again. 2039 2040### Portal Members 2041Open the **My Account** dropdown (or the mobile menu) and click **Take a Tour**. 2042 2043## Technical Details 2044 2045- Tour completion is stored in your browser's localStorage â clearing browser data will re-trigger the tour 2046- Steps targeting elements that aren't visible (e.g., commerce features when disabled) are automatically skipped 2047- The tour never appears in Platform Admin mode`},{id:"32",slug:"feature-module-toggles",title:"Enabling & Disabling Feature Modules",category:"settings",summary:"Turn on or off Commerce, Committees, Mailchimp, and MailerLite modules per society.",keywords:["module","feature","toggle","enable","disable","commerce","committee","mailchimp","mailerlite","hide"],order:6,content:`Feature modules let platform admins enable or disable entire feature areas per society. 2048 2049## Available Modules 2050 2051| Module | What It Controls | 2052|--------|-----------------| 2053| **Commerce** | Events, Products, Donations, Orders â both admin pages and portal shopping | 2054| **Committees** | Committee management, openings, and applications | 2055| **Mailchimp** | Mailchimp integration and sync configuration | 2056| **MailerLite** | MailerLite integration and sync configuration | 2057 2058## Toggling Modules 2059 20601. Go to **Platform > Societies > [Society] > Settings** 20612. Open the **Features** tab. Each feature shows what it needs (for example, Commerce needs Stripe) and links to where to set it up 20623. Toggle each feature on or off 20634. Click **Save changes** 2064 2065## What Happens When a Module Is Off 2066 2067- **Admin sidebar:** Related navigation items are hidden 2068- **Admin pages:** Visiting a disabled module's URL redirects to the dashboard 2069- **Portal:** Related widgets, pages, and navigation items are hidden 2070- **Settings:** Module-specific configuration sections are hidden (e.g., Mailchimp settings) 2071- **Data:** Existing data is preserved â nothing is deleted. Tur
2071ning a module back on restores everything 2072 2073## Default State 2074 2075All modules default to **enabled** for backward compatibility. New societies should have modules explicitly configured based on the customer's needs. 2076 2077## Use Cases 2078 2079- **Simple societies** that only need membership management can disable Commerce and Committees 2080- **Trial accounts** can start with basic features and enable Commerce later 2081- **Societies without email marketing** can disable Mailchimp to declutter the admin UI`},{id:"33",slug:"saving-payment-methods",title:"Saved Payment Methods",category:"payments",summary:"How members save cards for one-click checkout on future purchases.",keywords:["card","saved","payment method","one-click","checkout","update card","stripe"],order:5,content:`Members can save a payment card for faster checkout on future purchases. 2082 2083## How Members Save a Card 2084 20851. Member logs in to the **portal** 20862. Goes to **My Account** or clicks **Update Payment Method** 20873. Enters card details via the secure Stripe form 20884. Clicks **Save** 2089 2090The card is securely stored by Stripe â your system only sees the brand, last 4 digits, and expiry. 2091 2092## One-Click Checkout 2093 2094When a member with a saved card goes to checkout: 2095 20961. Their saved card is shown (e.g., "Visa ending in 4242, expires 12/28") 20972. They can click **Pay with Saved Card** for instant payment 20983. Or choose **Use a Different Card** to enter new details 2099 2100This works for events, products, donations, and membership renewals. 2101 2102## Auto-Renewal 2103 2104Saved cards are also used for auto-renewal: 2105- When a member enables auto-renewal, their saved card is charged automatically before expiry 2106- If the card fails, the dunning process kicks in with 3 retry attempts 2107 2108## Updating a Card 2109 2110Members can update their saved card at any time: 21111. Go to **My Account** in the portal 21122. Click **Update Payment Method** 21133. Enter the new card details 21144. The old card is replaced 2115 2116## Admin Visibility 2117 2118Admins can see: 2119- Whether a member has a card on file (member detail page) 2120- Card brand and last 4 digits 2121- Admins cannot see full card numbers (Stripe handles all sensitive data) 2122 2123## Security 2124 2125- Card data is never stored in your system â it's handled entirely by Stripe 2126- Members authenticate via their portal login before updating cards 2127- Card details are transmitted over encrypted connections directly to Stripe`},{id:"39",slug:"quickbooks-export",title:"Exporting to QuickBooks",category:"payments",summary:"Export payment data as a QuickBooks-compatible CSV for easy import into your accounting software.",keywords:["quickbooks","export","csv","accounting","treasurer","finance","payments","import"],order:6,content:`Export your payment data in a QuickBooks-compatible CSV format that can be imported directly into QuickBooks or other accounting software. 2128 2129## How to Export 2130 21311. Go to **Payments** in the sidebar 21322. Optionally set **From** and **To** date filters to limit the export range 21333. Click the **Export** dropdown in the top-right corner 21344. Select **QuickBooks CSV** 2135 2136The CSV file downloads immediately. You can also use **Export CSV** or **Export Excel** for the standard payment export format. 2137 2138## QuickBooks CSV Columns 2139 2140The export includes these columns, formatted for QuickBooks import: 2141 2142| Column | Description | 2143|--------|-------------| 2144| **Date** | Payment date (YYYY-MM-DD) | 2145| **Name** | Member's full name | 2146| **Email** | Member's email address | 2147| **Description** | Account type + member name (e.g., "Membership Dues â John Smith") | 2148| **Account** | QuickBooks account name (see mapping below) | 2149| **Amount** | Net payment amount (after discounts) | 2150| **Payment Method** | How payment was made (Stripe, check, etc.) | 2151| **Reference** | Payment reference number or Stripe PaymentIntent ID | 2152| **Invoice Number** | Associated invoice number, if one exists | 2153| **Status** | Payment status (always "succeeded" for this export) | 2154 2155## Account Mapping 2156 2157Payments are automatically mapped to QuickBooks account names based on payment type: 2158 2159| Payment Type | Default Account | 2160|-------------|----------------| 2161| Initial, Renewal, Auto-Renewal, Upgrade, Manual | Membership Dues | 2162| Event Registration | Event Revenue | 2163| Product Purchase | Product Sales | 2164| Donation | Donations |
2165| Other | Other Revenue | 2166 2167## Custom Account Names 2168 2169Platform admins can customize the account names per society to match your QuickBooks chart of accounts. Contact your platform admin to configure custom mappings. 2170 2171## What's Included 2172 2173- **Only succeeded payments** are included â failed, pending, and refunded payments are excluded 2174- Date range filters from the Payments page are respected 2175- If no date range is set, all succeeded payments are exported 2176 2177## Importing into QuickBooks 2178 21791. Open QuickBooks 21802. Go to **File > Utilities > Import > Excel/CSV files** (QuickBooks Desktop) or **Banking > Upload transactions** (QuickBooks Online) 21813. Select the downloaded CSV file 21824. Map the columns to your QuickBooks fields 21835. Review and accept the import 2184 2185## Tips 2186 2187- Export monthly for easier reconciliation 2188- The **Account** column maps directly to your QuickBooks chart of accounts 2189- Use the **Invoice Number** column to cross-reference with your AMS invoices 2190- The **Reference** column helps trace payments back to Stripe transactions`},{id:"34",slug:"member-portal-overview",title:"Member Portal Overview",category:"members",summary:"What members see and can do in their self-service portal.",keywords:["portal","member","self-service","login","magic link","password","passkey","account","profile","renew","invoice","dashboard","feedback"],order:8,content:`The member portal is a self-service area where members manage their account, pay invoices, renew memberships, and access society features. 2191 2192## Accessing the Portal 2193 2194Members can log in to the portal via: 2195 2196- **Email + Password** â Standard login 2197- **Magic Link** â Passwordless login via an emailed sign-in link (valid for 4 hours) 2198- **Passkey** â Biometric login (Face ID, fingerprint, Windows Hello) â no password needed. See the **Passkeys** article for setup instructions. 2199 2200The portal URL follows the pattern: yoursite.com/{society-slug}/portal 2201 2202### Magic Link Login 2203 2204Members who prefer not to use a password can request a magic link: 2205 22061. On the login page, click **Sign in with Magic Link** 22072. Enter their email address 22083. A sign-in link is sent to their inbox 22094. Clicking the link logs them in automatically 2210 2211Magic links expire after 4 hours. 2212 2213### Forgot Password 2214 2215If a member forgets their password: 2216 22171. Click **Forgot Password** on the login page 22182. Enter their email address 22193. A reset link is sent (valid for 24 hours) 22204. Click the link and set a new password 2221 2222Members whose accounts have no password (e.g., imported records) receive a 2223secure sign-in link (valid for 4 hours) instead â same request, no dead end. 2224 2225Password requirements: minimum 8 characters with at least 1 uppercase letter, 1 lowercase letter, and 1 number. 2226 2227## Portal Dashboard 2228 2229After logging in, members see their personalized dashboard with: 2230 2231- **Membership status** â Current status, type, and expiry date 2232- **Tenure badge** â Milestone recognition (5, 10, 15, 20, 25 years) 2233- **Renewal streak** â Consecutive years of membership 2234- **Lifetime savings** â Cumulative discounts from member pricing and auto-renew discounts 2235- **Badges** â Visual recognition awards assigned by admins 2236- **Upcoming events** â Next 3 events with registration status 2237- **Announcements** â Society news and updates 2238- **Active polls** â Polls awaiting their response 2239 2240## Self-Service Features 2241 2242### Update Profile 2243Members can edit their contact information (phone, address, city, state, postal code) and custom fields from **My Account**. 2244 2245### Change Email 2246Members can change their email address with two-step verification: 22471. Request change â verification code sent to the new email 22482. Enter the code to confirm 2249 2250### Renew Membership 2251Members can renew from the portal dashboard: 22521. Click **Renew Membership** 22532. Review the renewal amount (discounts applied if auto-renew is enabled) 22543. Enter payment details or use a saved card 22554. Confirm payment 2256 2257### Pay Invoices 2258Members can view and pay open invoices: 22591. Go to **Invoices** in the portal 22602. Click **Pay** on any unpaid (sent) invoice 22613. Enter payment details or use a saved card 22624. Download paid invoices as PDF 2263 2264### Update Payment Method 2265Members can add or update their saved card: 22661. Go to **My Account** 22672. Click **Update Payment Method** 22683. Enter new card details via the secure Stripe form 2269 2270### Toggle Auto-Renewal 2271Members can enable or disable auto-renewal from their account settings. When enabled, their saved card is charged automatically before expiry. 2272 2273### Register for Events (Wizard) 2274When a member opens an event, they walk through a multi-step wizard rather than a modal dialog. See [Portal Event Registration Wizard](/help/portal-registration-wizard) for the full flow: role selector, add-on children, contact step, per-event form fields, running total. Free-membership-offer, account-matching, and renewal-at-checkout panels appear in this wizard when applicable. 2275 2276## Account Security 2277 2278- **Failed login lockout** â 5 failed attempts locks the account for 15 minutes 2279- **Portal access** â Members with Pending, Rejected, or Suspended status cannot access the portal 2280- **Token-based auth** â Portal uses Bearer tokens (separate from admin cookies) 2281 2282## What Admins Should Know 2283 2284- Portal login activity appears in the **Audit Log** 2285- Members cannot change their name or membership type â only admins can 2286- Custom fields marked "show on profile" are editable by the member 2287- The portal respects **feature module toggles** â disabled modules hide their portal pages 2288 2289## Feedback Widget 2290 2291A floating feedback button appears on every portal page. Members can submit feedback, suggestions, or bug reports directly to platform admins. Submissions include the member's name, email, and the page they were on. Platform admins can view all feedback from **Platform Admin > Feedback**.`},{id:"35",slug:"managing-custom-fields",title:"Managing Custom Fields",category:"settings",summary:"Create custom data fields for member profiles, signup forms, and directories.",keywords:["custom","field","form","dropdown","checkbox","signup","profile","directory","data"],order:7,content:`Custom fields let you collect and store additional member data beyond the standard fields, without any code changes. 2292 2293## Accessing Custom Fields 2294 2295Custom fields are managed on the society's platform settings: **Platform > Societies > [Society] > Settings > Customization**. From **Registration forms** in your workspace you can also save a new form question as a custom profile field. 2296 2297## Creating a Custom Field 2298 22991. Click **Add Field** 23002. Configure the field: 2301 - **Label** â Display name shown on forms (e.g., "Board Certification Number") 2302 - **Field Key** â Unique identifier, auto-generated from label (cannot be changed after creation) 2303 - **Type** â Select the input type (see below) 2304 - **Placeholder** â Hint text inside the input 2305 - **Help Text** â Description shown below the field 23063. Set visibility options (see below) 23074. Save 2308 2309## Field Types 2310 2311| Type | Use Case | 2312|------|----------| 2313| Text | Single-line text (names, IDs, etc.) | 2314| Text Area | Multi-line text (bios, notes) | 2315| Number | Numeric values (years of experience, etc.) | 2316| Date | Date picker | 2317| Dropdown | Single selection from a list of options |
2318| Multi-Select | Multiple selections from a list | 2319| Checkbox | Yes/no toggle | 2320| Email | Email address with validation | 2321| Phone | Phone number | 2322| URL | Web address with validation | 2323 2324For **Dropdown** and **Multi-Select** types, you'll define the list of options when creating the field. 2325 2326## Visibility Settings 2327 2328Control where each field appears: 2329 2330| Setting | Where It Shows | 2331|---------|---------------| 2332| **Show on Signup** | Public signup form â new members fill it in | 2333| **Show on Profile** | Portal My Account page â members can edit it | 2334| **Show in Directory** | Member directory listing (if directory is enabled) | 2335 2336## Validation 2337 2338- **Required** â Toggle to make the field mandatory 2339- **Validation Rules** â Set minimum length, maximum length, or regex patterns for text fields 2340 2341## Membership Type Restrictions 2342 2343Optionally restrict a field to specific membership types. For example, a "Board Certification" field might only apply to Professional members, not Student members. 2344 2345## Conditional Logic 2346 2347Show or hide a field based on another field's value. For example, show "Specialty Area" only when "Board Certified" checkbox is checked. 2348 2349## Display Order 2350 2351Use the display order number to control the sequence of fields on forms. Lower numbers appear first. 2352 2353## Editing and Deleting 2354 2355- **Edit** â Change the label, help text, validation, and visibility. The field key and type cannot be changed after creation. 2356- **Delete** â Soft-deletes the field. Existing member data for that field is preserved but no longer displayed. 2357- **Toggle Active** â Deactivate a field to hide it without deleting 2358 2359## Where Custom Field Data Appears 2360 2361- **Admin member detail** â Custom fields section on the member profile 2362- **Admin member form** â When adding or editing a member 2363- **Signup form** â Fields marked "Show on Signup" 2364- **Portal profile** â Fields marked "Show on Profile" 2365- **CSV Export** â Custom fields are included in member exports`},{id:"36",slug:"using-member-notes",title:"Using Member Notes",category:"members",summary:"Add timestamped notes to member profiles for internal tracking.",keywords:["note","comment","admin","internal","history","re
2365cord","member"],order:9,content:`Member notes let admins keep an internal record of interactions, decisions, and follow-ups on any member's profile. 2366 2367## Adding a Note 2368 23691. Open a member's profile from the Members list 23702. Scroll to the **Notes** section 23713. Type your note in the text box 23724. Click **Add Note** 2373 2374The note is saved immediately with your name and a timestamp. 2375 2376## Viewing Notes 2377 2378Notes appear in reverse chronological order (newest first) on the member's profile. Each note shows: 2379 2380- **Author** â The admin who wrote it 2381- **Date/Time** â When it was created 2382- **Content** â The note text 2383 2384Notes are paginated â scroll down or click "Load more" for older notes. 2385 2386## Deleting a Note 2387 2388Only the original author (or a super admin) can delete a note: 2389 23901. Find the note you want to remove 23912. Click the **Delete** button 23923. Confirm deletion 2393 2394Deleted notes are soft-deleted and logged in the audit trail. 2395 2396## Notes Are Internal Only 2397 2398- Notes are **not visible** to members in the portal 2399- Notes **do not** appear in exports or reports 2400- Notes **are** logged in the audit trail for accountability 2401 2402## When to Use Notes 2403 2404- **Phone call summaries** â "Called about renewal, will send check by Friday" 2405- **Special arrangements** â "Approved 50% discount per board vote 1/15" 2406- **Follow-up reminders** â "Needs updated mailing address" 2407- **Application context** â "Referred by Dr. Smith, approved" 2408- **Issue tracking** â "Card declined twice, switching to check payment" 2409 2410## Tips 2411 2412- Keep notes factual and professional â they're part of the audit trail 2413- Use notes instead of trying to remember conversations 2414- Notes cannot be edited after creation â add a follow-up note instead`},{id:"37",slug:"event-app-integration",title:"Event-App Integration",category:"integrations",summary:"Import events from your event app, push attendees, and enable member SSO.",keywords:["event app","import","sync","push","attendee","SSO","integration","registration"],order:5,content:`If your society uses a separate event app, you can connect it to import events, automatically push registered attendees, and give members single sign-on access. 2415 2416## Setting Up the Connection 2417 2418The event-app integration is configured by platform admins: 2419 24201. Go to **Platform > Societies > [Society] > Settings** 24212. Open the **Integrations** tab and choose **Connect** on the Event App card 24223. Enter: 2423 - **Base URL** â Your event app's tenant URL (e.g., https://fgs.gievents.org/events) 2424 - **Import API Key** â Shared API key for authentication 2425 - **AMS API key** (optional) â the key Event App uses to call AMS, e.g. for delegated email sending 24264. Click **Connect** 2427 2428## Creating Events 2429 2430Events are created in AMS first and automatically pushed to the event app. You do not create events in the event app â AMS is the authoritative source. 2431 24321. Go to **Events** in the sidebar (under Commerce) 24332. Click **Create Event** 24343. Fill in the event name, dates, venue/address, time zone, description, and pricing 24354. In the **Event App slug** field, type a URL-safe slug (e.g. \`2026am\`). On save, AMS creates a matching event-app record with this slug. 24365. Leave **Event App slug** blank for commerce-only events that don't need an event-app presence (landing page, sessions, Q&A, etc.) 24376. Click **Create** to save 2438 2439After save, AMS pushes the event metadata (name, dates, venue, address, timezone, status, parent event linkage, registration URL) to the event app. Failed pushes retry automatically every 10 minutes; the admin UI shows a "Last sync failed" banner and a "Sync to event-app" button for manual retry. 2440 2441## Automatic Attendee Push 2442 2443When a member registers and pays for an imported event: 2444 24451. Payment is confirmed in AMS 24462. AMS automatically pushes the attendee to the event app 24473. The member appears in the event app's attendee list 2448 2449### Push Status 2450 2451On the event's registrations list, each registration shows its push status: 2452 2453- **Pushed** (green) â Successfully sent to event app 2454- **Failed** (red) â Push failed, with a **Retry** button 2455- **Pending** (gray) â Not yet attempted 2456 2457Failed pushes are automatically retried every 30 minutes by a background job. You can also retry manually by clicking the retry button. 2458 2459The event's [Event dashboard](/help/event-dashboard) rolls these up into an **Event app sync** card â pushed/pending/failed counts for the whole event family, with per-row retry. 2460 2461### Guest Support 2462 2463Both members and guest registrants (non-members who purchase event tickets) are pushed to the event app. 2464 2465## Member SSO (Single Sign-On) 2466 2467Members can access the event app directly from their portal without logging in separately: 2468 24691. Member logs in to the portal 24702. Goes to the **Upcoming Events** widget on their dashboard 24713. Clicks **Open** on a registered event 24724. They're automatically signed into the event app 2473 2474SSO uses a short-lived token (5 minutes) generated by AMS and verified by the event app. 2475 2476## Admin Link Generation 2477
2478On the Events admin page, each event has a **link icon** button that copies the direct registration URL. Share this link on your website or in emails to let visitors register directly for a specific event.`},{id:"43",slug:"registration-form-templates",title:"Registration Form Templates",category:"commerce",summary:"Create reusable form templates to collect attendee information during event registration.",keywords:["registration","form","template","field","custom field","event","attendee","profile"],order:6,content:`Build reusable registration forms that collect attendee information when members sign up for events. 2479 2480## Overview 2481 2482The **Registration forms** page (under Commerce in the sidebar) lets you manage two things: 2483 24841. **Form Templates** â Reusable configurations of fields that you assign to events 24852. **Field Library** â Individual field definitions available across all templates 2486 2487When you assign a template to an event, the field configuration is copied onto the event. This means you can update templates without affecting events that already use them. 2488 2489## Managing the Field Library 2490 2491Fields are the building blocks of your forms. Each field has: 2492 2493- **Label** â What the attendee sees (e.g., "Job Title") 2494- **Field Key** â Internal identifier (e.g., "job_title") â must be unique 2495- **Field Type** â Text, textarea, dropdown, multi-select, checkbox, number, date, email, phone, or URL 2496- **Options** â For dropdown and multi-select fields, the list of choices (one per line) 2497- **Help Text** â Optional hint shown below the field 2498- **Placeholder** â Optional placeholder text inside the input 2499 2500### Two Types of Fields 2501 2502The field library shows two sections: 2503 2504- **Registration Fields** â Fields specific to event registration (from the Field Library) 2505- **Profile Fields** â Custom fields from your member profile system. Using profile fields on registration forms lets you capture missing profile data during event signup. When a member registers, their responses are automatically saved back to their profile. 2506 2507### Creating a Field 2508 25091. Click **Create Field** in the Field Library section 25102. Fill in label, field key, type, and any options 25113. Click **Create** 2512 2513## Creating a Form Template 2514 25151. Click **Create Template** 25162. Enter a template name and optional description 25173. In the editor, click **Add from Library** and select fields 25184. Reorder fields using the drag handles 25195. Toggle **Required** on any field that must be filled out 25206. Click **Save** 2521 2522### Duplicating a Template 2523 2524Click the **copy icon** on any template to create a duplicate with "(Copy)" appended to the name. Edit the copy to customize it. 2525 2526## Assigning a Template to an Event 2527 25281. Go to **Events** and create or edit an event 25292. In the **Registration Form** section, select a template from the dropdown 25303. The template's fields are copied onto the event 25314. Save the event 2532 2533After saving, the portal will show the registration form when members add the event to their cart. 2534 2535## How It Works for Members 2536 2537When a member clicks "Add to Cart" on an event with a registration form: 2538 25391. A form dialog appears with the configured fields 25402. Known information (name, email, phone, etc.) is **automatically pre-filled** from their profile 25413. The member fills in any remaining fields and submits 25424. The event is added to their cart with the form responses attached 25435. After payment, responses are saved with the registration record 25446. Any profile field responses are automatically written back to the member's profile 2545 2546## Tips 2547 2548- Use **profile fields** for information you want to reuse across the system (organization, credentials, dietary restrictions) 2549- Use **registration fields** for event-specific questions (session preferences, meal choice for this event) 2550- Keep forms short â only ask for what you actually need 2551- Required fields are enforced at checkout, so members can't skip them`},{id:"58",slug:"data-security-backups",title:"Data Security & Backups",category:"settings",summary:"How your society data is protected, backed up, and recoverable.",keywords:["security","backup","data","protection","recovery","database","tenant","isolation"],order:10,content:`Your society's data is protected by multiple layers of security and backup systems. 2552 2553## Tenant Isolation 2554 2555Each society's data is completely isolated. Admin users can only access data belonging to their assigned society. This isolation is enforced at every API endpoint and audited by an automated tenant guard system that monitors all database queries. 2556 2557## Automated Backups 2558 2559Your data is backed up automatically on multiple schedules: 2560 2561- **Daily database snapshots** â Full database backup every night, retained for 7 days (plus 4 weekly snapshots) 2562- **Continuous write-ahead log (WAL) archiving** â Every database change is archived in near-real-time, enabling recovery to any point in t
2562ime within the last 28 days 2563- **Weekly base backups** â Full binary-level database backup for point-in-time recovery 2564 2565## Backup Verification 2566 2567Backups are automatically tested every week. The verification process restores the latest backup into a temporary database and validates that all tables, societies, users, and key data relationships are intact. If verification fails, the platform team is alerted immediately. 2568 2569## Data Recovery 2570 2571In the unlikely event of data loss, the platform team can restore your data to any point in time within the last 28 days using point-in-time recovery (PITR). For most scenarios, recovery can be completed within minutes. 2572 2573## Audit Trail 2574 2575All significant actions (member changes, payments, settings updates, login attempts) are recorded in the Audit Log. See the **Using the Audit Log** article for details.`},{id:"42",slug:"configuring-custom-domain",title:"Configuring a Custom Domain",category:"integrations",summary:"Set up a custom domain so members access the portal at your own URL instead of ams.korevera.com.",keywords:["domain","custom domain","white-label","DNS","CNAME","branding","portal","URL","SSL"],order:11,content:`Give your society a professional, branded portal URL like \`members.yoursociety.org\` instead of the default \`ams.korevera.com/your-slug/portal\`. 2576 2577## How It Works 2578 2579When you configure a custom domain, we provision an SSL certificate through Cloudflare so your members get a secure \`https://\` connection. You add a DNS record at your domain provider, and once it propagates, the portal is live on your domain. 2580 2581## Setting Up a Custom Domain 2582 25831. Go to **Platform Admin â Societies â [Society] â Settings** for the society you want to configure 25842. Scroll down to the **Custom Domain** card on the **General** tab 25853. Enter the domain you want to use (e.g., \`members.yoursociety.org\`) 25864. Click **Configure** 2587 2588After configuring, you'll see CNAME instructions with a target value to copy. 2589 2590## Adding the DNS Record 2591 2592At your DNS provider (GoDaddy, Namecheap, Cloudflare, etc.): 2593 25941. Go to DNS management for your domain 25952. Add a new **CNAME** record: 2596 - **Name / Host:** The subdomain part (e.g., \`members\` if your domain is \`members.yoursociety.org\`) 2597 - **Target / Value:** The value shown in the CNAME instructions (e.g., \`custom.korevera.com\`) 25983. Save the record 2599 2600## Waiting for Activation 2601 2602After adding the DNS record: 2603 2604- DNS propagation can take **a few minutes to 24 hours** depending on your provider 2605- Click **Check Status** on the Custom Domain card to see if Cloudflare has detected your CNAME 2606- Once detected, SSL is provisioned automatically (usually within minutes) 2607- The status badge will change from **Pending** (amber) to **Active** (green) 2608 2609## Testing 2610 2611Once the status shows Active, visit your custom domain: 2612 2613\`https://members.yoursociety.org/portal\` 2614 2615Members will see the same portal experience â login, dashboard, payments, directory â all on your branded URL. 2616 2617## Removing a Custom Domain 2618 2619Click **Remove** on the Custom Domain card and confirm. This deletes the Cloudflare hostname and reverts the society to the default \`ams.korevera.com\` URL. Members using the old custom domain will no longer be able to access the portal there. 2620 2621## Troubleshooting 2622 2623- **Status stays Pending:** Double-check the CNAME record at your DNS provider. Make sure the target matches exactly. Some providers add a trailing dot â that's normal. 2624- **SSL errors in browser:** Wait a few more minutes after status shows Active. The certificate may still be deploying to edge servers. 2625- **"Domain not found" error:** The custom domain must be configured in our system first (step 3 above) before the DNS record will work.`},{id:"40",slug:"passkeys",title:"Passkeys (Biometric Login)",category:"settings",summary:"Set up passkeys to sign in with Face ID, fingerprint, or Windows Hello instead of a password.",keywords:["passkey","passkeys","biometric","face id","fingerprint","windows hello","webauthn","login","security","authentication"],order:12,content:`Passkeys let you sign in with the biometrics you already use on your device â Face ID, fingerprint, or Windows Hello â instead of typing a password. 2626 2627## What Are Passkeys? 2628 2629Passkeys are a modern, phishing-resistant replacement for passwords. When you register a passkey, your device creates a unique cryptographic key pair. The private key stays on your device (or syncs via iCloud/Google), and the public key is stored on our server. To sign in, your device proves it holds the private key using biometrics â no password is transmitted or stored. 2630 2631## Setting Up a Passkey 2632 2633### For Admin Users 2634 26351. Open your account menu (your initials, top right) and choose **Your account** 26362. Find the **Passkeys** card 26373. Click **Register new passkey** 26384. Enter a name for this passkey (e.g., "iPhone 15" or "MacBook Pro") 26395. Follow your browser's prompts to complete biometric verification 2640 2641### For Portal Members 2642 26431. Log in to the member portal 26442. Go to **Profile** 26453. Scroll to the **Passkeys** card 26464. Click **Register new passkey** 26475. Name it and complete biometric verification 2648 2649## Signing In with a Passkey 2650 2651On the login page, click **Sign in with Passkey** (below the password form for admins, or above the login tabs for portal members). Your browser will prompt you to verify with your biometric. That's it â no password needed. 2652 2653> **Note:** The passkey button only appears in browsers that support passkeys (most modern browsers do). 2654 2655## Managing Your Passkeys 2656 2657From the Passkeys card on **Your account** (admins) or **Profile** (members), you can: 2658 2659- **View** all registered passkeys with their names and last-used timestamps 2660- **Rename** a passkey by clicking the edit icon 2661- **Delete** a passkey by clicking the trash icon 2662 2663## Custom Domains & Passkeys 2664 2665Passkeys are bound to the domain where they were registered. If your society uses a custom domain (e.g., \`members.yoursociety.org\`), a passkey registered there will only work on that domain â not on \`ams.korevera.com\`, and vice versa. The domain each passkey is bound to is shown in the management card. 2666 2667If you access the portal on multiple domains, register a passkey on each one. 2668 2669## Good to Know 2670 2671- Passkeys **supplement** passwords â you can always fall back to password login 2672- You can register multiple passkeys (e.g., one for your phone, one for your laptop) 2673- Passkeys may sync across your devices via iCloud Keychain or Google Password Manager 2674- Deleting a passkey from the management card only removes it from our server â remove it from your device's password manager separately if needed`},{id:"45",slug:"email-logs-suppression",title:"Email Logs & Suppression List",category:"email",summary:"View email delivery history and manage the suppression list for bounced or c
2674omplained addresses.",keywords:["email","log","logs","suppression","bounce","complaint","blocked","delivery","ses","status"],order:4,content:`Track every email your system sends and manage addresses that have been suppressed due to bounces or complaints. 2675 2676## Email Logs 2677 2678Go to **Emails** in the sidebar and click the **Email Log** tab. 2679 2680The log shows every email sent by your society, including: 2681 2682- **Recipient** â Who the email was sent to 2683- **Subject** â The email subject line 2684- **Template** â Which template was used (welcome, invoice, renewal, etc.) 2685- **Status** â Current delivery status 2686- **Date** â When it was sent 2687 2688### Email Statuses 2689 2690| Status | Meaning | 2691|--------|---------| 2692| **Sent** | Email accepted by the mail server | 2693| **Delivered** | Confirmed delivered to the recipient's inbox | 2694| **Bounced** | Email bounced back (address invalid, mailbox full, etc.) | 2695| **Complained** | Recipient marked the email as spam | 2696| **Failed** | Email could not be sent (paused, suppressed, or cap hit) | 2697 2698### Filtering 2699 2700Use the status dropdown and date range to filter the log. Click any row to see delivery details including bounce type and error messages. 2701 2702## Suppression List 2703 2704Go to **Emails** â **Suppression List** tab. 2705 2706The suppression list contains email addresses that are automatically blocked from receiving future emails. Addresses are added when: 2707 2708- **Hard bounce** â The email address doesn't exist or permanently rejects mail 2709- **Complaint** â The recipient marked your email as spam via their email provider 2710 2711### Why Suppression Matters 2712 2713Continuing to send to addresses that bounce or complain damages your email sender reputation and can cause your emails to be blocked for all members. The suppression list protects your deliverability. 2714 2715### Viewing Suppressions 2716 2717Each entry shows: 2718- **Email address** â The suppressed address 2719- **Reason** â Hard bounce, soft bounce, or complaint 2720- **Bounce details** â The specific bounce type and sub-type 2721- **Date** â When the suppression was recorded 2722 2723### Removing a Suppression 2724 2725If you believe an address was suppressed in error (e.g., a temporary mailbox issue has been fixed): 2726 27271. Find the address in the suppression list 27282. Click **Remove** 27293. Confirm â the address can now receive emails again 2730 2731**Caution:** Only remove suppressions if you're confident the issue is resolved. Sending to a still-invalid address will create a new suppression. 2732 2733### Soft Bounces 2734 2735Soft bounces (temporary issues like a full mailbox) are logged for visibility but do NOT block future sends. Only hard bounces and complaints block emails.`},{id:"46",slug:"sending-broadcast-emails",title:"Sending Broadcast Emails",category:"email",summary:"Send one-time emails to all members or a filtered subset.",keywords:["broadcast","blast","bulk","send","email","all members","newsletter","announcement"],order:5,content:`Send a one-time email to all members or a targeted group, with full template variable support and rich text editing. 2736 2737## Sending a Broadcast 2738 27391. Go to **Emails** in the sidebar (under the Engagement group) 27402. Click the **Send Broadcast** button 27413. Fill in the broadcast form: 2742 - **Subject** â The email subject line (template variables supported) 2743 - **Body** â Use the rich text editor to compose your message, or toggle Source Mode for raw HTML 2744 - **Recipients** â Choose from preset groups (see below) 27454. Click **Preview** to see how the email will look with sample data 27465. Click **Send** to dispatch to all selected recipients 2747 2748## Recipient Groups 2749 2750| Group | Who Receives | 2751|-------|-------------| 2752| **All Active Members** | Members with Active status | 2753| **Expiring Soon** | Members expiring within 30 days | 2754| **Grace Period** | Members in grace period | 2755| **Lapsed** | Members with Lapsed status | 2756 2757## Template Variables 2758 2759Broadcast emails support the same merge fields as templates: 2760 2761- \`{{member.firstName}}\`, \`{{member.lastName}}\`, \`{{member.email}}\` 2762- \`{{membership.type}}\`, \`{{membership.expiryDate}}\` 2763- \`{{society.name}}\`, \`{{portal_url}}\` 2764 2765## Safety Features 2766 2767- **Suppression list** â Addresses that have hard-bounced or c
2767omplained are automatically skipped 2768- **Hourly send cap** â The 200/hour circuit breaker applies to broadcasts too 2769- **Kill switch** â If email automations are paused, broadcasts are also blocked 2770- **Email log** â Every broadcast email appears in the Email Log with delivery status 2771 2772## Tips 2773 2774- Always send a test email to yourself first (use the Send Test button in the template editor) 2775- Use recipient filtering to send targeted messages rather than emailing everyone 2776- Keep broadcasts concise â long emails have lower engagement 2777- Check the Email Log after sending to monitor delivery rates`},{id:"47",slug:"memberclicks-integration",title:"MemberClicks Integration",category:"integrations",summary:"Import members from MemberClicks with field mapping, type/status mapping, and incremental sync.",keywords:["memberclicks","import","integration","sync","mapping","field","migration","mc"],order:13,content:`Import your member data from MemberClicks into AMS with full field mapping, type/status translation, and ongoing incremental sync. 2778 2779## Connecting MemberClicks 2780 27811. Go to **Platform Admin > Societies > [Society] > Settings > Integrations** tab 27822. Click **Connect** on the MemberClicks card 27833. Enter your MemberClicks credentials: 2784 - **Org ID** â Your MemberClicks organization identifier 2785 - **Client ID** â OAuth client ID from MemberClicks 2786 - **Client Secret** â OAuth client secret from MemberClicks 27874. Click **Connect** â the system validates the credentials 2788 2789## Field Mapping 2790 2791After connecting, go to **MemberClicks Import** in the sidebar (under the Admin group). 2792 2793### Step 1: Map Fields 2794 2795The field mapping page shows all fields from your MemberClicks account alongside the AMS fields they map to: 2796 2797- **Standard fields** (first name, last name, email, phone, etc.) are auto-mapped 2798- **Custom fields** can be mapped to existing AMS custom fields or new ones will be created automatically 2799- Fields set to **Skip** are not imported 2800 2801### Step 2: Type Mapping 2802 2803Map MemberClicks profile types to AMS membership types: 2804 28051. Click the **Type Mapping** tab 28062. For each MC profile type, select the corresponding AMS membership type 28073. Unmapped types will use the default membership type 2808 2809### Step 3: Status Mapping 2810 2811Map MemberClicks statuses to AMS member statuses: 2812 28131. Click the **Status Mapping** tab 28142. For each MC status, select the corresponding AMS status (Active, Grace, Lapsed, etc.) 28153. Unmapped statuses default to Pending 2816 2817## Running an Import 2818 28191. Click **Preview Import** to see how many members will be created or updated 28202. Review the summary (new members, updates, skipped) 28213. Click **Import** to execute 2822 2823The import creates members, sets membership types and statuses based on your mappings, and populates custom fields. Welcome emails are NOT sent during import. 2824 2825## Incremental Sync 2826 2827After the initial import, a background job runs every 6 hours to sync changes: 2828 2829- New members added in MemberClicks are created in AMS 2830- Updated fields in MemberClicks are reflected in AMS 2831- The sync only pulls records modified since the last run 2832 2833## Tips 2834 2835- Run a preview before every import to check for unexpected results 2836- Custom fields are auto-created with snake_case keys derived from the MemberClicks field label 2837- Bracket-notation fields in MemberClicks (like email aliases or multiple addresses) need manual mapping`},{id:"48",slug:"mailerlite-integration",title:"MailerLite Integration",category:"integrations",summary:"Sync your member list with MailerLite for email marketing campaigns.",keywords:["mailerlite","email marketing","sync","integration","subscriber","group","newsletter"],order:14,content:`Connect MailerLite to automatically sync your member data for email marketing campaigns. 2838 2839## Connecting MailerLite 2840 2841### From Settings (Society Admin) 2842 28431. Go to **Settings** in the sidebar 28442. Find the **MailerLite** section 28453. Enter your MailerLite API Key (found in your MailerLite account under Integrations > API) 28464. Click **Save & Test** 28475. If the connection succeeds, select a subscriber group from the dropdown 28486. Click **Save** 2849 2850### From Platform Admin 2851 28521. Go to **Platform Admin > Societies > [Society] > Settings > Integrations** tab 28532. Click **Connect** on the MailerLite card 28543. Enter your API Key 28554. Select a subscriber group 28565. Click **Connect** 2857 2858## What Gets Synced 2859 2860When connected, the following member data syncs to your MailerLite group: 2861 2862- **Email address** (used as the unique identifier) 2863- **First name** and **last name** 2864- **Membership type** and **status** 2865 2866Members are synced when they are created, updated, or when their status changes. 2867 2868## Choosing Between Mailchimp and MailerLite 2869 2870Only one email marketing integration can be active per society. If you connect MailerLite, the Mailchimp integration is disabled, and vice versa. 2871 2872## Disconnecting 2873 2874- Disconnecting is done from the platform: on the society's **Sett
2874ings > Integrations**, open the **â¯** menu on the MailerLite card > Disconnect. Society admins can ask Korevera support to do this. 2875 2876Disconnecting stops future syncs but does not remove subscribers already in MailerLite. 2877 2878## Feature Module Toggle 2879 2880The MailerLite integration can be hidden entirely by turning off the **MailerLite** feature in Platform Admin > Societies > [Society] > Settings > Features.`},{id:"50",slug:"video-library-integration",title:"Video Library Integration",category:"integrations",summary:"Set up and manage the Video Library add-on module for your society",content:` 2881## Video Library Integration 2882 2883The Video Library is an optional paid module that gives your members access to educational video content. Videos are hosted on Bunny.net or Vimeo and managed through a separate admin interface. 2884 2885### How It Works 2886 2887When enabled, a **Video Library** widget appears on your members' portal dashboard. Clicking "Watch" seamlessly signs them into the video library using single sign-on (SSO) â no separate login required. 2888 2889**Access requirements:** 2890- Members must have an **Active** membership status 2891- Members in Grace, Lapsed, or Pending status cannot access the video library 2892- The Video Library module must be enabled for your society 2893 2894### For Admins 2895 2896A **Video library** link appears in the admin sidebar when the module is enabled. Clicking it opens the video library admin panel where you can: 2897 2898- Upload and manage videos 2899- Create collections and featured content 2900- Mark specific videos as **Public** (visible without login) 2901- Manage video metadata, transcriptions, and keywords 2902- View upload/processing status 2903 2904### Setting Up Video Library 2905 2906Video Library configuration is managed by platform administrators: 2907 29081. Go to **Platform Admin â Societies â [Your Society] â Settings â Integrations** 29092. On the **Video Library** card, choose **Connect**, then **Provision** 29103. Korevera creates the library, its address and its sign-in key, and turns the module on (the **Features** tab shows it as on) 29114. Disconnecting the card turns the module off again 2912 2913### Public Videos 2914 2915Admins can mark individual videos as "Public" in the video library admin. Public videos are visible to anyone who visits the video library URL â no login required. All other videos require an active membership. 2916 2917### Custom Domain 2918 2919Each society's video library can have its own custom domain (e.g., \`videos.yoursociety.org\`). Contact your platform administrator to set this up. 2920 2921### Troubleshooting 2922 2923**"Could not open Video Library" error:** 2924- Verify the Video Library module is enabled in Platform Admin 2925- Check that the Base URL and SSO Key are configured correctly 2926- Ensure the video library app is running and accessible 2927 2928**Members can't access:** 2929- Only members with **Active** status can access the video library 2930- Members in Grace or Lapsed status will see a 403 error 2931- Check that the member's society has the Video Library module enabled 2932 2933**Videos not showing:** 2934- In the video library admin, verify videos have "Ready" status 2935- For public visitors, only videos marked as "Public" are visible 2936- Check that the video's society matches the member's society 2937 `.trim(),keywords:["video","library","videos","bunny","vimeo","
2937streaming","sso","integration","module","public","upload"],order:12},{id:"49",slug:"portal-feedback-widget",title:"Portal Feedback Widget",category:"engagement",summary:"Collect member feedback through the floating widget on every portal page.",keywords:["feedback","widget","portal","suggestion","bug report","member feedback","floating button"],order:6,content:`A floating feedback button appears on every portal page, making it easy for members to submit feedback, suggestions, or bug reports. 2938 2939## How It Works for Members 2940 29411. Members click the **Feedback** button (floating in the bottom-right corner of any portal page) 29422. A form slides up with fields for: 2943 - **Category** â Suggestion, Bug Report, or General Feedback 2944 - **Message** â Free-text description 29453. The member's name, email, and current page URL are automatically attached 29464. Click **Submit** â a confirmation message appears 2947 2948## Viewing Feedback (Platform Admin) 2949 2950Platform admins can view all submitted feedback: 2951 29521. Go to **Platform Admin > Feedback** in the sidebar 29532. Browse feedback entries with: 2954 - **Member name and email** 2955 - **Category** (suggestion, bug, general) 2956 - **Message content** 2957 - **Page URL** where feedback was submitted 2958 - **Society** the member belongs to 2959 - **Date** submitted 2960 2961## Managing Feedback 2962 2963- Filter by category, society, or date range 2964- Click any entry to see the full message 2965- Use feedback to identify common pain points, feature requests, and portal issues 2966 2967## Visibility 2968 2969- The feedback widget is visible to all authenticated portal members 2970- It does NOT appear on login/signup pages or admin pages 2971- Feedback is only visible to platform admins, not society admins`},{id:"51",slug:"paid-renewal-at-event-checkout",title:"Renewal at Event Checkout",category:"membership",summary:"LAPSED members pay standard dues at event checkout to unlock the member event rate â all in one transaction.",keywords:["renewal","lapsed","paid renewal","renewal at event checkout","event checkout","auto-renew","member rate","refund","lapsed recovery"],order:1,content:`*Renewal at event checkout* lets a LAPSED or EXPIRED member renew their dues *during* event registration. The member sees one cart line for the event + one for the renewal, pays once, and walks out as an ACTIVE member registered at the member rate. 2972 2973## When the renewal panel appears 2974 2975The wizard's StepEvent shows a **"Renew the society membership"** panel only when ALL of these are true: 2976 2977- Per-society toggle **Renewal at event checkout** is enabled (Platform â Societies â [Society] â Settings â Features tab) 2978- The member's status is LAPSED or EXPIRED (not ACTIVE, PENDING, REJECTED, SUSPENDED) 2979- The member's current membership type is a real type â guest-type members (those on a "non-member" membership type like Guest or Visitor) route through the free-membership-offer flow instead. See [Free Membership Offer at Event Registration](/help/free-membership-offer-at-events). 2980- The membership type is paid (price > 0) and renewable (not lifetime) 2981 2982For everyone else the panel is hidden. 2983 2984## What the member sees 2985 2986- **Renew checkbox** with the renewal price (e.g., $250/yr) 2987- **Auto-renew sub-toggle** when the membership type offers an auto-renew discount (e.g., 10% off â the panel shows "$225/yr with auto-renew ($25 off â was $250/yr)") 2988- **"Save $X on this event by renewing"** chip â the dollar delta between non-member and member rate on this event, quantified 2989- Running total reflects both the event (at member rate) and the renewal cost 2990 2991If the member declines, they pay the non-member rate; the event registers normally. 2992 2993If they opt in, the order has two line items: the event (priced at member rate) and a \`MEMBERSHIP_RENEWAL\` line. On payment confirmation the member becomes ACTIVE and the new cycle dates take effect. 2994 2995## Auto-renew sub-toggle 2996 2997The auto-renew checkbox is separate from "renew now": 2998- It only appears when the membership type has \`auto_renew_enabled\` and a non-zero discount percent 2999- Enabling it stores Stripe's saved card as the default payment method for future cycles 3000- It does NOT affect whether the event drops to the member rate â that's controlled by the parent renewal opt-in alone 3001 3002## Cycle math 3003 3004For **calendar cycles** (e.g., Oct 1 â Sep 30): \`membership_start_date\` = today, \`membership_end_date\` = next-cycle-end. The gap between today and the cycle start is the early-renewal perk. So a member renewing on May 17 for a calendar cycle starting Oct 1 gets coverage immediately *and* through next September. 3005 3006For **anniversary cycles**: today â today + 1 year, minus 1 day. 3007 3008## Refunds 3009 3010Refunding a renewal payment retracts the membership only when no later renewal already covers the cycle. The system snapshots the member's previous state at cart-add (status, dates, auto-renew) and restores it on refund â no manual cleanup needed. 3011 3012Three refund paths: 3013- **Admin refund** via the admin Payments page â retracts immediately 3014- **Stripe Dashboard refund** â \`refund.created\` webhook handles it 3015- **Auto refund** from the confirm flow when the renewal can't be applied (e.g., race with another renewal) 3016 3017Partial refunds use \`Payment.refunded_amount\` and mark the payment \`PARTIALLY_REFUNDED\`. The membership stays active. 3018 3019## Audit events 3020 3021You'll see these in Audit Log when the feature is active: 3022- \`MEMBERSHIP_RENEWAL_OFFERED\` â member saw the panel 3023- \`MEMBERSHIP_RENEWAL_APPLIED\` â member became ACTIVE 3024- \`MEMBERSHIP_RENEWAL_SKIPPED\` â already-covered period (rare; defensive) 3025- \`MEMBERSHIP_RENEWAL_REFUNDED\` â admin or webhook-initiated retraction 3026- \`MEMBERSHIP_RENEWAL_AUTO_REFUNDED\` â confirm-flow auto refund 3027- \`MEMBERSHIP_RENEWAL_RECONCILED\` â Stripe webhook â DB sync after a missed confirm 3028 3029## Enabling renewal at event checkout 3030 30311. **Platform Admin** â **Societies** â click the society â **Membership** tab 30322. Toggle **Renewal at event checkout** ON â Save 30333. Verify in a LAPSED member's event registration that the panel appears 3034 3035The toggle defaults OFF on every society. Flip it on when you're ready to roll out.`},{id:"52",slug:"account-matching-for-returning-members",title:"Account Matching for Returning Members",category:"membership",summary:"Identifies returning members who sign up under a new email, lets them merge with their old record via OTP verification.",keywords:["merge","merged accounts","match history","lapsed","account matching","duplicate accounts","fuzzy match","record linkage","OTP","duplicate"],order:2,content:`*Account matching* fixes a common problem: a member's record went LAPSED, they later sign up as a "new" member with a different email, and the system creates a second row. Without intervention, the society ends up with two records for the same person â and the new row never benefits from the old member's history. 3036 3037When an authenticated non-member registers for an event with the free-membership offer enabled, account matching looks for likely-same-person LAPSED records and offers to merge them. 3038 3039## How matching works 3040 3041Pure classical record linkage â no AI. Uses the \`jellyfish\` library for Jaro-Winkler string similarity, scored with caps and floors. 3042 3043Six blocking queries run in parallel: 3044- Last name + ZIP code 3045- Normalized email (lowercased, dots stripped from Gmail) 3046- Phone last-7 digits 3047- First name + Last name (within same society) 3048- And two other narrow buckets for edge cases 3049 3050Each candidate gets a score 0.0â1.0. The portal shows masked previews of the top matches (e.g., "J. S***th · 902** · j*****@gmail.com") so the member can pick "yes, that's me" without exposing PII. 3051 3052## Verification flow 3053 3054If the member picks a candidate, the system: 3055 30561. Generates a 6-digit OTP and sends it to the **canonical** row's email (the old, LAPSED one â not the new email they're registering with) 30572. The member enters the code on a verification panel 30583. On success, **MergeService** runs a hard-merge transaction that rewrites every member-owned FK across 23 tables onto the canonical row. The shell (new) row is deleted, the new email is updated onto the canonical row, and the session cookies are rotated so the member stays logged in as the canonical identity. 3059 3060The merge is atomic â either everything succeeds or nothing changes. 3061 3062## Rate limits 3063 3064To prevent abuse:
3065- 5 OTP attempts per challenge before the challenge is invalidated 3066- 5 challenges per shell-member per hour 3067- Stale challenges expire after 15 minutes 3068- Consumed candidate tokens are single-use 3069 3070## Admin pages 3071 3072When account matching is enabled on a society, two admin pages appear in the **Admin** sidebar group (next to Audit log): 3073 3074### Merged accounts (\`/admin/members/merged\`) 3075 3076Lists every successful hard-merge. Shows: 3077- Canonical row + the shell row that was absorbed 3078- When the merge happened and by which path 3079- The matched candidate's blocking-query signature 3080 3081Use this to verify a member who calls saying "I think my account got combined" â search by either the canonical or shell name/email. 3082 3083### Match history (\`/admin/members/link-history\`) 3084 3085Broader audit feed: 3086- \`MEMBER_LINK_CANDIDATES_PROBED\` â someone hit the fuzzy match endpoint 3087- \`MEMBER_LINK_VERIFICATION_FAILED\` â OTP entered wrong 3088- \`MEMBER_LINK_VERIFICATION_RATE_LIMITED\` â too many OTP attempts 3089- \`MEMBER_LINK_MERGE_COMPLETED\` â full hard merge succeeded 3090 3091Use this to spot abuse (lots of rate-limit hits) or to debug why a merge didn't fire when expected. 3092 3093## Admin metrics 3094 3095The admin Dashboard surfaces an account-matching activity tile when the toggle is on, showing 24-hour counters for probes, verifications, failures, and completed merges. 3096 3097## Enabling account matching 3098 30991. **Platform Admin** â **Societies** â click the society â **Membership** tab 31002. Toggle **Account matching for returning members** ON â Save 31013. **Merged accounts** and **Match history** appear in the Admin sidebar group (they hide on societies without account matching enabled) 3102 3103Defaults OFF. Flip on when you're ready â the matching algorithm is reasonably conservative but you should monitor Match History for the first few weeks to confirm match quality. 3104 3105## Privacy notes 3106 3107- Candidate previews mask all PII (first initial only, masked digits) 3108- OTP goes to the canonical email, NOT the new email â prevents an attacker who knows a member's basic profile from claiming their account via a third-party email 3109- All four audit events log the actor (the new shell member) and the canonical row ID for forensics`},{id:"53",slug:"free-membership-offer-at-events",title:"Free Membership Offer at Event Registration",category:"membership",summary:"Give qualifying event registrants a free year of membership as a registration incentive.",keywords:["free membership","event offer","membership offer","recruitment","guest","lapsed recovery","incentive"],order:3,content:`The *free membership offer* lets you give away a free 1-year membership to qualifying registrants of a specific event â a high-converting recruitment tool when paired with a paid event. 3110 3111## Who qualifies 3112 3113- The registrant must be an **authenticated portal member** on a **guest-type** membership (a membership type configured as "non-member" â e.g., Guest, Visitor, Walk-in) 3114- The event must have **Offer free membership** enabled in its configuration 3115- The registrant's selected role must be on the event's eligibility allowlist (if set; default is "all roles") 3116- The account must not be **Cancelled** or **Archived** (those accounts don't see the offer, and checkout refuses a claim from them) 3117 3118Members on real (paid) membership types who happen to be LAPSED/EXPIRED route through *Renewal at Event Checkout* instead. This avoids giving away free membership to people who already had a paid relationship with the society. 3119 3120## What the registrant sees 3121 3122A separate panel in the registration wizard: 3123 3124> **Get a free 1-year membership when you register** 3125> Active immediately. Auto-renew is off â you'll get a reminder before the year ends. 3126 3127If they check it, on payment confirmation: 31281. Their member row is upgraded to ACTIVE (idempotent â re-runs on retry are safe) 31292. \`membership_end_date\` is set to today + offer_free_membership_months (default 12) 31303. \`auto_renew\` is set to False (so they don't get auto-charged at year-end) 31314. \`acquisition_source\` is stamped \`event_offer:{event_id}\` for cohort reporting 31325. A welcome email goes out (per-society template, seeded by migration) 3133 3134## Per-event configuration 3135 3136In **Events** â edit an event â scroll to **Free Membership Offer** card: 3137 3138- **Enable free membership offer** â master toggle 3139- **Months of free membership** â default 12 3140- **Eligible role types** â multi-select of MembershipType IDs whose registrants qualify. Leave empty to qualify all non-member registrants. 3141 3142## Audit events 3143 3144- \`MEMBERSHIP_OFFER_CONFIGURED\` â admin toggled the per-event setting 3145- \`MEMBERSHIP_OFFER_GRANTED\` â registrant became ACTIVE via the offer 3146- \`STRIPE_WEBHOOK_RECONCILED\` â webhook â grant after a missed confirm 3147 3148## Common questions 3149 3150**What if someone is already ACTIVE?** The grant silently skips (\`skipped:already_active\`). They keep their existing membership; no double-grant. 3151 3152**What about retried failed payments?** The grant is idempotent. Each registration has a \`granted_member_id\` key â re-runs check that and noop if already granted. 3153 3154**Can I revoke the membership after granting it?** Refunding the original event payment doesn't auto-revoke (free-offer grants survive event refunds by design â the member already got value). Use **Members â edit â set status to LAPSED** if you need to manually revoke. 3155 3156**Capacity overflow?** If the event sells out between cart-add and confirm, the order is auto-refunded via Stripe before the membership grant fires. 3157 3158## Which prompt does each member see? 3159 3160| Member's current state | Prompt shown at event checkout | 3161|---|---| 3162| On a guest-type membership (Guest, Visitor, etc.) | Free membership offer â recruitment | 3163| On a real membership type, LAPSED or EXPIRED | Renewal at event checkout â lapsed recovery | 3164| On a real membership type, ACTIVE or in grace | No prompt â they pay the member rate as usual | 3165 3166The two features are complementary, not exclusive. Both can be enabled on the same society and the registration wizard picks the right panel based on the registrant's identity. See [Renewal at Event Checkout](/help/paid-renewal-at-event-checkout).`},{id:"54",slug:"per-role-non-member-event-pricing",title:"Per-Role Non-Member Event Pricing",category:"commerce",summary:"Charge different non-member event rates based on the role the registrant declares (Resident, Student, etc.).",keywords:["pricing","event pricing","non-member","role","member rate","audience","tiered","early bird"],order:10,content:`Most events have ONE non-member rate. But many societies want to charge a Resident or Student less than a full Physician non-member. Per-role pricing solves that. 3167 3168## How it works 3169 31701. You mark certain membership types as "eligible non-member roles" â e.g., Resident, Student, Allied Health 31712. On the event, you set per-role member AND non-member rates in a price matrix 31723. At checkout, a non-member picks their role from a dropdown; the resolver looks up the matching rate 3173 3174The matching member rate is also exposed in the matrix so a member registering as that role (e.g., a Resident who's a member) still pays the member-Resident rate. 3175 3176## Setting up 3177 3178### 1. Mark roles as eligible 3179 3180**Membership types** â click a type â **"Eligible as non-member role"** checkbox â Save. 3181 3182This flag is independent of \`is_non_member\`. A real-member type (Physician, Nurse Practitioner) can also be marked eligible â meaning a non-member can register AS that role for an event, paying that role's non-member rate. 3183 3184### 2. Configure per-role rates on the event 3185 3186**Events** â edit the event â scroll to **Per-role pricing** card. You'll see a matrix: 3187 3188| Role | Member rate | Non-member rate | 3189|---|---|---| 3190| Physician | $350 | $575 | 3191| Resident | $150 | $200 |
3192| Student | $75 | $100 | 3193 3194Leave a cell blank to fall back to the event's default \`member_price\` or \`regular_price\`. 3195 3196### 3. Optional: per-role early-bird overrides 3197 3198If your event has early-bird pricing, you can override per role too: 3199\`type_prices[uuid].early_bird_price\` for members, \`type_prices[uuid]:non_member.early_bird_price\` for non-members. The resolver walks an audience-key fallback chain â most-specific first. 3200 3201## What the registrant sees 3202 3203In the portal wizard's StepEvent: 3204 3205- **ACTIVE member** â no role picker, pays the matching member rate 3206- **Non-member** â role dropdown labeled "Professional role"; price updates as they pick 3207- **"Prefer not to say"** â falls back to the event's default \`regular_price\` 3208 3209The role is snapshotted on: 3210- \`EventRegistration.selected_role_type_id\` 3211- \`OrderLineItem.selected_role_type_id\` 3212- \`Order.line_items_snapshot[].selected_role_type_id\` 3213 3214So even if eligibility flags change later, the originally-charged role is preserved for reporting and refund logic. 3215 3216## Locked at cart validation 3217 3218Once the order is created, the role + price + audience-key are captured. \`confirm_order\` and the Stripe webhook reconciler do NOT re-validate role eligibility. This prevents a race where a member toggles a role's eligibility flag between cart-add and payment. 3219 3220## Audit events 3221 3222- \`ROLE_SELECTED_AT_REGISTRATION\` â non-member declared a role at checkout 3223- \`MEMBERSHIP_TYPE_ELIGIBILITY_CHANGED\` â admin toggled the eligible-as-non-member-role flag 3224 3225## Reporting 3226 3227Filter Event Registrations by \`selected_role_type_id\` to see role mix per event. Useful for: 3228- Justifying Resident-rate tier pricing to your board 3229- Comparing tier mix YoY 3230- Identifying which roles convert to full membership (combine with the free-membership offer) 3231 3232## Common questions 3233 3234**What if a non-member doesn't pick a role?** They pay \`regular_price\` (the default non-member rate). 3235 3236**Can a member pick a role?** ACTIVE members skip the role selector and pay the member rate directly. The role mechanic is only relevant when the registrant is not an active member. 3237 3238**Renewal-at-checkout interaction:** When a LAPSED member opts into renewal at checkout, they become a member-to-be for pricing purposes â the role selector's pick is discarded and they pay the standard member rate.`},{id:"55",slug:"portal-registration-wizard",title:"Portal Event Registration Wizard",category:"members",summary:"How members register for events through the multi-step wizard â and how it differs from the old dialog flow.",keywords:["wizard","registration","portal","event registration","StepEvent","StepContact","contact step","add-ons"],order:35,content:`The portal event registration wizard replaced the dialog-per-child flow in May 2026. Members now walk through a single multi-step page when registering for an event. 3239 3240## Step order 3241 3242The wizard derives steps dynamically based on the event's shape and the member's state: 3243 32441. **Event** (always) â parent event name, dates, venue, role selector (for non-members), child-event checklist, optional renewal-at-event-checkout panel, optional free-membership-offer panel 32452. **Contact** (always) â prefilled from the member profile. Editable. On Next, the diff syncs back to the member profile via PATCH /portal/profile. Profile-sync failures don't strand the user mid-registration. 32463. **Event fields â parent** (only if the parent has non-contact-overlap form fields and the member isn't already registered) 32474. **Event fields â child** (one step per selected child event with \`has_form=true\`) 32485. **Cart** (always, exits wizard) 3249 3250The "non-contact-overlap" check is important: when the only fields on an event are first_name / last_name / email / phone / address / etc., the wizard skips the step entirely because the contact step already collected them. 3251 3252## What members see at each step 3253 3254- **Step counter** at the top: "Step 2 of 4" 3255- **Back button** at the bottom (except on the first step) 3256- **Next button** â disabled until the current step's required fields are filled 3257- **Running total** card at the bottom of the Event step â updates live as add-ons / renew
3257al / role change 3258 3259## Add-on (child) events 3260 3261Parent events that have published children (e.g., 2026 Annual Meeting â Fellow's Corner, Ultrasound Course) show child checkboxes on the Event step. Selecting a child: 3262 3263- Adds its price to the running total 3264- Adds an event-fields step to the wizard (only if the child has non-contact-overlap form fields) 3265 3266Children with \`external_registration_url\` set bypass the wizard and link out directly â useful for legacy sub-events not yet migrated. 3267 3268## Already-registered handling 3269 3270- Parent registered, child not â the parent's event-fields step is skipped (they already filled it); they go straight from contact to child fields 3271- Child registered â the child shows as ticked + greyed out; cannot uncheck 3272 3273## Contact-overlap fields 3274 3275When admins build an event registration form, they sometimes add fields like First Name, Last Name, Email, Phone â even though the contact step already collects those. The wizard now hides those fields in the portal so members aren't asked twice. The admin form-config UI tags them with a small **"Hidden in portal"** chip. 3276 3277Other surfaces (admin Add Attendee, the form preview dialog) still show all fields because they don't have a contact step. 3278 3279See [Per-Role Non-Member Event Pricing](/help/per-role-non-member-event-pricing) for how the role selector works on the Event step. 3280 3281See [Renewal at Event Checkout](/help/paid-renewal-at-event-checkout) and [Free Membership Offer at Event Registration](/help/free-membership-offer-at-events) for the membership panels that appear conditionally on the Event step. 3282 3283## Differences from the old flow 3284 3285Before May 2026: 3286- Each child event had its own modal-style registration dialog 3287- Members repeated their contact info per registration 3288- No running-total preview before checkout 3289 3290After: 3291- One wizard for the whole transaction 3292- Contact info collected once and prefilled
3293- Running total updates live as add-ons / renewal / role change 3294- Cart auto-includes the parent when a child is added`},{id:"56",slug:"wordpress-integration",title:"WordPress Integration",category:"integrations",summary:"Embed live AMS data (member count, pricing, events, donations) on your WordPress marketing site via shortcodes.",keywords:["wordpress","plugin","shortcode","marketing","public api","simple tables","flgastro"],order:11,content:`If you run a public marketing site on WordPress, the AMS integration lets you embed live data directly in pages and posts â no manual updates when your member count grows or your dues change. 3295 3296## Architecture 3297 3298A small public API (4 unauthenticated, rate-limited endpoints on AMS) feeds WordPress shortcodes via transient-cached fetches. Stats refresh hourly by default. 3299 3300Endpoints (all return JSON): 3301- \`GET /api/v1/public/stats\` â total active members, founded year 3302- \`GET /api/v1/public/membership-types\` â pricing tiers for [ams_pricing] 3303- \`GET /api/v1/public/events\` â upcoming published events 3304- \`GET /api/v1/public/donation-campaigns\` â active fundraising campaigns 3305 3306No authentication, but rate-limited to 30 req/min per IP. 3307 3308## Shortcodes 3309 3310The \`ams-integration\` WordPress plugin exposes four shortcodes: 3311 3312### [ams_member_count] 3313 3314Drops the current member count inline. Example: "Join over [ams_member_count] members of the FGS." 3315 3316### [ams_pricing] 3317 3318Renders a pricing grid for all active, signup-visible membership types. Each tier shows name, price, and a **Join Now** button that links to the portal signup with that type pre-selected (\`?membership_type={id}\`). 3319 3320### [ams_events] 3321 3322Lists upcoming published events with date, location, price, and a registration button. 3323 3324### [ams_donation_campaigns] 3325 3326Lists active donation campaigns with progress bars and Donate buttons. 3327 3328## Bonus: Simple Tables plugin 3329 3330A sibling plugin ships alongside ams-integration: \`simple-tables\` replaces Ninja Tables (which forces a paid upgrade for more than 3 tables) with a lightweight alternative. Admin CRUD UI with inline row editing; frontend shortcode supports search/sort and a mobile card layout for wide tables. 3331 3332## Setup 3333 33341. **On the WordPress server** (not in the AMS repo): 3335 1. Download the plugin zip from \`~/wordpress-plugin/ams-integration/\` 3336 2. WordPress Admin â Plugins â Add New â Upload Plugin â select zip â Install + Activate 3337 3. Settings â AMS Integration â set: 3338 - \`AMS_API_URL\` (e.g., \`https://ams-api.korevera.com\`) 3339 - \`SOCIETY_SLUG\` (e.g., \`fgs\`) 33402. **On the AMS side** â no setup needed; the public endpoints are always on. Just confirm CORS allows your WordPress domain. 3341 3342## Updating the plugin 3343 3344The plugin zip lives at \`~/wordpress-plugin/\` (not in the ams-app repo). To update: 3345 33461. Edit the source files on your dev machine 33472. Re-zip the plugin folder 33483. WordPress: **Plugins â deactivate the old version â delete â re-upload the new zip â activate** 3349 3350WordPress doesn't let you overwrite an existing plugin folder via the uploader â you have to delete and re-upload. 3351 3352## Signup pre-selection from WordPress 3353 3354When a visitor clicks a "Join Now" button on the WordPress pricing page, they land on \`/portal/signup?membership_type={id}\`. The signup form auto-selects that membership type and skips the tier-selection step. 3355 3356## CORS 3357 3358\`flgastro.org\` and \`www.flgastro.org\` are in \`ALLOWED_ORIGINS\` on the AMS API. Add your WordPress domain there if you're running a different site. 3359 3360## Common issues 3361 3362**Shortcode shows raw text on the WP page** â plugin isn't activated, or the page is rendering inside a block that disables shortcodes. Drop into a "Classic Block" or use the Shortcode block explicitly. 3363 3364**Member count stuck at an old value** â WP transient cache. Either wait an hour or clear via Tools â Site Health â expire transients. 3365 3366**CORS error in browser console** â your WP domain isn't in \`ALLOWED_ORIGINS\`. Reach out to platform admin to add it. 3367 3368**Plugin won't install** â WordPress requires unique plugin folder names. If a previous version exists, deactivate and delete it first.`},{id:"57",slug:"event-form-field-configuration",title:"Event Form Field Configuration",category:"commerce",summary:"Build per-event registration forms from your society field library, with portal/event-app sync controls.",keywords:["form fields","registration form","event form","custom fields","sync to event app","hidden in portal","contact overlap"],order:12,content:`Each event can have its own registration form built from a shared library of fields. The form admins build is shown to members during portal registration AND pushed to the event-app as a schema for non-portal registrations. 3369 3370## Two field sources 3371 3372When you add a field to an event's form, you pick from one of two libraries: 3373 3374- **Event Form Fields** (event-specific library): Defined per-society under **Registration forms**. Reusable across events. 3375- **Custom Fields** (member-profile library): Defined on the society's platform settings (**Customization** tab), or saved from a form question under **Registration forms**. Useful when an event question should also update the member's profile. 3376 3377## Building an event form 3378 3379**Events** â edit the event â **Registration Form** section: 3380 33811. Click **Add Field** â pick from the library 33822. Drag to reorder 33833. Toggle **Required** per field 33844. Assign to a section if your form has multiple pages (sections render as step
3384sub-pages in the wizard) 3385 3386## The "Hidden in portal" warning 3387 3388The portal wizard's contact step (StepContact) already collects: first_name, last_name, email, phone, address, city, state, zip_code, country, organization. 3389 3390If you add a field whose \`field_key\` matches one of those, the row shows an amber **"Hidden in portal"** chip. The wizard skips that field for portal members so they aren't asked twice. Other surfaces (admin Add Attendee, the form preview dialog) still render the field â useful when an admin is manually entering a guest attendee. 3391 3392Best practice: don't add the contact-overlap fields to portal-targeting events. Use them only on events that primarily register through non-portal flows (paper, phone, walk-up). 3393 3394## Sync to Event App 3395 3396Each field has a **Sync to Event App** checkbox. When ON: 3397- The field's value is pushed to event-app as a \`customField\` on the attendee record 3398- The field's schema is pushed too (so event-app can validate non-portal registrations against the same form) 3399 3400When OFF, the field stays in AMS only â useful for fields that are sensitive or AMS-internal (e.g., emergency contact, AMS-internal notes). 3401 3402Note: \`firstName\`, \`lastName\`, \`email\`, \`city\`, \`state\` are pushed to event-app from the Member row directly. You don't need to sync those even if they appear in the form. 3403 3404## Field sections 3405 3406For long forms, group fields into sections: 3407 34081. **Add Section** (above the field list) â name the section (e.g., "Travel Details", "Dietary & Accessibility") 34092. Drag fields into the section 34103. The portal wizard renders one step per section 3411 3412Fields without a section render in a default "Unsectioned" step at the top. 3413 3414## Templates 3415 3416If you frequently build the same form across events, save it as a **Form Template**: **Registration forms** â create a template. Then on the event, pick the template instead of building from scratch. 3417 3418## Validation 3419 3420The wizard validates required fields at submit time: 3421- Empty required â "X is required" error inline on the field 3422- For required fields whose key is in the contact-overlap set, the wizard skips the form prompt but the contact step's snapshot satisfies the requirement on the backend. 3423 3424## Custom field auto-creation (MemberClicks) 3425 3426When importing from MemberClicks, MC fields without a 1:1 mapping in AMS auto-create as Custom Fields. The newly-created field key is enforced to snake_case (regex \`^[a-z][a-z0-9_]*$\`). Bracket-notation MC fields (\`[Email | Office Email Address]\`) skip the mapping UI; map them manually in the society settings JSONB.`},{id:"59",slug:"registering-members-by-phone",title:"Registering Members by Phone (Bulk Registration)",category:"commerce",tourId:"phone-orders",summary:"Register up to 25 members for an event in one batch â with one card paying for everyone â directly from the event registrants dialog.",keywords:["phone","bulk","batch","register","registration","office manager","card on file","add registrations","wizard","group"],order:5,content:`When an office manager calls to register several people at once â and pay for all of them with one credit card â use the **Add Registrations** wizard. It handles up to 25 registrants per batch, resolves each person's correct price automatically, collects any required registration forms, and charges a single payment. 3427 3428## Opening the Wizard 3429 34301. Go to **Events** and find the event. 34312. Click the **registrants icon** (the people icon) to open the Registration quickview. 34323. Click **Add registrations**. 3433 3434(The same dialog opens from the [Event dashboard](/help/event-dashboard) via **Registration quickview**.) 3435 3436The wizard is scoped to that event, plus any of its published child events (workshops, courses, labs). 3437 3438## Step 1: Pick Members 3439 3440Search for each registrant by name or email and select them â each appears as a chip showing their name, email, status, and membership type. You can add up to 25 people per batch. 3441 3442If the event has published child events, checkboxes appear under each registrant so you can add child-event registrations (for example, the main meeting plus a hands-on lab) for that specific person. Every registrant you select is registered for the main event; child events are optional per person. 3443 3444**Registrants must already exist as members** (any status â including non-member records). If someone isn't in your member list yet, add them first via **Members â Add Member**, then return to the wizard. 3445 3446## Step 2: Registration Forms 3447 3448If the event (or a selected child event) has a registration form, the wizard shows one form per registrant per event. Required fields must be completed before you can continue â ask the caller for the answers as you go. Answers save automatically as you type. 3449 3450## Step 3: Review Prices 3451 3452Each line shows the registrant, the rate that was applied (member, non-member, or a role-specific rate), and the amount. The batch total appears at the bottom. 3453 3454- **Override a price** by editing the amount â a reason is required for every override. The override and reason are recorded in the audit log. 3455- **Comp a registration** by overriding the price to 0. The line shows a comp marker. 3456- If pricing changes on the server between this step and payment (for example, another admin edits the event), the wizard automatically reopens this step with fresh prices so you can confirm before anything is charged. 3457 3458## Step 4: Payment 3459 3460One payer covers the whole batch. Two options: 3461 3462**Key in card** â Enter the card number, expiry, and CVC the caller reads to you, plus the cardholder name and a receipt email. The charge happens immediately and the receipt goes to that email. 3463 3464**Card on file** â If the payer is a member with a saved card, pick them in the payer search, select their saved card, and check the authorization box confirming the cardholder authorized this charge. The authorization attestation is recorded in the audit log with your name and a timestamp â only check it if the payer genuinely gave permission on the call. 3465 3466For a fully comped batch ($0 total), no card is needed â you'll just enter the payer's name and email for the record and the receipt. 3467 3468## What Happens After Payment 3469 3470- Each registrant is registered and appears in the event's registrants list immediately. 3471- Each registrant receives a **registration confirmation email**. 3472- The payer receives a **receipt email** listing every registration in the batch. 3473- An invoice is created per registration for your records. 3474- If the event is connected to the event app, attendees sync there automatically. 3475 3476## If You Close the Browser Mid-Batch 3477 3478The wizard is built to recover safely. If your browser crashes or you close the tab after starting a payment, reopen the wizard for the same event â it detects the unfinished attempt, checks what actually happened with the payment, and picks up where things left off. **It will never charge the card twice** for the same attempt. 3479 3480If the wizard shows "previous attempt unresolved â checkingâ¦", let it finish checking. Only use **Abandon previous attempt** if you're certain the payment didn't go through (the wizard re-checks before letting you abandon). 3481 3482For declined cards, failed payments, and refunds, see **Payments, Failures, and Refunds for Phone Orders**.`},{id:"71",slug:"walk-in-desk",title:"Registering Walk-ins at the Door (Walk-in Desk)",category:"commerce",summary:"Register and charge one onsite arrival at a time from a tablet at the check-in table â with quick-add for people not in the system and the free-membership offer when the event includes it.",keywords:["w
3482alk-in","walk in","onsite","door","check-in","desk","day of event","quick add","register","kiosk"],order:6,content:`When someone arrives at an event unregistered, use the **Walk-in desk** â a one-person-at-a-time flow built for a tablet at the check-in table. Open a published event's dashboard and choose **Walk-in desk**. (Session dashboards route to the main event's desk; sessions are selected as add-ons there.) 3483 3484## Step 1: Find the person 3485 3486Search by name or email. If they're not in the system, use **Quick-add** with their first name, last name, email, and professional role. If the email already exists, the desk shows that record â choose **Use this person** rather than creating a duplicate. 3487 3488## Step 2: Rate and details 3489 3490Review the resolved rate, tick any add-on sessions, and complete the required registration details. When the event includes the free-membership offer and the person is eligible, a **Join free** toggle applies the member rate. Price overrides are available and require a reason. 3491 3492## Step 3: Payment 3493 3494Check the prefilled payer name and receipt email (edit them if someone else is paying), then enter the card details. The desk uses keyed card entry only â saved cards and wallet buttons are not offered on a shared device. A zero-dollar registration needs no card. 3495 3496## After payment 3497 3498Receipt and confirmation emails are sent automatically and connected events sync to the event app. Choose **Next walk-in** to reset the desk for the next person, keeping the same event. 3499 3500If a rate, availability, or the offer changes between quoting and payment, the desk shows what changed â review the updated details before continuing. If a payment attempt is still processing, let the desk resolve it before starting another.`},{id:"60",slug:"phone-order-payments-and-refunds",title:"Payments, Failures, and Refunds for Phone Orders",category:"commerce",summary:"What each payment outcome means in the Add Registrations wizard â declined cards, failure messages, and how refunds work for batch registrations.",keywords:["phone order","declined","failed","refund","batch","bulk","payment","error","charge","receipt"],order:7,content:`This article covers what happens when a phone-order (bulk registration) payment doesn't go smoothly, and how refunds work for batch registrations. For the registration flow itself, see **Registering Members by Phone**. 3501 3502## Payment Outcomes 3503 3504**Paid** â The charge succeeded. All registrations in the batch are confirmed, confirmation emails and the receipt are sent, and the registrants appear in the event's list. 3505 3506**Card declined** â No one was registered and nothing was charged. Ask the caller for a different card and submit again â the wizard keeps the batch you built, so you won't re-enter anything. 3507 3508**Processing** â Some payments (rarely) take a moment to settle. The wizard waits and updates automatically; leave it open until it resolves. 3509 3510## Failure Messages Explained 3511 3512If something goes wrong between the charge and the registrations being created (for example, the last seat was taken while the card was processing), the system automatically refunds the charge. The wizard tells you exactly where things stand: 3513 3514- **"Payment was refunded â no one was registered"** â The charge was made and then fully refunded automatically. The caller's card will show the charge and the refund. Safe to try again once the underlying issue (like capacity) is resolved. 3515- **"Registration failed â the refund is still processing; verify in Stripe before re-charging"** â The automatic refund hasn't settled yet. **Do not charge the card again** until you've confirmed in Stripe that the refund went through â otherwise the caller could briefly be charged twice. 3516- **"The payment was refunded/disputed before completion â no one was registered"** â The payment was reversed (refunded or disputed) before registrations could be created. No one was registered; nothing further is owed. 3517 3518An every-few-minutes background check also watches for stuck payments and resolves them automatically, so an abandoned or interrupted attempt cleans itself up even if no one returns to the wizard. 3519 3520## Refunding a Batch Registration 3521 3522Each registration in a batch has its own payment line, so refunds work per person: 3523 35241. Go to **Payments** and find the payment (each line shows the registrant's name). 35252. Click **Refund** and enter the amount (full or partial) and a reason. 35263. A **full refund automatically cancels that person's registration**, frees their seat, removes them from the event app (if connected), and sends them a cancellation notice. The payer receives a refund notification. 3527 3528Refunding one registrant does not affect the others in the batch â their registrations and payments stand. 3529 3530To refund an entire batch, refund each payment line. When every line is refunded, the order shows as fully refunded. 3531 3532## Receipts and the Payer 3533 3534The receipt goes to the payer email entered at checkout (or the saved-card member's email). It lists every registration in the batch with amounts. Registrants get their own confirmation emails; only the payer gets the receipt. 3535 3536## Common Questions 3537 3538**The caller says they were charged but I don't see registrations.** Reopen the Add Registrations wizard for that event â it will find the unfinished attempt and complete it (or show you its true status). Don't start a new batch until it resolves. 3539 3540**Can I use one member's saved card to pay for other people?** Yes â that's the card-on-file option. You must check the authorization box confirming the cardholder gave permission; this is recorded in the audit log. 3541 3542**Can I mix free and paid registrations in one batch?** Yes. Comp individual lines to $0 with a reason; the card is only charged the remaining total. A fully-comped batch skips the card entirely.`},{id:"61",slug:"quickbooks-sync-overview",title:"QuickBooks sync overview",category:"integrations",summary:"How the nightly QuickBooks sync posts your Str
3542ipe activity â receipts, fees, refunds, disputes, and payouts â and where each piece lands.",keywords:["quickbooks","qbo","accounting","sync","stripe","sales receipt","refund","dispute","payout","clearing","fee","nightly","bookkeeping","ledger"],order:15,content:`The QuickBooks integration posts your society's Stripe activity into QuickBooks Online automatically, so your books stay current without hand-entry. It replaces third-party sync services with a first-party pipeline that AMS owns end to end. 3543 3544## Who can use it 3545 3546QuickBooks sync is a **platform-admin** feature. It lives under **Platform admin â Societies â [society] â Settings â Integrations**, with a dedicated sync-status page and configuration page for each connected society. Society admins do not see it. 3547 3548## When it runs 3549 3550- **Nightly sync â 2:35 AM ET.** Every night the sync sweeps the day's owned Stripe balance movements and posts a document in QuickBooks for each one. 3551- **Monthly tie-out â the 3rd of the month at 3:20 AM ET.** A completeness check that proves Stripe, the sync's own ledger, and QuickBooks all agree for the prior month. See **The monthly tie-out**. 3552 3553You can also run either on demand from the sync page with **Run sync now** or **Run tie-out**. 3554 3555## What posts, and where it lands 3556 3557Money that comes in through Stripe never lands directly in your checking account in the books â it lands in a **clearing account** first (where Stripe holds it until a payout), then moves to checking when Stripe actually pays you out. The sync mirrors that reality: 3558 3559- **Sales receipt** â one per Stripe charge. It is deposited **net** to the clearing account, with the Stripe processing fee as a **negative line** on the same receipt (and a promo discount, if any, as a second negative line). The receipt total equals what actually settled: gross minus the fee. 3560- **Refund receipt** â one per refund, for the **full refund amount**. Stripe does not return the processing fee when you refund a charge, so the fee stays booked as a cost â the refund receipt reverses the sale, not the fee. See the FAQ for why a full refund can leave a small balance behind. 3561- **Dispute journal entry** â when a charge is disputed (a chargeback), a journal entry books the money leaving your balance to the chargeback expense account. 3562- **Payout transfer** â when Stripe pays out to your bank, a transfer moves that amount from the clearing account to your checking account, matching the deposit your bank feed will show. 3563 3564## Items pick the account, classes pick the reporting 3565 3566Two QuickBooks concepts decide how each line is booked: 3567 3568- **Items** (Products/Services) decide **which account** a line hits. A revenue line uses the item mapped to its category, so its income posts to whatever income account that item points at. The fee line uses a fee item that points at the fee expense account â that is how a negative amount on the receipt lands as an expense. 3569- **Classes** are an **orthogonal reporting dimension**. Every line carries a class, so you can slice revenue and expense by program, chapter, or fund in QuickBooks reports without changing which account the money hits. 3570 3571You choose default items and classes once, and override them per category where you need to. See **Accounts, items, and default mappings** and **Category mappings**. 3572 3573## Getting started 3574 35751. Connect the society's QuickBooks company â see **Connecting QuickBooks**. 35762. Configure accounts, default items/classes, and category mappings â see **Accounts, items, and default mappings**. 35773. Turn on **Sync enabled** once the opening balance is verified. 35784. Watch the first nightly runs and the first monthly tie-out on the sync page â see **Reading the sync page**.`},{id:"62",slug:"quickbooks-connecting",title:"Connecting QuickBooks",category:"integrations",summary:"Connect a society to its QuickBooks company: use a desktop browser, sign in as a company admin, and pass the class-tracking check.",keywords:["quickbooks","qbo","connect","oauth","intuit","authorize","class tracking","reconnect","disconnect","company","realm","integration"],order:16,content:`Connecting binds one society to one QuickBooks Online company. Do this from a platform-admin session, on a desktop. 3579 3580## Connect from a desktop browser 3581 3582**Use a desktop or laptop browser â not a phone.** Intuit's sign-in page misbehaves inside phone browsers (the login gets intercepted by the QuickBooks mobile app's universal links and never completes), so the authorization silently fails. Start the connect from a real computer. 3583 35841. Go to **Platform admin â Societies**, open the society, choose **Settings**, and switch to the **Integrations** tab. 35852. On the **QuickBooks** card, click **Connect**. 35863. You are redirected to Intuit. **Sign in as a QuickBooks company administrator** and choose the company to connect. A non-admin login can authorize but will not have the permissions the sync needs. 35874. On return, the card shows **Connected** and a banner reads "QuickBooks connected â Configure accounts and mappings below, then enable sync." 3588 3589If the authorization is declined or expires, you land back with a short explanation and can simply connect again. 3590 3591## Turn on class tracking first 3592 3593Every line the sync posts carries a QuickBooks class, so the company must have **class tracking turned on, per transaction line**. This needs a **QuickBooks Online Plus or Advanced** plan. In QuickBooks: **Settings â Account and settings â Advanced â Categories** â turn on **Track classes**, and set **Assign classes** to **one to each row in transaction**. 3594 3595The configuration page runs a **class-tracking preflight** and will not let you finish setup until this passes. If it fails, turn class tracking on in QuickBooks, then reconnect. 3596 3597## One company per society 3598 3599A society is bound to the single QuickBooks company you connect. If the society already has documents synced to one company and you try to connect a **different** company, the connect is blocked ("This society already has synced records tied to a different QuickBooks company") â this protects your posted books from being re-pointed at the wrong company. Switching a live society to a different QuickBooks company is a supported-by-request process, not a self-service button; contact support. 3600 3601## Reconnecting after a broken connection 3602 3603QuickBooks access can lapse (an expired authorization, a revoked token). When that happens the card shows **Connection broken** with the reason, and syncing pauses. Click **Reconnect** on the QuickBooks card to restore access â **your configuration is preserved**; you are only re-authorizing. 3604 3605## Disconnecting 3606 3607Disconnecting is available from the QuickBooks card. It stops syncing and clears the stored QuickBooks credentials. Your accounts, mappings, and the sync ledger stay intact, so reconnecting the **same** company later resumes where you left off.`},{id:"63",slug:"quickbooks-accounts-and-mappings",title:"Accounts, items, and default mappings",category:"integrations",summary:"Set the clearing, checking, fee, and dispute accounts, plus the default items and classes the sync falls back to for every line.",keywords:["quickbooks","qbo","configuration","clearing account","checking","fee item","fee expense","dispute account","discount item","default item","class","mapping","posting mode"],order:17,content:`The QuickBooks **configuration** page has three tabs: **Accounts & connection**, **Default mappings**, and **Category mappings**. This article covers the first two â the accounts money moves through, and the default item and class every line falls back to. (Per-category overrides live on the third tab â see **Category mappings**.) 3608 3609Reach it from the sync page's **Configuration** button, or from the QuickBooks card's manage action. Every dropdown is populated live from your QuickBooks chart of accounts, item list, and class list. Click **Save** on each tab to store its changes. 3610 3611## Accounts & connection tab 3612 3613**Posting mode** â how the Stripe fee is recorded. **Primary** posts the fee as a negative line on the sales receipt itself; this is the normal mode and matches how most societies already keep their books. Fallback posts the fee as a separate expense instead. This is set during setup and generally left as configured â changing it only affects charges that sync **after** the change. 3614 3615The account fields: 3616 3617- **Clearing account** â the account Stripe money lands in until it is paid out. Pick a **Bank** or **Other Current Asset** account (many societies call it "Stripe Clearing"). Every sales receipt deposits here, every refund comes back out of here, and every payout transfers out of here to checking. 3618- **Checking account** â the **Bank** account Stripe actually pays out to. Payout transfers move money from clearing into this account, matching your bank feed. 3619- **Fee expense account** â an **Expense** account for Stripe processing fees. It is always required: dispute journal entries debit it too. 3620- **Dispute account** â an **Expense** account for chargeback losses, debited by dispute journal entries. 3621 3622The tab also holds the cutover fields (the moment your previous sync service stopped, and the last payout it posted). These are set once during cutover and should not be changed afterward â see the cutover runbook before touching them. 3623 3624## Default mappings tab 3625 3626These are the item and class the sync uses for any line that has no more-specific category override. 3627
3628- **Fee item** (Primary mode) â the QuickBooks Product/Service item used for the negative fee line. **Point it at the fee expense account.** That is the trick that makes a negative amount on a sales receipt land as an expense: the line uses an item, but the item routes the money to the fee account. 3629- **Discount item** â the item used for promo-discount lines. 3630- **Default item** â the fallback item for any revenue line whose category is not mapped. Its income account is where unmapped revenue lands, so choose a sensible catch-all. 3631- **Fee class**, **Discount class**, **Default class** â the classes attached to fee lines, discount lines, and any line with no category-specific class. Every posted line carries a class, so these are how unmapped activity still shows up in your class-based reports. 3632 3633### Adding a class without leaving the page 3634 3635If you need a class that does not exist yet, use **+ Add class** beneath any class dropdown. It creates the class in QuickBooks and selects it immediately, so you do not have to switch over to QuickBooks and come back. 3636 3637Fallback mode adds one more field, **Discount account**, an income account for promo-discount lines (fallback records discounts against an account rather than an item).`},{id:"64",slug:"quickbooks-category-mappings",title:"Category mappings",category:"integrations",summary:"Route specific events, products, campaigns, and dues to their own QuickBooks item and class â including per-event classes and the (no category) buckets.",keywords:["quickbooks","qbo","category","mapping","item","class","event","product","campaign","donation","dues","historical","no category","reporting"],order:18,content:`Category mappings let you route revenue to a specific QuickBooks item and class instead of the defaults â for example, sending each conference's registration income to its own item and class. They live on the **Category mappings** tab of the QuickBooks configuration page. 3638 3639## How a category becomes a row 3640 36411. **Give the source a QuickBooks category.** On an event, product, or campaign's edit form, set its QuickBooks category value. 36422. **After the next sync, it appears in the table.** Each distinct category shows up as a row with a **Type** tag (Events, Products, Donations, or Dues) telling you where it came from. 36433. **Map it.** In that row, choose an **Item** and a **Class**. Rows you leave on **"Use default"** fall back to the default item and class from the **Default mappings** tab, as the footer note under the table reminds you: "Rows left on 'Use default' fall back to the default item and class above at sync time." 3644 3645Because the item decides the account and the class is an independent reporting dimension, a common pattern is to give every event of a program the **same item** (so revenue books to one income account) but a **per-event class** (so each event reports separately). 3646 3647## The (no category) buckets 3648 3649Some rows are built in and always present: 3650 3651- **Membership dues** â the catch-all for non-commerce dues payments. 3652- **Events (no category)**, **Products (no category)**, **Donations (no category)** â where activity lands when its source has **no** QuickBooks category assigned. If an event shows up here, it simply has no category set. Give that event its own category value and it will get its own row on the next sync. 3653 3654## Historical rows 3655 3656A category tagged **Historical** is no longer attached to any live event, product, or campaign, but is kept because **past sales still reference it**. You cannot delete these â they preserve the mapping that older receipts were booked under. Use the **Historical** filter to find them. 3657 3658## Finding your way around the table 3659 3660- **Filter chips** â **All**, **Events**, **Products**, **Donations**, **Dues**, **Historical** â narrow the table to one type. 3661- **Search** matches on the category value. 3662 3663## Mappings never rewrite already-sold revenue 3664 3665Changing a mapping only affects **future** sales. When a purchase is made, AMS snapshots the category and its item/class onto that order, so a receipt always posts under the mapping that was in effect **at the time of sale**. Re-mapping a category tomorrow does not reach back and re-book yesterday's receipts.`},{id:"65",slug:"quickbooks-reading-the-sync-page",title:"Reading the sync page",category:"integrations",summary:"Understand the sync page: the live current-state cards, the Ledger tab of every document, the Activity audit trail, and what each status means.",keywords:["quickbooks","qbo","sync status","ledger","activity","audit","needs attention","synced","failed","needs review","skipped","status","documents"],order:19,content:`The QuickBooks **sync** page (**Platform admin â Societies â [society] â Settings â Integrations â QuickBooks**, then the sync-status view) reads like an operations console. It answers two different questions in three places: what needs you **right now**, the full history of **every document**, and **who did what**. 3666 3667## Current-state cards â live, right now 3668 3669The four cards at the top always reflect the current live state, not the last run: 3670 3671- **Needs attention** â how many documents the sync could not finish on its own (failed or held for review). "All clear" when it is zero, "Needs a look" otherwise. 3672- **Open tie-out flags** â unresolved discrepancies from the monthly tie-out. Links to the tie-out section below. 3673- **Documents in QuickBooks** â the all-time count of documents the sync has posted, plus the total dollars posted ("... posted all-time"). This is the scoreboard for success. 3674- **Next scheduled runs** â when the nightly sync and monthly tie-out will next run on their own. 3675 3676## Ledger tab â every document 3677 3678The **Ledger** tab lists **every** document the sync owns â successes included, not just problems. A receipt that synced cleanly stays here as a row; it does not vanish. Columns: 3679 3680- **Type** â sales receipt, refund receipt, dispute journal entry, transfer, or purchase. 3681- **Source** â the Stripe id the document came from. 3682- **Amount** â the document total. 3683- **Status** â see below.
3684- **QuickBooks ref** â the document's reference number in QuickBooks, so you can find it there. 3685- **Last event** â the row's story: **"Auto-synced"** for a clean nightly post, **"Force-retried â synced"** (and when) for a hand-recovered one, or the last error/skip reason for one still waiting. 3686 3687Use the filter chips â **All**, **Needs attention**, **Synced**, **Skipped** â and the search box ("Search source or referenceâ¦") to narrow the list. Recovery actions appear only on the rows that need them; see **Fixing sync problems**. 3688 3689### What each status means 3690 3691- **Synced** (green) â posted to QuickBooks successfully. Done. 3692- **Failed** (red) â the sync tried and could not post it. It needs a look; a background retry may also pick it up. 3693- **Needs review** (amber) â posted, but something does not line up (for example the document's total no longer matches), so it is held for a human. 3694- **Skipped** (muted) â intentionally not posted (out of the sync's domain â for example a movement from before your cutover date). 3695 3696## Activity tab â who did what 3697 3698The **Activity** tab is the audit trail for this integration: every connect, configuration save, enable/disable, sync run, force-retry, and tie-out action, each with **who** (a person's name, or "Scheduled" for an automated run) and **when**. Detail text wraps fully and is never truncated, so you can read and copy the whole thing. It shows the newest 50 actions and shows the newest 50 QuickBooks actions; the complete history lives on the Audit logs page. 3699 3700## Where things go when you resolve them 3701 3702Resolving a problem moves it out of your way. A failed row you recover flips to **Synced** and shows its QuickBooks reference. A tie-out flag you acknowledge or resolve **leaves the open list** â the record of it lives on in the **Activity** tab and the audit log. The current-state cards drop the count accordingly.`},{id:"66",slug:"quickbooks-fixing-sync-problems",title:"Fixing sync problems",category:"integrations",summary:"Recover a failed or held document: force retry, point at an existing QuickBooks document, or mark it resolved outside QuickBooks.",keywords:["quickbooks","qbo","failed","needs review","force retry","mark resolved","recovery","point at document","reference number","re-snapshot","parent drift","refund","troubleshoot"],order:20,content:`When a document shows **Failed** or **Needs review** on the Ledger tab, the row carries the actions that can clear it. Every action is confirmed in a short dialog with a required **Resolution note**, and the sync re-checks everything on its side before it does anything. 3703 3704## Force retry â the safe first move 3705 3706**Force retry** re-runs the record now. It is **idempotent**: a record that already created a QuickBooks document is re-checked against that document rather than posting a second one, so a retry **never double-posts**. Reach for this first for a transient failure (QuickBooks briefly unreachable, a token that has since refreshed). If the underlying cause is gone, the row flips to **Synced** and shows its QuickBooks reference. 3707 3708## Point at an existing QuickBooks document 3709 3710Use **Mark resolved â Point at an existing QuickBooks document** when the document already exists in QuickBooks â someone entered it by hand, or it posted during a crash before AMS recorded it. You give the document's **reference number** (the "NO." shown on the transaction in QuickBooks, on the document itself and in every transaction list). The sync **verifies** that the document really matches before it links it. If verification rejects your reference, that is the protection working â it means the document you pointed at does not match this record; double-check the reference rather than forcing it. (Transfers have no reference number in QuickBooks; a transfer that already carries a stored document is re-verified against that stored document instead.) 3711 3712## Resolved outside QuickBooks 3713 3714Use **Mark resolved â Resolved outside QuickBooks** when there is **no** QuickBooks document to point at and there never will be â the movement was handled some other way and this record should simply be closed. This links no document; it just marks the record done. It is only offered when the record
3714is not already tied to a QuickBooks document. 3715 3716## Re-snapshot parent â for a refund blocked by an edited receipt 3717 3718If a refund is held for review because **its original sales receipt was edited in QuickBooks after it posted**, the row offers **Re-snapshot parent**. The refund cannot mirror a receipt it no longer recognizes. Re-snapshot parent re-reads the receipt as it stands now and **adopts** the edit; then you **Force retry** the refund and it posts against the updated receipt. 3719 3720## When to wait, and when to act 3721 3722- **Transient failures** (QuickBooks unreachable, a token refreshing) often clear themselves â a background retry re-attempts failed rows, and the nightly run tries again. A quick **Force retry** is safe if you do not want to wait. 3723- **Held for review** (an edited receipt, a total that no longer matches) needs a person â the sync deliberately will not guess. Use the row's specific action above. 3724- If an action reports the connection is broken, **Reconnect** from the QuickBooks card first (see **Connecting QuickBooks**), then retry â recovery actions that touch QuickBooks are disabled while the connection is down.`},{id:"67",slug:"quickbooks-monthly-tie-out",title:"The monthly tie-out",category:"integrations",summary:"The monthly check that proves Stripe, the sync ledger, and QuickBooks agree â reading the verdict, the three checks, and resolving each flag.",keywords:["quickbooks","qbo","tie-out","tieout","reconciliation","variance","clearing","flag","missing in ledger","missing in quickbooks","total mismatch","unhandled category","acknowledge","month"],content:`The monthly tie-out is the safety net that proves nothing fell through the cracks. It checks that three sources agree for a given month: **Stripe** (what actually moved), the **sync's own ledger** (what AMS thinks it posted), and **QuickBooks** (what is really there). It runs automatically on the 3rd of each month, or on demand from the sync page. 3725 3726## Running one 3727 3728The **Run tie-out** control in the page header has a month picker joined to it. It defaults to the **last completed month** and cannot go earlier than your cutover month â a tie-out only covers full months after cutover. Pick a month and click **Run tie-out**. (If you try a month before cutover you will see "Run a tie-out only for months after the cutover date.") 3729 3730## The verdict 3731 3732The result reads like a verdict â one badge with the number a treasurer cares about: 3733 3734- **"Books agree â variance $0.00"** â everything reconciles. 3735- **"Needs attention â variance $X"** â there is a discrepancy to work. 3736- **"Tie-out incomplete â N checks could not run"** â a check was skipped (its reason is shown on the leg below). 3737 3738## The three checks 3739 3740Below the verdict, three legs report in plain language: 3741 3742- **Stripe â ledger** â every Stripe movement AMS owns (charge, refund, dispute, or payout) has a matching document in the sync ledger. Nothing owned is missing. 3743- **Ledger â QuickBooks** â every document the sync posted still exists in QuickBooks with the expected total. This one re-checks **all** synced documents, not just the month's, so it catches a document edited or deleted in QuickBooks long after it posted. 3744- **Clearing account** â the net movement through the clearing account that Stripe implies matches what QuickBooks actually shows. This is the dollars-level proof. 3745 3746A skipped leg shows its reason in words (for example, "the cutover isn't midnight-aligned, so the clearing window is ambiguous") rather than a bare code. 3747 3748## Flags and what to do with each 3749 3750Anything that does not reconcile becomes an **open flag** in the table below, each with its own resolution action: 3751 3752- **Missing from ledger** â Stripe shows a movement with no document. Use **Resolve** and tell the tie-out how each expected document was handled (point at the QuickBooks document that covers it, or mark it resolved outside QuickBooks). Do **not** simply acknowledge a missing-from-ledger flag â each missing document must actually be resolved. 3753- **Missing in QuickBooks** â AMS has a record for a document that no longer exists in QuickBooks (often deleted during cleanup). **Point at document** if the movement was re-posted under a different reference, **Convert to external** if a manual QuickBooks entry now covers it, or **Acknowledge** only if this was an expected, already-accounted-for outcome. 3754- **Total mismatch in QuickBooks** â the document AMS posted was edited in QuickBooks and no longer matches. Fix the document in QuickBooks to match AMS's record (the source of truth), then **Acknowledge**. 3755- **Unhandled category** / **Clearing variance** â a movement of a kind the sync does not auto-post, or a dollars-level gap. Investigate, book whatever is needed in QuickBooks by hand, then **Acknowledge** with a note of what you did. 3756 3757## Acknowledged flags come back if they are not really fixed 3758 3759Acknowledging or resolving a flag removes it from the open list, and the audit log records it. But acknowledging does not change any books â so if the underlying discrepancy is still there next month, the tie-out **flags it again**. A flag only stays gone once the real cause is resolved. 3760 3761## A worked example: a full refund leaves the fee behind 3762 3763Say a $400 registration is sold with an $11.90 Stripe fee, then fully refunded. The sale deposited $388.10 net to clearing; the refund took the full $400 back out. Clearing is now at **â$11.90** â the processing fee Stripe kept and never returned. That is **correct**: the fee is a real cost your society paid, and the clearing check will show that â$11.90 as expected movement matching QuickBooks, variance $0.00. A full refund is never quite "back to zero," and the tie-out proves the leftover is exactly the unreturned fee.`,order:21},{id:"68",slug:"quickbooks-faq",title:"QuickBooks sync FAQ",category:"integrations",summary:"Answers to the common questions: full-amount refunds, records that seem to disappear, acknowledged flags, phone connects, tie-out months, and (no category) events.",keywords:["quickbooks","qbo","faq","refund full amount","fee","disappeared","ledger","acknowledged flag","phone connect","desktop","tie-out month","no category","questions"],order:22,content:`Common questions from live use of the QuickBooks sync. 3764 3765## Why did my refund post for the full amount? 3766 3767Because the processing fee is not returned. When you refund a Stripe charge, Stripe gives back the full amount to the customer but keeps its original processing fee. So the refund receipt reverses the **full** sale, while the fee stays booked as the cost it always was. Your books show the truth: you received the net, paid the fee, and refunded the whole charge. A fully-refunded sale therefore leaves the fee behind in clearing â see the worked example in **The monthly tie-out**. 3768 3769## A record synced and then disappeared from the list â where did it go? 3770 3771Nowhere â you were probably looking at a filtered view. The **Ledger** tab shows **every** document, successes included; a synced receipt stays there as a row with its QuickBooks reference. The **current-state cards** and the **Needs attention** filter only ever show what needs you, so a document leaves those views the moment it succeeds. Switch the Ledger filter to **All** (or **Synced**) and it is right there. 3772 3773## I acknowledged a flag and it vanished â is that a problem? 3774 3775No. Acknowledging or resolving a tie-out flag removes it from the **open** list on purpose â that list is meant to show only unfinished work. The record of what you did lives on in the **Activity** tab and the full audit log (who acknowledged it, when, and your note). Note that acknowledging does not change your books, so if the real discrepancy is still there, next month's tie-out will flag it again. 3776 3777## The connect fails on my phone â why? 3778 3779Connect QuickBooks from a **desktop or laptop browser**, not a phone. On phones, Intuit's sign-in gets intercepted by the QuickBooks mobile app and never finishes the authorization, so the connect silently fails. On a real computer it completes normally. See **Connecting QuickBooks**. 3780 3781## Can I run a tie-out for any month? 3782 3783Only for **completed** months **after your cutover date**. The tie-out proves a full month reconciled, so it will not run for the current in-progress month or for anything before cutover â if you try, you will see "Run a tie-out only for months after the cutover date." Use the month picker beside **Run tie-out**; it defaults to the last completed month and stops at your cutover month. 3784 3785## Why does an event say "(no category)"? 3786 3787Because that event has no QuickBooks category assigned, so its revenue falls into the **Events (no category)** bucket â the cat
3787ch-all that keeps unassigned event income posting to your defaults. To give the event its own item and class, set a QuickBooks category on the event's edit form; after the next sync it appears as its own row on the **Category mappings** tab. See **Category mappings**.`},{id:"69",slug:"exporting-event-registrations",title:"Exporting Event Registrations",category:"commerce",summary:"Download an event roster as CSV with a column picker â profile, contact, faculty, registration dates, and every form answer.",keywords:["export","csv","registrations","roster","attendees","download","faculty","registration date","columns"],order:5,content:`Download a complete roster for any event, choosing exactly the columns you need. 3788 3789## Where to Find It 3790 37911. Go to **Events** (under the Commerce group) 37922. Click the **registrations icon** on an event to open its Registration quickview 37933. Click **Export CSV** in the dialog header 3794 3795You can also reach this same picker from the [Event dashboard](/help/event-dashboard) â click the 3796event's name, then **Export â Registrations CSV**. 3797 3798Each registration row in the dialog also shows **when the person registered** â the same 3799timestamp exported in the "registered_at" column. 3800 3801## Choosing Columns 3802 3803The picker opens with **every column selected**, so clicking straight through to 3804**Download CSV** gives the full export. Uncheck anything you don't need â the counter at the 3805bottom shows how many columns are in. 3806 3807- **All · None** links select or clear a whole group at once 3808- Column order in the file is always the same, regardless of what you pick 3809- The Download button stays disabled while the event's form is loading and whenever no 3810 columns are selected 3811 3812## Column Reference 3813 3814### Attendee 3815 3816| Column | What it holds | 3817|--------|---------------| 3818| First name, Last name, Email | From the member profile (or the guest checkout details) | 3819| Organization, City, State | From the member profile â blank for guests | 3820| Member type, Member status | Membership type name and current status | 3821| Faculty | **Yes/No from the member's faculty tag** â see the note below | 3822| Registered at | When the registration was created (the true registration time) | 3823| Registration status | Confirmed, cancelled, etc. â the export includes every status | 3824| Price paid | What this registration was charged | 3825| Guest | Yes for guest checkouts that aren't linked to a member record | 3826 3827### Contact details 3828 3829Phone, address lines, postal code, and country as entered on the **checkout contact step** â 3830useful when the registration address differs from the member profile (blank when the wizard 3831didn't collect them). 3832 3833### Form answers 3834 3835One column per question on the event's registration form â **all** questions, including ones 3836that aren't synced to the event app. **Other stored answers** sweeps in responses whose 3837question was later renamed or removed from the form, so form answers survive form edits. 3838(Internal checkout bookkeeping outside the curated contact fields is deliberately not 3839exported.) 3840 3841## Faculty Column vs. Event App Faculty 3842 3843The **Faculty** column here reflects the member-level *faculty tag* in Korevera â it says 3844"this person is on the faculty roster," society-wide. 3845 3846For **per-event** faculty status and the *type* of faculty (Speaker, Moderator, Course 3847Director, Panelistâ¦), use the **event app's** Attendees export instead â its "faculty" and 3848"facultyroles" columns come from that event's engagement records. 3849 3850## Good to Know 3851 3852- The export covers **one event at a time** â a parent event and its child events each export 3853 their own roster 3854- Cancelled registrations are included (filter by the Registration status column in your 3855 spreadsheet) 3856- Exports are limited to 5 per minute and are recorded in the audit log 3857`},{id:"70",slug:"event-dashboard",title:"Event dashboard",category:"commerce",summary:"The per-event stats page â registrations, net revenue, refunds, membership wins, weekly booking pace, registrant mix, event-app sync, and four CSV exports.",keywords:["dashboard","event stats","registrations","revenue","net revenue","refunds","weekly","trend","chart","child events","membership wins","registrant mi
3857x","sync","export"],order:8,content:`Every event has its own dashboard: one page showing how registrations are pacing, what the event has earned, who is signing up, and how many memberships it won. 3858 3859## Opening the Dashboard 3860 38611. Go to **Events** in the sidebar (under the Commerce group) 38622. Click the **event's name** 3863 3864Child events (workshops, labs, dinners) have dashboards of their own â open one from the Events list, or from the **Child events** table on the parent's dashboard. The back arrow returns you to Events; on a child page, the **Part ofâ¦** link takes you up to the parent. 3865 3866## The Four Stat Cards 3867 3868### Registrations 3869 3870**Confirmed registrations only** â cancelled and refunded ones are not counted. The big number is the event's **own** registrations, which on a parent event is your headcount: everyone attending an add-on is also registered for the parent, so the parent's own count is the number of actual people. The line underneath adds the capacity (when one is set) and, on parents, the family-wide record count **including sessions** â that larger figure counts one person once per session they booked. 3871 3872### Net revenue 3873 3874What the event has actually collected: everything booked, minus everything refunded, minus **comped** registrations â bookings fully covered by a promo code where no money ever changed hands. The smaller line underneath shows **gross booked** (the total at booked prices) and, when there are any, the comped amount, so the gap between gross and net is always explained by refunds plus comps. 3875 3876These figures are cash-accurate for full comps, with one caveat: a *partial* promo discount (say 20% off) still shows the registration at its full booked price. 3877 3878### Refunds & cancellations 3879 3880The big number is the refunded money â this event's share of every refund (on a parent, its children's refunds included), partial refunds included. The line underneath says where it came from: how many payments were refunded and how many of those were partial, plus any registrations refunded offline (money handled outside the card processor) and any cancellations. Someone who got $25 back on a $200 ticket is still a confirmed registrant (they still count under Registrations), and their $25 shows here labelled as a partial refund. 3881 3882### Membership wins 3883 3884Memberships the event brought in: free-membership offers claimed at registration, plus dues renewals paid alongside an event checkout. The line underneath splits the two and shows the renewal dollars. Refunding someone's ticket later does **not** take a win back â they still became, or stayed, a member. 3885 3886## Registrations Over Time 3887 3888The chart is labelled **Bookings by week â includes later cancellations**, and that label is the whole story. Bars are how many people registered during each week; the line is the running total. Weeks start on Monday, in the event's own time zone. 3889 3890It is a *booking pace* chart, so it never rewrites history: a registration that was later cancelled or refunded still appears in the week it was booked. That is why **the chart'
3890s total can be higher than the Registrations card** â the card counts who is confirmed today, the chart counts who signed up back then. 3891 3892Use the chart to see when your promotion landed. Use the cards for where things stand now. 3893 3894## Registrant Mix 3895 3896Who the event is drawing, counted as **people rather than rows**. A parent event's mix covers the parent's own registrations only, so someone who also booked two workshops isn't counted three times. 3897 3898Member registrants are broken down **one row per membership type** (Physician, Resident, â¦), sorted by count; members without a membership type are grouped under *No membership type*. Below the divider sit the two non-member rows: 3899 3900| Bucket | Who's in it | 3901|--------|-------------| 3902| Non-members | People registered at a non-member rate, or on a non-member record | 3903| Guests | Registrations not tied to a member record at all | 3904 3905Everything is read **as of right now**, not as of the day someone registered â a registrant's row reflects their current membership type, and lapsed or expired members still count under their type. 3906 3907## Event App Sync 3908 3909This card only appears when the event (or one of its children) is connected to the event app. It reports how attendees are being delivered: 3910 3911- **Pushed** â the attendee is in the event app 3912- **Pending** â queued but not sent yet; a background job keeps retrying 3913- **Failed** â the push errored, with the reason listed underneath 3914 3915Each failed row has a **Retry** button. Click it to send that person again â on success the row disappears and the counts update. Child events that are intentionally not connected to the event app contribute nothing to these numbers. 3916 3917## Child Events 3918 3919Parent events get a table of their add-ons: date, registered count against capacity, and gross and net revenue for each. Click any name to open that child's dashboard. 3920 3921The parent's **money** cards (revenue, refunds) already include every child, so never add a parent's dollar totals to its children's â you'd count the same money twice. The **Registrations** card is different: its big number is the parent's own headcount and does *not* include the child rows (the "incl. sessions" figure underneath does). The Financial summary CSV's Total row likewise sums registration *records* across the family, not people. 3922 3923## Registration Quickview 3924 3925The **Registration quickview** button opens the same list you get from the Events page: each person's name, email, city and state, when they registered, what they paid, their registration status, and their event-app push state (with a retry button on failures). You can also **Add registrations** from here â see [Registering Members by Phone](/help/registering-members-by-phone). 3926 3927It is a quick look, not the full record. **Full contact details â phone, address, postal code, country, and organization â are in the CSV export**, not on screen. 3928 3929On a parent event the quickview shows the parent's own registrations only; each child's list lives on that child's dashboard. 3930 3931## The Export Menu 3932 3933**Export** in the page header offers four files: 3934 3935| Export | What you get | 3936|--------|--------------| 3937| **Registrations CSV** | The attendee roster, with a column picker. Parent events get an **Include child add-on events** checkbox that merges the whole family into one file with an extra *Event* column. See [Exporting Event Registrations](/help/exporting-event-registrations). | 3938| **Weekly registrations CSV** | One row per week â new registrations, running total, revenue, running revenue. The chart as a spreadsheet. | 3939| **Financial summary CSV** | One row per event in the family (parent first, then children) â registrations, gross, refunded, comped, net â plus a Total row. | 3940| **Membership wins CSV** | One row per membership won â who, whether it was an offer or a renewal, the membership type, the amount, and the date. | 3941 3942Exports are limited to 5 per minute and every one is recorded in the audit log. 3943 3944## Good to Know 3945 3946- The dashboard is **admin-only** â members never see it 3947- A brand-new event shows zeros and an empty chart; nothing is broken 3948- Figures come straight from your live data â reload the page after taking a payment or issuing a refund to see it reflected 3949- A parent's revenue figures roll up its children, so parent and child dashboards overlap on purpose; headcount does not roll up â the parent's Registrations number already represents the people attending the whole family 3950`}];function O5(t,s){const a=s.toLowerCase().trim();return a?t.filter(n=>n.title.toLowerCase().includes(a)||n.summary.toLowerCase().includes(a)||n.keywords.some(r=>r.toLowerCase().includes(a))||n.content.toLowerCase().includes(a)):t}function U5(t,s){return t.filter(a=>a.category===s).sort((a,n)=>a.order-n.order)}function z5(t,s){return t.find(a=>a.slug===s)}function B5(t,s,a=3){return t.filter(n=>
3950n.category===s.category&&n.id!==s.id).sort((n,r)=>n.order-r.order).slice(0,a)}function K5(t){const s={};for(const a of Object.keys(Bn))s[a]=t.filter(n=>n.category===a).length;return s}const Q5={Rocket:Vb,Users:Lt,CreditCard:Qt,FileText:cs,Mail:$t,ShoppingBag:Wn,Settings:cn};function W5({category:t,articleCount:s,isSelected:a,onClick:n}){const r=Bn[t],i=Q5[r.icon]||cs;return e.jsx(L,{className:me("cursor-pointer transition-all hover:border-primary/50 hover:shadow-md",a&&"border-primary ring-2 ring-primary/20"),onClick:n,children:e.jsx($,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:me("rounded-lg bg-primary/10 p-2",a&&"bg-primary/20"),children:e.jsx(i,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("h3",{className:"text-sm font-medium",children:r.label}),e.jsx("p",{className:"mt-0.5 line-clamp-2 text-xs text-muted-foreground",children:r.description}),e.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:[s," ",s===1?"article":"articles"]})]})]})})})}function V5({article:t}){const s=Bn[t.category];return e.jsx(je,{to:`/help/${t.slug}`,children:e.jsx(L,{className:"cursor-pointer transition-all hover:border-primary/50 hover:shadow-md",children:e.jsx($,{className:"p-4",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("h3",{className:"text-sm font-medium",children:t.title}),e.jsx("p",{className:"mt-1 line-clamp-2 text-sm text-muted-foreground",children:t.summary})]}),e.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1.5 whitespace-nowrap",children:[e.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-muted-foreground/60"}),e.jsx("span",{className:"text-xs font-medium",children:s.label})]})]})})})})}function G5(){const{selectedSocietyId:t}=V(),s=kt(),{data:a}=Fx(),n=Cd(),r=J(),[i,l]=o.useState(""),[m,c]=o.useState(""),[d,u]=o.useState(null),h=()=>{s("/dashboard?tour=dashboard")};o.useEffect(()=>{const j=setTimeout(()=>{c(i)},200);return()=>clearTimeout(j)},[i]);const p=o.useMemo(()=>K5(Dl),[]),x=o.useMemo(()=>{let j=Dl;return d&&(j=U5(j,d)),m&&(j=O5(j,m)),j.sort((w,v)=>{if(w.category!==v.category){const k=Object.keys(Bn);return k.indexOf(w.category)-k.indexOf(v.category)}return w.order-v.order})},[m,d]),f=j=>{u(d===j?null:j)},b=()=>{u(null),l("")},N=Object.keys(Bn);return e.jsxs("div",{className:"space-y-6",children:[e.jsx("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:e.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(zl,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:"Help center"}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"Find answers to common questions and learn how to use the platform"})]})]})}),e.jsx("div",{className:"max-w-2xl",children:e.jsx(I5,{value:i,onChange:l,resultCount:m?x.length:void 0})}),e.jsxs("section",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h2",{className:"text-lg font-semibold tracking-tight",children:"Getting started"}),e.jsxs("div",{className:"flex items-center gap-2",children:[a?.dismissed_source==="user"&&e.jsx(g,{variant:"outline",size:"sm",onClick:()=>n.mutate({checklist_dismissed:{society_id:t,dismissed:!1}},{onSuccess:()=>{r.invalidateQueries({queryKey:["setup-status"]})}}),children:"Show on dashboard again"}),e.jsxs(g,{variant:"outline",size:"sm",onClick:h,className:"shrink-0",children:[e.jsx(jr,{className:"mr-1.5 h-4 w-4"}),"Restart dashboard tour"]})]})]}),e.jsx(Rg,{forceVisible:!0})]}),e.jsxs("div",{children:[e.jsx("h2",{className:"mb-3 text-lg font-semibold tracking-tight",children:"Browse by category"}),e.jsx("div",{className:"grid grid-cols-2 gap-3 md:grid-cols-3 xl:grid-cols-4",children:N.map(j=>e.jsx(W5,{category:j,articleCount:p[j],isSelected:d===j,onClick:()=>f(j)},j))})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"mb-3 flex items-center justify-between",children:[e.jsx("h2",{className:"text-lg font-semibold tracking-tight",children:d?Bn[d].label:m?"Search results":"All articles"}),(d||i)&&e.jsxs(g,{variant:"ghost",size:"sm",onClick:b,children:[e.jsx(ms,{className:"mr-1 h-4 w-4"}),"Clear filter"]})]}),x.length===0?e.jsxs("div",{className:"py-12 text-center text-muted-foreground",children:[e.jsx("p",{children:"No articles found matching your search."}),e.jsx(g,{variant:"link",onClick:b,className:"mt-2",children:"Clear filters and show all articles"})]}):e.jsx("div",{className:"grid gap-3",children:x.map(j=>e.jsx(V5,{article:j},j.id))})]})]})}function Y5(){const{slug:t}=Ds(),s=kt(),a=o.useMemo(()=>
3950{if(t)return z5(Dl,t)},[t]),n=o.useMemo(()=>a?B5(Dl,a,3):[],[a]);if(!a)return e.jsx(_t,{to:"/help",replace:!0});const r=Bn[a.category];return e.jsxs("div",{className:"max-w-4xl",children:[e.jsxs(je,{to:"/help",className:"mb-6 inline-flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground",children:[e.jsx(es,{className:"h-4 w-4"}),"Back to help center"]}),e.jsxs("div",{className:"mb-6 flex items-center gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(cs,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("span",{className:"mb-2 inline-flex items-center gap-1.5 whitespace-nowrap",children:[e.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-muted-foreground/60"}),e.jsx("span",{className:"text-xs font-medium",children:r.label})]}),e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:a.title}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:a.summary})]})]}),a.tourId&&(()=>{const i=a.tourId;return e.jsx("div",{className:"mb-6",children:e.jsxs(g,{onClick:()=>{s(Fg(i))},children:[e.jsx(Gb,{className:"mr-1.5 h-4 w-4"}),"Walk me through it"]})})})(),e.jsx(L,{className:"min-w-0 overflow-hidden",children:e.jsx($,{className:"prose prose-sm dark:prose-invert max-w-none p-6",children:e.jsx(_j,{components:{h2:({children:i})=>e.jsx("h2",{className:"mb-3 mt-6 text-lg font-semibold first:mt-0",children:i}),h3:({children:i})=>e.jsx("h3",{className:"mb-2 mt-4 text-base font-semibold",children:i}),p:({children:i})=>e.jsx("p",{className:"mb-3 text-sm leading-relaxed text-muted-foreground",children:i}),ul:({children:i})=>e.jsx("ul",{className:"mb-3 list-inside list-disc space-y-1 text-sm text-muted-foreground",children:i}),ol:({children:i})=>e.jsx("ol",{className:"mb-3 list-inside list-decimal space-y-1 text-sm text-muted-foreground",children:i}),li:({children:i})=>e.jsx("li",{className:"leading-relaxed",children:i}),strong:({children:i})=>e.jsx("strong",{className:"font-semibold text-foreground",children:i}),table:({children:i})=>e.jsx("div",{className:"mb-4 overflow-x-auto",children:e.jsx("table",{className:"w-full border-collapse text-sm",children:i})}),thead:({children:i})=>e.jsx("thead",{className:"bg-muted",children:i}),th:({children:i})=>e.jsx("th",{className:"border px-3 py-2 text-left text-[11px] font-medium uppercase tracking-wider text-muted-foreground/80",children:i}),td:({children:i})=>e.jsx("td",{className:"border px-3 py-2 text-muted-foreground",children:i}),code:({children:i})=>e.jsx("code",{className:"rounded bg-muted px-1.5 py-0.5 font-mono text-xs",children:i}),hr:()=>e.jsx("hr",{className:"my-6 border-border"}),a:({href:i,children:l})=>i&&i.startsWith("/")?e.jsx(je,{to:i,className:"font-medium text-blue-600 hover:underline dark:text-blue-400",children:l}):e.jsx("a",{href:i,target:"_blank",rel:"noopener noreferrer",className:"font-medium text-blue-600 hover:underline dark:text-blue-400",children:l})},children:a.content})})}),n.length>0&&e.jsxs("div",{className:"mt-8",children:[e.jsx("h2",{className:"mb-3 text-lg font-semibold tracking-tight",children:"Related articles"}),e.jsx("div",{className:"space-y-2",children:n.map(i=>e.jsx(je,{to:`/help/${i.slug}`,className:"block text-sm text-primary hover:underline",children:i.title},i.id))})]})]})}function H5(t){const s=[];return t.filters.statuses?.length&&s.push(`${t.filters.statuses.length} status${t.filters.statuses.length>1?"es":""}`),t.filters.membership_type_ids?.length&&s.push(`${t.filters.membership_type_ids.length} type${t.filters.membership_type_ids.length>1?"s":""}`),t.filters.tags?.length&&s.push(`${t.filters.tags.length} tag${t.filters.tags.length>1?"s":""}`),s}function J5(){const{selectedSocietyId:t}=V(),{data:s,isLoading:a}=tr(t??void 0),{data:n,isLoading:r}=sr(t??void 0),{data:i,isLoading:l}=jS(),m=vS(),c=wS(),d=NS(),u=kS(),[h,p]=o.useState(!1),[x,f]=o.useState(null),[b,N]=o.useState(null),[j,w]=o.useState(null),v=!!s?.mailchimp_connected,k=!!n?.mailerlite_connected,S=a||r,_=v||k,y=!l&&(!i||i.length===0),C=async K=>{await m.mutateAsync(K),p(!1)},P=K=>{f(K),p(!0)},A=async K=>{x&&(await c.mutateAsync({ruleId:x.id,data:{name:K.name,destination_id:K.destination_id,destination_name:K.destination_name,filters:K.filters}}),f(null),p(!1))},E=async K=>{await c.mutateAsync({ruleId:K.id,data:{is_active:!K.is_active}})},Q=async()=>{b&&(await d.mutateAsync(b.id),N(null))},U=async K=>{w(K.id);
3950try{await u.mutateAsync(K.id)}finally{w(null)}},D=()=>{p(!1),f(null)};return e.jsxs("div",{className:"space-y-6",children:[e.jsx(Tn,{}),e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(Yb,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:"Sync rules"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Automatically sync member segments to Mailchimp or MailerLite"})]})]}),_&&!h&&e.jsxs(g,{onClick:()=>{f(null),p(!0)},children:[e.jsx(Rt,{className:"mr-2 h-4 w-4"}),"Create sync rule"]})]}),!S&&!_&&e.jsx(L,{className:"min-w-0 overflow-hidden",children:e.jsx($,{className:"py-12 text-center",children:e.jsxs("p",{className:"text-muted-foreground",children:["Connect Mailchimp or MailerLite in"," ",e.jsx(je,{to:"/settings",className:"text-primary underline hover:no-underline",children:"Settings"})," ","to create sync rules."]})})}),h&&e.jsx(hC,{onSubmit:x?A:C,onCancel:D,initialValues:x??void 0,isEditing:!!x}),_&&!h&&e.jsx(L,{className:"min-w-0 overflow-hidden",children:e.jsx($,{className:"p-0",children:l?e.jsx("div",{className:"space-y-3 p-6",children:Array.from({length:3}).map((K,xe)=>e.jsx(Y,{className:"h-12 w-full"},xe))}):y?e.jsxs("div",{className:"py-12 text-center",children:[e.jsx("p",{className:"text-muted-foreground",children:"No sync rules yet."}),e.jsxs(g,{className:"mt-4",onClick:()=>{f(null),p(!0)},children:[e.jsx(Rt,{className:"mr-2 h-4 w-4"}),"Create your first sync rule"]})]}):e.jsxs(Pt,{children:[e.jsx(At,{className:"bg-muted/30",children:e.jsxs(Ue,{className:"hover:bg-transparent",children:[e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Name"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Platform"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Destination"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Filters"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Active"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Last synced"}),e.jsx(H,{className:"h-10 w-32 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Actions"})]})}),e.jsx(Et,{children:i?.map(K=>{const xe=H5(K),z=j===K.id;return e.jsxs(Ue,{className:"hover:bg-brand-navy/[0.04] dark:hover:bg-brand-navy/10",children:[e.jsx(G,{className:"font-medium",children:K.name}),e.jsx(G,{children:e.jsxs("span",{className:"inline-flex items-center gap-1.5 whitespace-nowrap",children:[e.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-muted-foreground/60"}),e.jsx("span",{className:"text-xs font-medium",children:K.platform==="mailchimp"?"Mailchimp":"MailerLite"})]})}),e.jsx(G,{className:"text-sm text-muted-foreground",children:K.destination_name||K.destination_id}),e.jsx(G,{children:xe.length>0?e.jsx("div",{className:"flex flex-wrap gap-x-3 gap-y-1",children:xe.map(ae=>e.jsxs("span",{className:"inline-flex items-center gap-1.5 whitespace-nowrap",children:[e.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-muted-foreground/60"}),e.jsx("span",{className:"text-xs font-medium",children:ae})]},ae))}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"All members"})}),e.jsx(G,{children:e.jsx(ss,{checked:K.is_active,onCheckedChange:()=>E(K),disabled:c.isPending})}),e.jsxs(G,{className:"whitespace-nowrap text-sm text-muted-foreground",children:[K.last_synced_at?Ct(K.last_synced_at).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"}
3950):"Never",K.last_sync_count!==null&&K.last_synced_at&&e.jsxs("span",{className:"ml-1 text-xs",children:["(",K.last_sync_count,")"]})]}),e.jsx(G,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsxs(g,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>P(K),title:"Edit",children:[e.jsx(Hs,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Edit"})]}),e.jsxs(g,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>U(K),disabled:z,title:"Sync now",children:[z?e.jsx(He,{className:"h-4 w-4 animate-spin"}):e.jsx(St,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Sync now"})]}),e.jsxs(g,{variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground hover:text-destructive",onClick:()=>N(K),title:"Delete",children:[e.jsx(Ft,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Delete"})]})]})})]},K.id)})})]})})}),e.jsx(Fe,{open:!!b,onOpenChange:K=>!K&&N(null),children:e.jsxs(Te,{children:[e.jsxs(Ae,{children:[e.jsx(Ee,{children:"Delete sync rule"}),e.jsxs(tt,{children:["This will stop syncing members to"," ",e.jsx("strong",{children:b?.destination_name||"this group"}),". Members already in the group will NOT be removed."]})]}),e.jsxs(Ge,{children:[e.jsx(g,{variant:"outline",onClick:()=>N(null),children:"Cancel"}),e.jsx(g,{variant:"destructive",onClick:Q,disabled:d.isPending,children:d.isPending?"Deletingâ¦":"Delete rule"})]})]})})]})}const Vo={list:async(t={})=>(await F.get("/admin/event-app/revoke-queue",{params:t})).data.items,retry:async t=>(await F.post(`/admin/event-app/revoke-queue/${t}/retry`)).data,dismiss:async t=>(await F.post(`/admin/event-app/revoke-queue/${t}/dismiss`)).data},Z5=[{key:"pending",label:"Pending"},{key:"failed",label:"Failed (capped)"},{key:"succeeded",label:"Succeeded"}];function ku(t){if(!t)return"â";const s=Ct(t);return Number.isNaN(s.getTime())?t:s.toLocaleString()}function X5(t,s=80){return t?t.length>s?t.slice(0,s)+"â¦":t:"â"}function e3(){const{user:t}=V(),s=t?.role==="super_admin",[a,n]=o.useState("pending"),[r,i]=o.useState([]),[l,m]=o.useState(!1),[c,d]=o.useState(null),[u,h]=o.useState(null),p=o.useCallback(async()=>{m(!0),d(null);try{const b=await Vo.list({state:a,limit:100});i(b)}catch(b){const N=b instanceof Error?b.message:"Failed to load revoke queue";d(N)}finally{m(!1)}},[a]);o.useEffect(()=>{p()},[p]);const x=async b=>{h(b);try{await Vo.retry(b),await p()}catch(N){const j=N instanceof Error?N.message:"Retry failed";d(j)}finally{h(null)}},f=async b=>{if(window.confirm("Mark this row as succeeded without calling event-app? This cannot be undone.")){h(b);try{await Vo.dismiss(b),await p()}catch(N){const j=N instanceof Error?N.message:"Dismiss failed";d(j)}finally{h(null)}}};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(St,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:"Event-app revoke queue"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Durable outbox for event-app attendee revocations. The drain cron retries pending rows with exponential backoff; rows that exhaust their attempts move to Failed and require manual retry or dismissal."})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[Z5.map(b=>e.jsx(g,{variant:a===b.key?"default":"outline",size:"sm",onClick:()=>n(b.key),children:b.label},b.key)),e.jsx(g,{variant:"outline",size:"sm",onClick:()=>{p()},disabled:l,children:"Refresh"})]}),c&&e.jsx(L,{className:"min-w-0 overflow-hidden",children:e.jsx($,{className:"py-4 text-sm text-destructive",children:c})}),e.jsx(L,{className:"min-w-0 overflow-hidden",children:e.jsx($,{className:"p-0",children:l?e.jsx("div",{className:"space-y-3 p-6",children:Array.from({length:5}).map((b,N)=>e.jsx(Y,{className:"h-10 w-full"},N))}):r.length===0?e.jsxs("div",{className:"py-12 text-center text-muted-foreground",children:["No ",a," rows."]}):e.jsxs(Pt,{children:[e.jsx(At,{className:"bg-muted/30",children:e.jsxs(Ue,{className:"hover:bg-transparent",children:[e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground
3950/80",children:"Created"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Event slug"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Email"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Reason"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Attempts"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Last error"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Last attempt"}),s&&a!=="succeeded"&&e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Actions"})]})}),e.jsx(Et,{children:r.map(b=>e.jsxs(Ue,{className:"hover:bg-brand-navy/[0.04] dark:hover:bg-brand-navy/10",children:[e.jsx(G,{className:"whitespace-nowrap text-xs",children:ku(b.created_at)}),e.jsx(G,{className:"font-mono text-xs",children:b.event_app_event_slug}),e.jsx(G,{className:"text-xs",children:b.member_email}),e.jsx(G,{children:e.jsxs("span",{className:"inline-flex items-center gap-1.5 whitespace-nowrap",children:[e.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-muted-foreground/60"}),e.jsx("span",{className:"text-xs font-medium",children:b.reason})]})}),e.jsx(G,{children:b.attempts}),e.jsx(G,{className:"max-w-xs text-xs",title:b.last_error||"",children:X5(b.last_error,60)}),e.jsx(G,{className:"whitespace-nowrap text-xs",children:ku(b.last_attempt_at)}),s&&a!=="succeeded"&&e.jsx(G,{children:e.jsxs("div",{className:"flex gap-2",children:[e.jsx(g,{variant:"outline",size:"sm",onClick:()=>{x(b.id)},disabled:u===b.id,children:"Retry"}),e.jsx(g,{variant:"outline",size:"sm",onClick:()=>{f(b.id)},disabled:u===b.id,children:"Dismiss"})]})})]},b.id))})]})})})]})}function t3(t){if(!t)return"â";const s=Ct(t);return Number.isNaN(s.getTime())?t:s.toLocaleString()}function s3(){const{user:t,selectedSocietyId:s}=V(),[a,n]=o.useState(1),[r,i]=o.useState(null),[l,m]=o.useState(!1),[c,d]=o.useState(null),u=20,h=o.useCallback(async()=>{m(!0),d(null);try{const x={page:a,size:u};t?.role==="super_admin"&&s&&(x.society_id=s);const f=await F.get("/members/merged",{params:x});i(f.data)}catch(x){const f=x instanceof Error?x.message:"Failed to load merged accounts";d(f)}finally{m(!1)}},[a,t?.role,s]);o.useEffect(()=>{h()},[h]);const p=r?Math.ceil(r.total/u):0;return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(yp,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:"Merged accounts"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Records that were merged into another member â by an admin or through portal account matching."})]})]}),e.jsx("div",{className:"flex items-center justify-end",children:e.jsx(g,{variant:"outline",size:"sm",onClick:()=>{h()},disabled:l,children:"Refresh"})}),c&&e.jsx(L,{className:"min-w-0 overflow-hidden",children:e.jsx($,{className:"py-4 text-sm text-destructive",children:c})}),e.jsx(L,{className:"min-w-0 overflow-hidden",children:e.jsx($,{className:"p-0",children:l?e.jsx("div",{className:"space-y-3 p-6",children:Array.from({length:5}).map((x,f)=>e.jsx(Y,{className:"h-10 w-full"},f))}):!r||r.items.length===0?e.jsx("div",{className:"py-12 text-center text-muted-foreground",children:"No merged accounts yet."}):e.jsxs(Pt,{children:[e.jsx(At,{className:"bg-muted/30",children:e.jsxs(Ue,{className:"hover:bg-transparent",children:[e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Shell email"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground
3950/80",children:"Merged at"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Canonical email"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Canonical ID"})]})}),e.jsx(Et,{children:r.items.map(x=>e.jsxs(Ue,{className:"hover:bg-brand-navy/[0.04] dark:hover:bg-brand-navy/10",children:[e.jsx(G,{className:"font-mono text-xs text-muted-foreground",children:x.shell_email}),e.jsx(G,{className:"whitespace-nowrap text-xs",children:e.jsxs("div",{className:"flex items-center gap-2",children:[t3(x.merged_at),e.jsx(Ts,{variant:"secondary",children:x.source==="admin"?"Admin merge":"Portal merge"})]})}),e.jsx(G,{className:"text-xs",children:x.canonical_email??"â"}),e.jsx(G,{className:"font-mono text-xs text-muted-foreground",children:x.canonical_id?x.canonical_id.slice(0,8)+"â¦":"â"})]},x.shell_id))})]})})}),p>1&&e.jsxs("div",{className:"flex items-center justify-center gap-2",children:[e.jsx(g,{variant:"outline",size:"sm",onClick:()=>n(x=>Math.max(1,x-1)),disabled:a===1||l,children:"Previous"}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:["Page ",a," of ",p]}),e.jsx(g,{variant:"outline",size:"sm",onClick:()=>n(x=>Math.min(p,x+1)),disabled:a===p||l,children:"Next"})]})]})}const a3={pending:"bg-amber-400",verified:"bg-emerald-500",failed:"bg-red-500",expired:"bg-muted-foreground/40"},n3=[{value:"",label:"All statuses"},{value:"pending",label:"Pending"},{value:"verified",label:"Verified"},{value:"failed",label:"Failed"},{value:"expired",label:"Expired"}];function _u(t){if(!t)return"â";const s=Ct(t);return Number.isNaN(s.getTime())?t:s.toLocaleString()}function r3(){const{user:t,selectedSocietyId:s}=V(),[a,n]=o.useState(1),[r,i]=o.useState(""),[l,m]=o.useState(null),[c,d]=o.useState(!1),[u,h]=o.useState(null),p=20,x=o.useCallback(async()=>{d(!0),h(null);try{const b={page:a,size:p,sort_by:"match_score",sort_dir:"desc"};r&&(b.status=r),t?.role==="super_admin"&&s&&(b.society_id=s);const N=await F.get("/members/link-history",{params:b});m(N.data)}catch(b){const N=b instanceof Error?b.message:"Failed to load link history";h(N)}finally{d(!1)}},[a,r,t?.role,s]);o.useEffect(()=>{x()},[x]);const f=l?Math.ceil(l.total/p):0;return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(li,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:"Match history"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"OTP verification challenges issued during Phase 3 cross-row lapsed detection. Sorted by match score."})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[n3.map(b=>e.jsx(g,{variant:r===b.value?"default":"outline",size:"sm",onClick:()=>{i(b.value),n(1)},children:b.label},b.value)),e.jsx(g,{variant:"outline",size:"sm",onClick:()=>{x()},disabled:c,children:"Refresh"})]}),u&&e.jsx(L,{className:"min-w-0 overflow-hidden",children:e.jsx($,{className:"py-4 text-sm text-destructive",children:u})}),e.jsx(L,{className:"min-w-0 overflow-hidden",children:e.jsx($,{className:"p-0",children:c?e.jsx("div",{className:"space-y-3 p-6",children:Array.from({length:5}).map((b,N)=>e.jsx(Y,{className:"h-10 w-full"},N))}):!l||l.items.length===0?e.jsx("div",{className:"py-12 text-center text-muted-foreground",children:"No match history yet."}):e.jsxs(Pt,{children:[e.jsx(At,{className:"bg-muted/30",children:e.jsxs(Ue,{className:"hover:bg-transparent",children:[e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Status"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Score"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground
3950/80",children:"Block key"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Shell ID"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Canonical ID"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Created"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Resolved"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Failure reason"})]})}),e.jsx(Et,{children:l.items.map(b=>e.jsxs(Ue,{className:"hover:bg-brand-navy/[0.04] dark:hover:bg-brand-navy/10",children:[e.jsx(G,{children:e.jsxs("span",{className:"inline-flex items-center gap-1.5 whitespace-nowrap",children:[e.jsx("span",{className:`h-1.5 w-1.5 shrink-0 rounded-full ${a3[b.status]??"bg-muted-foreground/40"}`}),e.jsx("span",{className:"text-xs font-medium",children:b.status})]})}),e.jsxs(G,{className:"text-xs font-medium",children:[(b.match_score*100).toFixed(0),"%"]}),e.jsx(G,{className:"font-mono text-xs",children:b.blocking_key}),e.jsxs(G,{className:"font-mono text-xs text-muted-foreground",children:[b.shell_member_id.slice(0,8),"â¦"]}),e.jsxs(G,{className:"font-mono text-xs text-muted-foreground",children:[b.canonical_candidate_id.slice(0,8),"â¦"]}),e.jsx(G,{className:"whitespace-nowrap text-xs",children:_u(b.created_at)}),e.jsx(G,{className:"whitespace-nowrap text-xs",children:_u(b.verified_at??b.failed_at)}),e.jsx(G,{className:"text-xs text-muted-foreground",children:b.failure_reason??"â"})]},b.id))})]})})}),f>1&&e.jsxs("div",{className:"flex items-center justify-center gap-2",children:[e.jsx(g,{variant:"outline",size:"sm",onClick:()=>n(b=>Math.max(1,b-1)),disabled:a===1||c,children:"Previous"}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:["Page ",a," of ",f]}),e.jsx(g,{variant:"outline",size:"sm",onClick:()=>n(b=>Math.min(f,b+1)),disabled:a===f||c,children:"Next"})]})]})}function Yf(){return e.jsxs("div",{className:"relative flex min-h-screen flex-col items-center justify-center overflow-hidden bg-background",children:[e.jsx("div",{className:"pointer-events-none absolute inset-0",style:{background:"radial-gradient(ellipse 80% 60% at 50% 40%, hsl(var(--muted) / 0.5), transparent)"}}),e.jsx("span",{className:"pointer-events-none absolute select-none font-bold tracking-tighter text-muted-foreground/[0.06]",style:{fontSize:"clamp(16rem, 40vw, 28rem)",lineHeight:1},"aria-hidden":"true",children:"404"}),e.jsxs("div",{className:"relative z-10 flex flex-col items-center px-6 text-center",children:[e.jsx("img",{src:pn,alt:"Korevera",className:"animate-fade-slide-up h-6 object-contain opacity-40"}),e.jsx("div",{className:"animate-fade-slide-up-delay-1 my-8 h-px w-12 bg-border"}),e.jsx("h1",{className:"animate-fade-slide-up-delay-1 text-lg font-medium tracking-wide text-foreground",children:"Page not found"}),e.jsx("p",{className:"animate-fade-slide-up-delay-2 mt-3 max-w-xs text-sm leading-relaxed text-muted-foreground",children:"The page you're looking for doesn't exist or has been moved."})]})]})}function Su(){const t=qs(),[s]=ws(),a=s.get("token")??"",[n,r]=o.useState(null),[i,l]=o.useState("loading"),[m,c]=o.useState(null),d=t?`${ds}/api/v1/public/${t}`:null;o.useEffect(()=>{if(!d)return;async function h(){try{if(!(await fetch(`${d}/email/unsubscribe?token=${encodeURIComponent(a)}`,{method:"POST"})).ok)throw new Error;const x=await fetch(`${d}/email/unsubscribe/status?token=${encodeURIComponent(a)}`);if(!x.ok)throw new Error;r(await x.json()),l("ready")}catch{l("error")}}h()},[d,a]);async function u(){try{if(!(await fetch(`${d}/email/resubscribe?token=${encodeURIComponent(a)}`,{method:"POST"})).ok)throw new Error;l("undone")}catch{c(`Couldn't resubscribe â the undo window may have expired. Contact ${n?.society_name??"the society"} to opt back in.`)}}return e.jsx("div",{className:"min-h-screen bg-gray-50 flex items-center justify-center p-6",children:e.jsxs("div",{className:"w-full max-w-md rounded-xl border border-gray-200 bg-white p-8 text-center shadow-sm",children:[n?.logo_url&&e.jsx("img",{src:n.logo_url,className:"mx-auto mb-4 h-12 w-auto",alt:""}),i==="loading"&&e.jsx("p",{className:"text-gray-500",children:"One momentâ¦"}),i==="error"&&e.jsx("p",{className:"text-gray-700",children:"This unsubscribe link is invali
3950d or expired."}),i==="undone"&&n&&e.jsxs(e.Fragment,{children:[e.jsx("h1",{className:"text-lg font-semibold text-gray-900",children:"You're resubscribed"}),e.jsxs("p",{className:"mt-2 text-sm text-gray-600",children:[n.email_masked," will keep receiving emails from ",n.society_name,"."]})]}),i==="ready"&&n&&e.jsxs(e.Fragment,{children:[e.jsxs("h1",{className:"text-lg font-semibold text-gray-900",children:["You've been unsubscribed from ",n.society_name," emails"]}),e.jsxs("p",{className:"mt-2 text-sm text-gray-600",children:[n.email_masked," will no longer receive marketing email. Account emails (receipts, renewal notices) will still arrive."]}),m?e.jsx("p",{className:"mt-4 text-xs text-red-400",children:m}):n.undo_available?e.jsx("button",{onClick:()=>{u()},style:{backgroundColor:n.primary_color??"#2563eb"},className:"mt-5 rounded-md px-4 py-2 text-sm font-medium text-white",children:"Undo â keep me subscribed"}):e.jsxs("p",{className:"mt-4 text-xs text-gray-400",children:["Changed your mind? Contact ",n.society_n
3950ame," to resubscribe."]})]})]})})}function qd(t){const[s,a]=o.useState({url:null,shape:"unknown"});return o.useEffect(()=>{if(!t)return;let n=!1;const r=new Image;return r.onload=()=>{if(n)return;const{naturalWidth:i,naturalHeight:l}=r,m=l?i/l:0;a({url:t,shape:m>=.85&&m<=1.15?"round":"wide"})},r.onerror=()=>{n||a({url:t,shape:"failed"})},r.src=t,()=>{n=!0}},[t]),s.url===t?s.shape:"unknown"}const i3="Manage your membership, register for events, and stay connected with your community, all in one place.",Cu=["M-40 170 C 140 90, 300 250, 470 160 S 760 70, 920 150","M-40 200 C 160 130, 330 270, 500 190 S 780 110, 920 185","M-40 230 C 180 170, 350 290, 520 220 S 800 150, 920 215","M-40 255 C 200 205, 370 300, 540 245 S 820 185, 920 240"],l3=[{className:"pl-comet stroke-[var(--login-accent)]",width:1.8,dash:"110 890"},{className:"pl-comet pl-comet-2 stroke-[var(--login-streak)]",width:1.6,dash:"80 920"},{className:"pl-comet pl-comet-3 stroke-[var(--login-accent)] [stroke-opacity:.7]",width:1.4,dash:"140 860"},{className:"pl-comet pl-comet-4 stroke-white [stroke-opacity:.5]",width:1.2,dash:"60 940"}],Go="pl-seal absolute left-[74px] top-[74px] h-[132px] w-[132px] rounded-full";function Hf({societyName:t,logoUrl:s,logoShape:a,loading:n=!1,adaptive:r=!1,className:i}){const l=a==="failed"?null:s;return e.jsxs("div",{className:me("pl-rise flex min-h-12 items-center gap-3 [animation-delay:60ms]",i),children:[l&&e.jsx("img",{src:l,alt:t,className:me("w-auto object-contain",a==="wide"?"h-12 max-w-[200px]":"h-10 max-w-[40px]")}),(!l||a==="round")&&!n&&e.jsxs("div",{className:"flex flex-col gap-px",children:[e.jsx("div",{className:me("text-[15px] font-bold tracking-[0.02em]",r?"text-foreground":"text-[#0F1B2D]"),children:_g(t)}),e.jsx("div",{className:me("text-xs font-medium uppercase tracking-[0.08em]",r?"text-muted-foreground":"text-[#5B6576]"),children:"Member portal"})]})]})}function Id({societyName:t,logoUrl:s,logoShape:a,loading:n=!1,websiteUrl:r,eyebrow:i="Member portal",tagline:l=i3,className:m}){const c=a==="failed"?null:s,d=t.split(/\s+/);return e.jsxs("section",{"aria-label":t,className:me("portal-auth relative hidden flex-col items-center [justify-content:safe_center] overflow-hidden bg-[var(--login-deep)] px-12 pb-[200px] pt-20 text-center text-white lg:flex [@media(max-height:820px)]:pb-[120px] [@media(max-height:820px)]:pt-10",m),children:[e.jsx("div",{"aria-hidden":"true",className:"pl-orb-a pointer-events-none absolute -left-[120px] -top-[160px] h-[560px] w-[560px] rounded-full"}),e.jsx("div",{"aria-hidden":"true",className:"pl-orb-b pointer-events-none absolute -bottom-[200px] -right-[160px] h-[620px] w-[620px] rounded-full"}),e.jsx("div",{"aria-hidden":"true",className:"pl-grid pointer-events-none absolute inset-0"}),e.jsxs("div",{"aria-hidden":"true",className:"pl-fade relative h-[280px] w-[280px] flex-shrink-0 [animation-delay:200ms] [@media(max-height:820px)]:[zoom:0.72]",children:[e.jsx("svg",{className:"pl-ring-slow absolute inset-0",viewBox:"0 0 280 280",children:e.jsx("circle",{cx:"140",cy:"140",r:"104",fill:"none",strokeOpacity:".7",strokeWidth:"1.5",strokeDasharray:"2 9",strokeLinecap:"round",className:"stroke-[var(--login-accent)]"})}),e.jsxs("svg",{className:"pl-ring-fast absolute inset-0",viewBox:"0 0 280 280",children:[e.jsx("circle",{cx:"140",cy:"140",r:"132",fill:"none",stroke:"rgba(255,255,255,.14)",strokeWidth:"1"}),e.jsx("circle",{cx:"140",cy:"8",r:"4",className:"fill-[var(--login-accent)]"}),e.jsx("circle",{cx:"140",cy:"8",r:"9",fillOpacity:".2",className:"fill-[var(--login-accent)]"})]}),e.jsx("div",{className:"pl-sonar absolute left-[74px] top-[74px] h-[132px] w-[132px] rounded-full border border-[var(--login-accent)]"}),e.jsx("div",{className:"pl-sonar pl-sonar-late absolute left-[74px] top-[74px] h-[132px] w-[132px] rounded-full border border-[var(--login-accent)]"}),c&&a==="round"&&e.jsx("img",{src:c,alt:"",className:me(Go,"object-cover")}),c&&a==="wide"&&e.jsx("div",{className:me(Go,"flex items-center justify-center bg-white p-3.5"),children:e.jsx("img",{src:c,alt:"",className:"max-h-full max-w-full object-contain"})}),!c&&!n&&e.jsx("div",{className:me(Go,"pl-serif flex items-center justify-center bg-white/10 text-5xl text-[var(--login-accent)]"),children:t.charAt(0)})]}),e.jsxs("div",{className:"relative mt-7 flex flex-col items-center gap-[18px] [@media(max-height:820px)]:mt-3 [@media(max-height:820px)]:gap-3",children:[e.jsxs("div",{className:"pl-rise flex items-center gap-3 text-xs font-semibold uppercase tracking-[0.22em] text-[var(--login-accent)] [animation-delay:300ms]",children:[e.jsx("span",{"aria-hidden":"true",className:"h-px w-7 bg-[var(--login-accent)]"}),i,e.jsx("span",{"aria-hidden":"true",className:"h-px w-7 bg-[var(--login-accent)]"})]}),!n&&e.jsx("h2",{className:"pl-headline pl-serif m-0 text-[clamp(40px,3.8vw,54px)] font-medium leading-[1.08] tracking-[-0.01em] [text-wrap:balance]",children:d.map((u,h)=>e.jsxs(o.Fragment,{children:[h>0&&" ",e.jsx("span",{children:h===d.length-1?e.jsx("em",{className:"italic text-[var(--login-accent)]",children:u}):u})]},h))}),e.jsx("p",{className:"pl-rise max-w-[480px] text-[17px] leading-relaxed text-white/80 [animation-delay:760ms]",children:l}),r&&e.jsxs("a",{href:r,target:"_blank",rel:"noopener noreferrer",className:"pl-site-link pl-rise flex items-center gap-1.5 rounded text-sm font-medium text-white/80 outline-offset-2 transition-colors [animation-delay:860ms] hover:text-[var(--login-accent)] focu
3950s-visible:outline focus-visible:outline-2 focus-visible:outline-[var(--login-accent)]",children:["Visit the ",_g(t)," website",e.jsx(Bp,{className:"pl-arrow h-3.5 w-3.5","aria-hidden":"true"})]})]}),e.jsxs("svg",{"aria-hidden":"true",className:"pl-waves pl-fade pointer-events-none absolute bottom-0 left-0 h-[260px] w-full [animation-delay:500ms] [@media(max-height:820px)]:h-[150px]",viewBox:"0 0 880 260",preserveAspectRatio:"none",children:[Cu.map(u=>e.jsx("path",{d:u,stroke:"rgba(255,255,255,.07)",strokeWidth:"1.2"},u)),l3.map((u,h)=>e.jsx("path",{d:Cu[h],pathLength:1e3,strokeWidth:u.width,strokeDasharray:u.dash,className:u.className},u.dash))]})]})}const o3=600;function c3(){return window.matchMedia?.("(prefers-reduced-motion: reduce)").matches??!1}function d3(){return e.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",className:"text-[var(--portal-primary)]",children:[e.jsx("path",{d:"M12 11c0 3.5-1 6.5-2.5 9"}),e.jsx("path",{d:"M8.5 7.5A5 5 0 0 1 17 11c0 2-.2 3.9-.7 5.6"}),e.jsx("path",{d:"M5.5 9.5a7.5 7.5 0 0 1 1-2.8"}),e.jsx("path",{d:"M6 13c0 2.3-.6 4.3-1.5 6"}),e.jsx("path",{d:"M14.5 11c0 3-.6 5.8-1.8 8.2"}),e.jsx("path",{d:"M8 3.8A9.5 9.5 0 0 1 21 11c0 1.6-.1 3.2-.4 4.7"})]})}function Jf(){return e.jsxs("svg",{className:"animate-spin",width:"18",height:"18",viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",children:[e.jsx("circle",{cx:"12",cy:"12",r:"9",stroke:"currentColor",strokeOpacity:".3",strokeWidth:"2.5"}),e.jsx("path",{d:"M21 12a9 9 0 0 0-9-9",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round"})]})}function Pu({phase:t,idleLabel:s,loadingLabel:a,doneLabel:n}){return e.jsxs("button",{type:"submit","aria-busy":t!=="idle","aria-live":"polite",disabled:t!=="idle",className:"pl-cta pl-focus mt-1 flex h-[52px] w-full items-center justify-center gap-2.5 rounded-xl bg-[var(--portal-primary)] text-base font-semibold text-[var(--portal-primary-fg)] disabled:cursor-progress",children:[t==="idle"&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:s}),e.jsx(as,{className:"pl-arrow h-[18px] w-[18px]","aria-hidden":"true"})]}),t==="loading"&&e.jsxs(e.Fragment,{children:[e.jsx(Jf,{}),e.jsx("span",{children:a})]}),t==="done"&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"pl-pop flex h-[22px] w-[22px] items-center justify-center rounded-full bg-[var(--login-accent)]",children:e.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",className:"stroke-[var(--login-deep)]",children:e.jsx("path",{className:"pl-check",d:"m5 12.5 4.5 4.5L19 7.5"})})}),e.jsx("span",{children:n})]})]})}const Yo="pl-field flex h-[50px] items-center gap-2.5 rounded-xl border border-[#DCE1E8] bg-white px-3.5",Ho="h-full w-full border-0 bg-transparent p-0 text-[15px] text-[#0F1B2D] shadow-none outline-none placeholder:text-[#8A94A6] focus:shadow-none focus:ring-0",Jo="pl-ficon h-[18px] w-[18px] flex-shrink-0 text-[#8A94A6]",Zo="text-sm font-semibold text-[#26303F]",Xo="pl-focus rounded font-semibold text-[var(--portal-primary)] hover:underline",Au="pl-focus relative h-full rounded-[9px] text-sm font-semibold text-[#6B7486] focus-visible:ring-0 focus-visible:ring-offset-0 data-[state=active]:bg-transparent data-[state=active]:text-[#0F1B2D] data-[state=active]:shadow-none";function Eu(){const[t]=ws(),s=qs(),a=t.get("redirect"),n=ta(),[r,i]=o.useState(()=>n.state?.email?.toString()??""),[l,m]=o.useState(""),[c,d]=o.useState(!1),[u,h]=o.useState("password"),p=t.get("error")==="access_restricted"?"Your account does not have portal access. Please contact the society.":"",[x,f]=o.useState(p),b=t.get("reset")==="success",[N,j]=o.useState(!1),[w,v]=o.useState(!1),{login:k,loginWithPasskey:S}=ft(),_=kt(),y=us(),C=io(),{data:P,isLoading:A}=ma(s||void 0),E=Nd(P?.society?.primary_color);Ra(P?.society?.favicon_url);const Q=P?.society?.logo_url,U=Q?`${ds}${Q}`:null,D=qd(U),[K,xe]=o.useState(""),[z,ae]=o.useState(!1),[ue,_e]=o.useState(!1),[ee,se]=o.useState(!1),le=o.useRef(void 0);if(o.useEffect(()=>()=>window.clearTimeout(le.current),[]),!s)return e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background px-4",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-xl font-semibold text-foreground",children:"Invalid portal link"}),e.jsx("p",{className:"mt-2 text-muted-foreground",children:"Please check your URL and try again."})]})});const oe=ke=>{if(c3()){ke();return}le.current=window.setTimeout(ke,o3)},Pe=async ke=>{if(ke.preventDefault(),!N){f(""),j(!0);try{await k(r,l,s);const ve=a&&a.startsWith("/")?y(a):y("/dashboard");_(ve,{replace:!0})}catch(ve){const Ne=px(ve);if(Ne){_(y("/complete-payment"),{state:{resumeToken:Ne}});return}const Qe=ve?.response;Qe?.status===401?f("Invalid email or password"):Qe?.status===403?f(typeof Qe.data?.detail=="string"?Qe.data.detail:"Your account does not have portal access."):Qe?.status===404?f("Society not found"):f("Login failed. Please try again.")}finally{j(!1)}}},M=async ke=>{if(ke.preventDefault(),!(ue||ee)){_e(!0),f("");try{await Me.post("/portal/magic-link",{email:K,society_slug:s}),se(!0),oe(()=>{se(!1),ae(!0)})}catch(ve){const Ne=ve?.response;Ne?.status===429?f("Too many requests. Please wait a moment and try again."):Ne?.data?.detail?f(Ne.data.detail):f("Failed to send login link. Please try again.")}finally{_e(!1)}}},I=async()=>{f(""),v(!0);try{await S(s);const ke=a&&a.startsWith("/")?y(a):y("/dashboard");_(ke,{replace:!0})}catch(ke){ke instanceof Error&&ke.name==="NotAllowedError"||f("Passkey authentication failed. Try signing in with your password.")}finally{v(!1)}},R=P?.society?.name||s?.toUpperCase()||"Member Portal",X=P?.society?.website_url,Se=N?"loading":"idle",ce=ee?"done":ue?"loading":"idle";return e.jsxs("div",{className:"portal-auth min-h-screen bg-[#FBFAF7] text-[#0F1B2D] antialiased lg:grid lg:grid-cols-[minmax(480px,560px)_minmax(0,1fr)]",style:E,children:[e.jsxs("section",{"aria-label":"Sign in",className:"flex min-h-screen flex-col justify-between gap-10 px-5 pb-7 pt-8 lg:px-[clamp(24px,5.5vw,80px)] lg:pb-9 lg:pt-11",children:[e.jsx(Hf,{societyName:R,logoUrl:U,logoShape:D,loading:A}),e.jsxs("div",{className:"mx-auto flex w-full max-w-[400px] flex-col gap-[22px] lg:mx-0",children:[e.jsxs("div",{className:"pl-rise [animation-delay:140ms]",children:[e.jsx("h1",{className:"text-[36px] font-semibold leading-[1.1] tracking-[-0.02em]",children:"Welcome back"}),e.jsx("p",{className:"mt-2 text-base text-[#5B6576]",children:"Sign in to your member account."})]}),b&&e.jsxs("div",{className:"flex items-center gap-2 rounded-xl border border-emerald-200 bg-emerald-50 px-4 py-3",children:[e.jsx(Kt,{className:"h-4 w-4 flex-shrink-0 text-emerald-600"}),e.jsx("p",{className:"text-sm text-emerald-800",children:"Password reset successfully. Sign in with your new password."})]}),x&&e.jsx("div",{role:"alert",className:"rounded-xl border border-red-200 bg-red-50 px-4 py-3",children:e.jsx("p",{className:"text-sm text-red-700",children:x})}),C&&e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",onClick:I,disabled:w,className:"pl-ghost pl-focus pl-rise flex h-[50px] items-center justify-center gap-2.5 rounded-xl border border-[#DCE1E8] bg-white text-[15px] font-semibold [animation-delay:220ms] disabled:cursor-progress",children:w?e.jsxs(e.Fragment,{children:[e.jsx(Jf,{}),"Waiting for deviceâ¦"]}):e.jsxs(e.Fragment,{children:[e.jsx(d3,{}
3950),"Sign in with passkey"]})}),e.jsxs("div",{className:"pl-rise flex items-center gap-3.5 [animation-delay:280ms]",children:[e.jsx("span",{className:"h-px flex-1 bg-[#E3E7ED]"}),e.jsx("span",{className:"text-xs font-semibold uppercase tracking-[0.12em] text-[#8A94A6]",children:"or"}),e.jsx("span",{className:"h-px flex-1 bg-[#E3E7ED]"})]})]}),e.jsxs(Ur,{value:u,onValueChange:ke=>h(ke==="magic-link"?"magic-link":"password"),className:"flex w-full flex-col gap-[22px]",children:[e.jsxs(ir,{"aria-label":"Sign-in method",className:"pl-rise relative grid h-[46px] w-full grid-cols-2 rounded-xl bg-[#EEF1F5] p-1 [animation-delay:340ms]",children:[e.jsx("span",{"aria-hidden":"true",className:me("pl-indicator absolute left-1 top-1 h-[38px] w-[calc(50%-4px)] rounded-[9px] bg-white shadow-[0_1px_2px_rgba(15,27,45,.08),0_4px_12px_rgba(15,27,45,.06)]",u==="magic-link"&&"translate-x-full")}),e.jsx(bs,{value:"password",className:Au,children:"Password"}),e.jsx(bs,{value:"magic-link",className:Au,children:"Magic link"})]}),e.jsxs("div",{className:"pl-rise [animation-delay:420ms]",children:[e.jsx(js,{value:"password",className:"mt-0",children:e.jsxs("form",{onSubmit:Pe,className:"flex flex-col gap-[18px]",children:[e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("label",{htmlFor:"email",className:Zo,children:"Email"}),e.jsxs("div",{className:Yo,children:[e.jsx($t,{className:Jo,"aria-hidden":"true"}),e.jsx("input",{id:"email",type:"email",placeholder:"[email protected]",value:r,onChange:ke=>i(ke.target.value),required:!0,autoComplete:"email",className:Ho})]})]}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsxs("div",{className:"flex items-baseline justify-between",children:[e.jsx("label",{htmlFor:"password",className:Zo,children:"Password"}),e.jsx(je,{to:y("/forgot-password"),className:me(Xo,"text-[13px]"),children:"Forgot password?"})]}),e.jsxs("div",{className:me(Yo,"pr-1.5"),children:[e.jsx(Ys,{className:Jo,"aria-hidden":"true"}),e.jsx("input",{id:"password",type:c?"text":"password",placeholder:"Enter your password",value:l,onChange:ke=>m(ke.target.value),required:!0,autoComplete:"current-password",className:Ho}),e.jsx("button",{type:"button",onClick:()=>d(ke=>!ke),"aria-pressed":c,"aria-label":c?"Hide password":"Show password",className:"pl-focus flex h-[38px] w-[38px] flex-shrink-0 items-center justify-center rounded-lg text-[#6B7486] transition-colors hover:text-[var(--portal-primary)]",children:c?e.jsx(Er,{className:"h-[18px] w-[18px]","aria-hidden":"true"}):e.jsx(ca,{className:"h-[18px] w-[18px]","aria-hidden":"true"})})]})]}),e.jsx(Pu,{phase:Se,idleLabel:"Sign in",loadingLabel:"Signing inâ¦"})]})}),e.jsx(js,{value:"magic-link",className:"mt-0",children:z?e.jsxs("div",{className:"py-6 text-center",children:[e.jsx("div",{className:"mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-[var(--portal-primary-light)]",children:e.jsx($t,{className:"h-6 w-6 text-[var(--portal-primary)]","aria-hidden":"true"})}),e.jsx("h3",{className:"mb-2 text-lg font-semibold",children:"Check your email"}),e.jsxs("p",{className:"mb-4 text-sm text-[#5B6576]",children:["We sent a login link to",e.jsx("br",{}),e.jsx("span",{className:"font-medium text-[#0F1B2D]",children:K})]}),e.jsxs("p",{className:"text-xs text-[#5B6576]",children:["Click the link in the email to sign in.",e.jsx("br",{}),"The link expires in 4 hours."]}),e.jsx("button",{type:"button",onClick:()=>{ae(!1),xe("")},className:me(Xo,"mt-4 text-sm"),children:"Use a different email"})]}):e.jsxs("form",{onSubmit:M,className:"flex flex-col gap-[18px]",children:[e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("label",{htmlFor:"magic-email",className:Zo,children:"Email"}),e.jsxs("div",{className:Yo,children:[e.jsx($t,{className:Jo,"aria-hidden":"true"}),e.jsx("input",{id:"magic-email",type:"email",placeholder:"[email protected]",value:K,onChange:ke=>xe(ke.target.value),readOnly:ce!=="idle",required:!0,autoComplete:"email",className:Ho})]})]}),e.jsx("p",{className:"-mt-1 text-sm leading-normal text-[#5B6576]",children:"We'll email you a secure link that signs you in instantly. No password needed."}),e.jsx(Pu,{phase:ce,idleLabel:"Email me a sign-in link",loadingLabel:"Sending linkâ¦",doneLabel:"Check your inbox"})]})})]})]}),e.jsxs("p",{className:"pl-rise text-center text-sm text-[#5B6576] [animation-delay:500ms]",children:["Don't have an account?"," ",e.jsx(je,{to:y("/signup"),className:Xo,children:"Sign up"})]})]}),e.jsxs("div",{className:"pl-fade flex items-center gap-2 text-xs text-[#6B7486] [animation-delay:700ms]",children:[e.jsx("span",{children:"Powered by"}),e.jsx("img",{src:pn,alt:"Korevera",className:"h-3.5 w-auto object-contain"})]})]}),e.jsx(Id,{societyName:R,logoUrl:U,logoShape:D,loading:A,websiteUrl:X})]})}const Zs={getEvents:async t=>(await Me.get("/portal/events",{params:t?.includeChildren?{include_children:!0}:void 0})).data,getEvent:async t=>(await Me.get(`/portal/events/${t}`)).data,getProducts:async()=>(await Me.get("/portal/products")).data,getDonationCampaigns:async()=>(await Me.get("/portal/donation-campaigns")).data,getMyDonations:async()=>(await Me.get("/portal/my-donations")).data,getMyRegistrations:async()=>(await Me.get("/portal/my-registrations")).data,validatePromoCode:async(t,s="all")=>(await Me.post("/portal/promo-code/validate",{code:t,scope:s})).data,pricePreview:async t=>(await Me.post("/portal/checkout/price-preview",t)).data,checkout:async(t,s)=>(await Me.post("/portal/checkout",{items:t,promo_code:s||null})).data,confirmCheckout:async(t,s)=>(await Me.post("/portal/checkout/confirm",{order_id:t,payment_intent_id:s})).data,payWithSavedCard:async t=>(await Me.post("/portal/checkout/pay-with-saved-card",{order_id:t})).data,getMyOrders:async(t=1,s=20)=>(await Me.get("/portal/my-orders",{params:{page:t,size:s}})).data,getMyOrder:async t=>(await Me.get(`/portal/my-orders/${t}`)).data,downloadOrderReceipt:async t=>(await Me.get(`/portal/my-orders/${t}/receipt`,{responseType:"blob"})).data};function Zf(t){const{isAuthenticated:s}=ft(),a=!!t?.includeChildren;return re({queryKey:["portal","events",{includeChildren:a}],queryFn:()=>Zs.getEvents({includeChildren:a}),enabled:s})}function m3(t){const{isAuthenticated:s}=ft();return re({queryKey:["portal","events",t],queryFn:()=>Zs.getEvent(t),enabled:s&&!!t})}function u3(){const{isAuthenticated:t}=ft();return re({queryKey:["portal","products"],queryFn:()=>Zs.getProducts(),enabled:t})}function h3(){const{isAuthenticated:t}=ft();return re({queryKey:["portal","donation-campaigns"],queryFn:()=>Zs.getDonationCampaigns(),enabled:t})}function p3(t=!0){const{isAuthenticated:s}=ft();return re({queryKey:["portal","my-donations"],queryFn:()=>Zs.getMyDonations(),enabled:s&&t})}function x3(){return W({mutationFn:({code:t,scope:s})=>Zs.validatePromoCode(t,s)})}function Xf(){return W({mutationFn:({items:t,promoCode:s})=>Zs.checkout(t,s)})}function ey(){const t=J();return W({mutationFn:({orderId:s,paymentIntentId:a})=>Zs.confirmCheckout(s,a),onSuccess:()=>{t.invalidateQueries({queryKey:["portal","events"]}),t.invalidateQueries({queryKey:["portal","products"]}),t.invalidateQueries({queryKey:["portal","my-registrations"]}),t.invalidateQueries({queryKey:["portal","payments"]}),t.invalidateQueries({queryKey:["portal","invoices"]}),t.invalidateQueries({queryKey:["portal","my-donations"]}),t.invalidateQueries({queryKey:["portal","donation-campaigns"]}),t.invalidateQueries({queryKey:["portal","dashboard-stats"]}),t.invalidateQueries({queryKey:["portal","my-orders"]})}})}function ty(){const t=J();return W({mutationFn:s=>Zs.payWithSavedCard(s),onSuccess:()=>{t.invalidateQueries({queryKey:["portal","events"]}),t.invalidateQueries({queryKey:["portal","products"]}),t.invalidateQueries({queryKey:["portal","my-registrations"]}),t.invalidateQueries({queryKey:["portal","payments"]}),t.invalidateQueries({queryKey:["portal","invoices"]}),t.invalidateQueries({queryKey:["portal","my-donations"]}),t.invalidateQueries({queryKey:["portal","donation-campaigns"]}),t.invalidateQueries({queryKey:["portal","dashboard-stats"]}),t.invalidateQueries({queryKey:["portal","my-orders"]})}})}function g3(t=1,s=20){const{isAuthenticated:a}=ft();return re({queryKey:["portal","my-orders",t,s],queryFn:()=>Zs.getMyOrders(t,s),enabled:a})}function f3(t){const{isAuthenticated:s}=ft();return re({queryKey:["portal","my-orders",t],queryFn:()=>Zs.getMyOrder(t),enabled:s&&!!t})}const Fi={getActivePolls:async()=>(await Me.get("/portal/polls")).data,getPoll:async t=>(await Me.get(`/portal/polls/${t}`)).data,submitResponse:async(t,s)=>(await Me.post(`/portal/polls/${t}/respond`,s)).data,getPollResults:async t=>(await Me.get(`/portal/polls/${t}/results`)).data,getAnnouncements:async()=>(await Me.get("/portal/announcements")).data};function y3(t=!0){const{isAuthenticated:s}=ft();return re({queryKey:["portal","polls"],queryFn:()=>Fi.getActivePolls(),enabled:s&&t})}function b3(t){const{isAuthenticated:s}=ft();return re({queryKey:["portal","polls",t],queryFn:()=>Fi.getPoll(t),enabled:s&&!!t})}function j3(){const t=J();return W({mutationFn:({pollId:s,data:a})=>Fi.submitResponse(s,a),onSuccess:()=>{t.invalidateQueries({queryKey:["portal","polls"]})}})}function v3(t){const{isAuthenticated:s}=ft();return re({queryKey:["portal","poll-results",t],queryFn:()=>Fi.getPollResults(t),enabled:s&&!!t})}function w3(t=!0){const{isAuthenticated:s}=ft();return re({queryKey:["portal","announcements"],queryFn:()=>Fi.getAnnouncements(),enabled:s&&t})}const zr={getCommittees:async()=>(await Me.get("/portal/committees")).data,getMyCommittees:async()=>(await Me.get("/portal/my-committees")).data,getOpenings:async()=>(await Me.get("/portal/committee-openings")).data,applyForOpening:async t=>(await Me.post("/portal/committee-openings/apply",t)).data,withdrawApplication:async t=>{await Me.delete(`/portal/committee-openings/applications/${t}`)},getMyApplications:async()=>(await Me.get("/portal/committee-openings/my-applications")).data};function N3(){const{isAuthenticated:t}=ft();return re({queryKey:["portal","committees"],queryFn:()=>zr.getCommittees(),enabled:t})}function sy(t=!0){const{isAuthenticated:s}=ft();return re({queryKey:["portal","my-committees"],queryFn:()=>zr.getMyCommittees(),enabled:s&&t})}function ay(t=!0){const{isAuthenticated:s}=ft();return re({queryKey:["portal","committee-openings"],queryFn:()=>zr.getOpenings(),enabled:s&&t})}function k3(){const t=J();return W({mutationFn:s=>zr.applyForOpening(s),onSuccess:()=>{t.invalidateQueries({queryKey:["portal","committee-openings"]}),t.invalidateQueries({queryKey:["portal","my-applications"]})}})}function _3(){const t=J();return W({mutationFn:s=>zr.withdrawApplication(s),onSuccess:()=>{t.invalidateQueries({queryKey:["portal","committee-openings"]}),t.invalidateQueries({queryKey:["portal","my-applications"]})}})}function S3(){const{isAuthenticated:t}=ft();return re({queryKey:["portal","my-applications"],queryFn:()=>zr.getMyApplications(),enabled:t})}const C3=[25,50,100];function P3({onSuccess:t}){const s=mn(),a=un(),[n,r]=o.useState(!1),[i,l]=o.useState(null),[m,c]=o.useState(!1),d=async u=>
3950{if(u.preventDefault(),!s||!a||!m)return;r(!0),l(null);const h=await s.confirmPayment({elements:a,confirmParams:{return_url:window.location.href},redirect:"if_required"});h.error?(l(h.error.message||"Payment failed"),r(!1)):h.paymentIntent?.status==="succeeded"?t(h.paymentIntent.id):(l("Unexpected payment status"),r(!1))};return e.jsxs("form",{onSubmit:d,className:"space-y-3",children:[e.jsx(hn,{onReady:()=>c(!0)}),i&&e.jsxs("div",{className:"flex items-center gap-2 text-sm text-red-600",children:[e.jsx(Dt,{className:"h-4 w-4 shrink-0"}),i]}),e.jsx(g,{type:"submit",disabled:!s||!m||n,className:"w-full bg-blue-600 text-white hover:bg-blue-700",size:"sm",children:n?e.jsxs(e.Fragment,{children:[e.jsx(He,{className:"mr-2 h-4 w-4 animate-spin"}),"Processing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ys,{className:"mr-2 h-4 w-4"}),"Pay Now"]})})]})}function A3({savedCard:t,onUseSavedCard:s,onUseNewCard:a,isProcessing:n,error:r}){const i={visa:"Visa",mastercard:"Mastercard",amex:"Amex",discover:"Discover"};return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"rounded-lg border bg-muted p-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Qt,{className:"h-5 w-5 text-muted-foreground"}),e.jsx("div",{className:"flex-1",children:e.jsxs("p",{className:"text-sm font-medium text-foreground",children:[i[t.brand.toLowerCase()]||t.brand," â¢â¢â¢â¢"," ",t.last4]})}),e.jsx(Xt,{className:"h-4 w-4 text-green-600"})]})}),r&&e.jsxs("div",{className:"flex items-center gap-2 text-sm text-red-600",children:[e.jsx(Dt,{className:"h-4 w-4 shrink-0"}),r]}),e.jsx(g,{onClick:s,disabled:n,className:"w-full bg-blue-600 text-white hover:bg-blue-700",size:"sm",children:n?e.jsxs(e.Fragment,{children:[e.jsx(He,{className:"mr-2 h-4 w-4 animate-spin"}),"Processing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ys,{className:"mr-2 h-4 w-4"}),"Pay with Saved Card"]})}),e.jsx("button",{type:"button",onClick:a,className:"w-full py-1 text-xs text-muted-foreground hover:text-foreground",children:"Use a different card"})]})}function E3(){const{data:t,isLoading:s}=h3(),a=Xf(),n=ey(),r=J(),i=ty(),[l,m]=o.useState(null),[c,d]=o.useState("idle"),[u,h]=o.useState(new Set),p=o.useCallback(z=>{h(ae=>{const ue=new Set(ae);return ue.has(z)?ue.delete(z):ue.add(z),ue})},[]),[x,f]=o.useState(""),[b,N]=o.useState(null),[j,w]=o.useState(null),[v,k]=o.useState(null),[S,_]=o.useState(!0),[y,C]=o.useState(!1),[P,A]=o.useState(null),E=()=>{m(null),d("idle"),f(""),N(null),w(null),k(null),_(!0),C(!1),A(null)},Q=z=>{m(z),d("amount"),f(""),k(null)},U=()=>{const z=parseFloat(x);!z||z<1||!l||(d("paying"),k(null),a.mutate({items:[{type:"donation",id:null,name:l.name,unit_price:z,quantity:1,campaign_id:l.id}]},{onSuccess:ae=>{if(ae.free_order||ae.already_paid){d("success"),setTimeout(E,3e3),r.invalidateQueries({queryKey:["portal","my-donations"]}),r.invalidateQueries({queryKey:["portal","donation-campaigns"]}),r.invalidateQueries({queryKey:["portal","dashboard-stats"]}),r.invalidateQueries({queryKey:["portal","my-orders"]});return}w(ae),ae.publishable_key&&N(rd(ae.publishable_key)),_(!!ae.saved_payment_method)},onError:ae=>{const ue=ae.response?.data?.detail,_e=typeof ue=="string"?ue:ae.response?.data?.message||ae.message||"Something went wrong. Please try again.";k(_e),d("amount")}}))},D=async z=>{if(j){d("confirming");try{await n.mutateAsync({orderId:j.order_id,paymentIntentId:z}),d("success"),setTimeout(E,3e3)}catch(ae){const ue=ae.response?.data?.detail,_e=typeof ue=="string"?ue:ae.response?.data?.message||ae.message||"Payment confirmed but processing failed. Please contact support.";k(_e),d("paying")}}},K=async()=>{if(j){C(!0),A(null);try{await i.mutateAsync(j.order_id),d("success"),setTimeout(E,3e3)}catch(z){const ae=z.response?.data?.detail;A(ae||"Payment failed. Please try again or use a different card."),C(!1)}}};if(s||!t||t.length===0)return null;const xe=!!j?.saved_payment_method;return e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-pink-100 text-pink-600 dark:bg-pink-900/30 dark:text-pink-400",children:e.jsx(br,{className:"h-4 w-4"})}
3950),"Support Our Campaigns"]})}),e.jsxs($,{className:"space-y-4",children:[c==="success"&&e.jsxs("div",{className:"space-y-2 py-4 text-center",children:[e.jsx(Kt,{className:"mx-auto h-8 w-8 text-emerald-500"}),e.jsx("p",{className:"text-sm font-semibold text-emerald-700 dark:text-emerald-400",children:"Thank you for your donation!"})]}),c==="confirming"&&e.jsxs("div",{className:"py-4 text-center",children:[e.jsx(He,{className:"mx-auto h-6 w-6 animate-spin text-muted-foreground"}),e.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"Confirming your donationâ¦"})]}),c==="idle"&&t.map(z=>e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-semibold leading-tight tracking-tight",children:z.name}),z.description&&e.jsxs("div",{className:"mt-1",children:[e.jsx("p",{className:`text-xs leading-relaxed text-muted-foreground ${u.has(z.id)?"":"line-clamp-2"}`,children:z.description}),z.description.length>80&&e.jsx("button",{type:"button",onClick:()=>p(z.id),className:"mt-0.5 text-xs font-medium text-blue-600 hover:text-blue-700",children:u.has(z.id)?"Show less":"Show more"})]})]}),e.jsxs(g,{size:"sm",className:"shrink-0 bg-pink-600 font-medium text-white hover:bg-pink-700",onClick:()=>Q(z),children:[e.jsx(br,{className:"mr-1 h-3.5 w-3.5"}),"Donate"]})]}),z.goal_amount&&e.jsx("div",{className:"h-1.5 w-full overflow-hidden rounded-full bg-muted",children:e.jsx("div",{className:"h-full rounded-full bg-gradient-to-r from-pink-500 to-pink-600 transition-all",style:{width:"0%"}})})]},z.id)),c==="amount"&&l&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{onClick:E,className:"text-muted-foreground hover:text-foreground",children:e.jsx(es,{className:"h-4 w-4"})}),e.jsx("p",{className:"text-sm font-medium",children:l.name})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:C3.map(z=>e.jsxs(g,{size:"sm",variant:x===String(z)?"default":"outline",onClick:()=>f(String(z)),children:["$",z]},z))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-sm text-muted-foreground",children:"$"}),e.jsx(O,{type:"number",min:"1",step:"0.01",placeholder:"Other",value:x,onChange:z=>f(z.target.value),className:"pl-7"})]}),e.jsx(g,{size:"default",disabled:!x||parseFloat(x)<1,onClick:U,children:"Continue"})]}),v&&e.jsx("p",{className:"text-sm text-red-600",children:v})]}),c==="paying"&&l&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{onClick:E,className:"text-muted-foreground hover:text-foreground",children:e.jsx(es,{className:"h-4 w-4"})}),e.jsxs("p",{className:"text-sm font-medium",children:[l.name," â $",parseFloat(x).toFixed(2)]})]}),j&&b?xe&&S?e.jsx(A3,{savedCard:j.saved_payment_method,onUseSavedCard:K,onUseNewCard:()=>_(!1),isProcessing:y,error:P}):e.jsxs("div",{className:"space-y-2",children:[xe&&e.jsx("button",{type:"button",onClick:()=>_(!0),className:"text-xs text-blue-600 hover:text-blue-800",children:"â Use saved card"}),e.jsx(dn,{stripe:b,options:{clientSecret:j.client_secret,appearance:{theme:"stripe"}},children:e.jsx(P3,{orderId:j.order_id,onSuccess:D})})]}):e.jsx("div",{className:"flex justify-center py-6",children:e.jsx(He,{className:"h-6 w-6 animate-spin text-muted-foreground"})})]})]})]})}function Tu(t){return`profile_completion_banner_dismissed_${t}`}function T3(t){return[t.phone,t.organization,t.address_line1,t.city,t.state,t.postal_code].filter(s=>!s).length}function F3(){const{data:t}=ar(),s=us(),a=kt(),[n,r]=o.useState(!1);if(!t)return null;const i=t.is_non_member===!0,l=T3(t),m=n||localStorage.getItem(Tu(t.id))==="true";if(!(i&&l>0&&!m))return null;const d=()=>{localStorage.setItem(Tu(t.id),"true"),r(!0)},u=()=>{a(s("/profile"))};return e.jsx("div",{className:"relative overflow-hidden rounded-xl border border-blue-200 bg-blue-50 p-4 dark:border-blue-900/60 dark:bg-blue-950/30 sm:p-5",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("span",{className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-lg",style:{backgroundColor:"var(--portal-primary-light)",color:"var(--portal-primary)"},children:e.jsx(vr,{className:"h-4 w-4"})}),e.jsxs("div",{className:"min-w-0 flex-1 space-y-2",children:[e.jsxs("div",{className:"min-w-0 pr-8",children:[e.jsxs("h2",{className:"text-sm font-semibold tracking-tight text-foreground",children:["Complete your profile (",l," field",l!==1?"s":""," left)"]}),e.jsx("p",{className:"mt-0.5 text-xs text-muted-foreground",children:"Add your contact info so we can reach you about events. Takes about 30 seconds."})]}),e.jsx("div",{children:e.jsx(g,{type:"button",size:"sm",className:"bg-blue-600 text-white hover:bg-blue-700",onClick:u,children:"Open profile"})})]}),e.jsx("button",{type:"button","aria-label":"Dismiss profile completion reminder",className:"absolute right-3 top-3 flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-blue-100 hover:text-foreground dark:hover:bg-blue-900/40",onClick:d,children:e.jsx(ms,{className:"h-4 w-4"})})]})})}function R3(t){const s=bj(pt(t),new Date);return s<=0?"Today":s===1?"Tomorrow":s<30?`${s} days away`:`In ${Math.round(s/30)} month${s>=45?"s":""}`}function M3({eventAppBaseUrl:t}){const{data:s}=Zf({includeChildren:!0}),a=jg(),n=us();if(!s)return null;const r=s.filter(p=>{if(p.parent_event_id&&!p.is_registered)return!1;if(!p.start_date)return!0;const x=pt(p.start_date);return nd(x)||yj(x)});if(r.length===0)return null;const i=r[0],l=r.slice(1,3),m=r.length>3,c=async p=>{if(!t||!p.event_app_event_slug)return;const x=window.open("about:blank","_blank");try{const{token:f,base_url:b}=await a.mutateAsync(),N=`/${p.event_app_event_slug}/info`,j=`${b.replace(/\/$/,"")}/api/auth/verify-member?token=${encodeURIComponent(f)}&redirect=${encodeURIComponent(N)}`;x?x.location.href=j:window.open(j,"_blank")}catch{const f=`${t.replace(/\/$/,"")}/${p.event_app_event_slug}/info`;x?x.location.href=f:window.open(f,"_blank")}},d=p=>e.jsxs("span",{className:"inline-flex items-center gap-1.5 whitespace-nowrap",children:[e.jsx("span",{className:`h-1.5 w-1.5 shrink-0 rounded-full ${p?"bg-emerald-500":"bg-muted-foreground
3950/60"}`}),e.jsx("span",{className:"text-xs font-medium",children:p?"Registered":"Not registered"})]}),u=(p,x)=>{const f=x==="hero",b=!!t&&!!p.event_app_event_slug,N="bg-blue-600 font-medium text-white hover:bg-blue-700",j="h-7 shrink-0 px-2 text-xs font-medium text-blue-600 hover:text-blue-700";return p.is_registered?b?f?e.jsxs(g,{size:"sm",className:N,onClick:()=>c(p),disabled:a.isPending,children:["Open event",e.jsx(Rs,{className:"ml-1.5 h-3.5 w-3.5"})]}):e.jsxs(g,{size:"sm",variant:"ghost",className:j,onClick:()=>c(p),disabled:a.isPending,children:["Open",e.jsx(Rs,{className:"ml-1 h-3 w-3"})]}):null:p.external_registration_url&&/^https?:\/\//i.test(p.external_registration_url)?f?e.jsx(g,{size:"sm",className:N,asChild:!0,children:e.jsxs("a",{href:p.external_registration_url,target:"_blank",rel:"noopener noreferrer",children:["Register",e.jsx(Rs,{className:"ml-1.5 h-3.5 w-3.5"})]})}):e.jsx(g,{size:"sm",variant:"ghost",className:j,asChild:!0,children:e.jsxs("a",{href:p.external_registration_url,target:"_blank",rel:"noopener noreferrer",children:["Register",e.jsx(Rs,{className:"ml-1 h-3 w-3"})]})}):f?e.jsx(g,{size:"sm",className:N,asChild:!0,children:e.jsxs(je,{to:n(`/events/${p.id}`),children:["Register",e.jsx(as,{className:"ml-1.5 h-3.5 w-3.5"})]})}):e.jsx(g,{size:"sm",variant:"ghost",className:j,asChild:!0,children:e.jsxs(je,{to:n(`/events/${p.id}`),target:"_blank",children:["Register",e.jsx(as,{className:"ml-1 h-3 w-3"})]})})},h=i.start_date?pt(i.start_date):null;return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h2",{className:"flex items-center gap-2.5 text-lg font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 items-center justify-center rounded-lg",style:{backgroundColor:"var(--portal-primary-light)",color:"var(--portal-primary)"},children:e.jsx(Yt,{className:"h-4 w-4"})}),"Upcoming events"]}),m&&e.jsx(g,{variant:"ghost",size:"sm",asChild:!0,className:"text-muted-foreground hover:text-foreground",children:e.jsxs(je,{to:n("/events"),target:"_blank",children:["View all",e.jsx(as,{className:"ml-1 h-3.5 w-3.5"})]})})]}),e.jsx(L,{className:"min-w-0 overflow-hidden transition-shadow hover:shadow-md",children:e.jsxs("div",{className:"flex flex-col sm:flex-row",children:[e.jsxs("div",{className:"relative shrink-0 p-5 text-white sm:w-52",style:{backgroundColor:"var(--portal-primary)",backgroundImage:"linear-gradient(135deg, var(--portal-primary), color-mix(in oklab, var(--portal-primary) 65%, black))"},children:[e.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wider text-white/80",children:"Next up"}),h?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-2 text-4xl font-semibold leading-none tracking-tight",children:Be(h,"d")}),e.jsxs("div",{className:"mt-1 text-sm text-white/85",children:[Be(h,"MMM yyyy")," · ",Be(h,"EEE")]}),e.jsx("span",{className:"mt-4 inline-flex items-center gap-1 rounded-full bg-white/15 px-2.5 py-1 text-xs font-medium backdrop-blur",children:R3(i.start_date)})]}):e.jsx(Yt,{className:"mt-3 h-10 w-10 text-white/85"})]}),e.jsxs("div",{className:"flex flex-1 flex-col justify-between gap-4 p-5 sm:p-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h3",{className:"text-base font-semibold leading-tight tracking-tight sm:text-lg",children:i.name}),e.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-1.5 text-sm text-muted-foreground",children:[i.start_date&&e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Yt,{className:"h-3.5 w-3.5 shrink-0"}),Be(pt(i.start_date),"EEEE, MMMM d, yyyy")]}),i.location&&e.jsxs("a",{href:`https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(i.location)}`,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1.5 hover:text-foreground",children:[e.jsx(Fa,{className:"h-3.5 w-3.5 shrink-0"}),i.location]})]}),i.description&&e.jsx("p",{className:"line-clamp-2 text-sm leading-relaxed text-muted-foreground",children:i.description}),i.website_url&&/^https?:\/\//i.test(i.website_url)&&e.jsxs("a",{href:i.website_url,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1.5 text-sm font-medium text-blue-600 hover:text-blue-700",children:[e.jsx(bl,{className:"h-3.5 w-3.5 shrink-0"}),"Meeting page"]})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2 border-t pt-4",children:[d(i.is_registered),u(i,"hero")]})]})]})}),l.length>0&&e.jsx("div",{className:"grid gap-2 sm:grid-cols-2",children:l.map(p=>e.jsxs(L,{className:"flex min-w-0 items-center gap-3 p-3 transition-shadow hover:shadow-sm",children:[e.jsxs("div",{className:"min-w-0 flex-1 space-y-1",children:[e.jsx("p",{className:"truncate text-sm font-semibold leading-tight tracking-tight",children:p.name}),e.jsxs("p",{className:"truncate text-xs text-muted-foreground",children:[p.start_date&&Be(pt(p.start_date),"MMM d, yyyy"),p.start_date&&p.location?" · ":"",p.location]}),d(p.is_registered)]}),u(p,"compact")]},p.id))})]})}function D3({societyName:t}){const s=aN(),a=async()=>{const n=window.open("about:blank","_blank");try{const{token:r,base_url:i}=await s.mutateAsync(),l=`${i.replace(/\/$/,"")}/api/auth/verify-member?token=${encodeURIComponent(r)}&redirect=/video-library`;n?n.location.href=l:window.open(l,"_blank")}catch{n&&n.close(),alert("Could not open Video Library. Please try again.")}};return e.jsx(L,{className:"min-w-0 overflow-hidden transition-shadow hover:shadow-sm",children:e.jsx($,{className:"p-4",children:e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-3",children:[e.jsx("div",{className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-purple-100 text-purple-600 dar
3950k:bg-purple-900/30 dark:text-purple-400",children:e.jsx(Qc,{className:"h-4 w-4"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("h3",{className:"truncate text-sm font-semibold tracking-tight",children:"Video Library"}),e.jsxs("p",{className:"hidden truncate text-xs text-muted-foreground sm:block",children:["Watch educational lectures from ",t]})]})]}),e.jsxs(g,{onClick:a,disabled:s.isPending,className:"shrink-0 bg-blue-600 font-medium text-white hover:bg-blue-700",size:"sm",children:[s.isPending?"Openingâ¦":"Watch",e.jsx(Rs,{className:"ml-1.5 h-3.5 w-3.5"})]})]})})})}function L3({societyName:t}){const s=jg(),a=async()=>{const n=window.open("about:blank","_blank");try{const{token:r,base_url:i}=await s.mutateAsync(),l=`${i.replace(/\/$/,"")}/api/auth/verify-member?token=${encodeURIComponent(r)}&redirect=/faculty-portal`;n?n.location.href=l:window.open(l,"_blank")}catch{n&&n.close(),alert("Could not open the Faculty Portal. Please try again.")}};return e.jsx(L,{className:"min-w-0 overflow-hidden transition-shadow hover:shadow-sm",children:e.jsx($,{className:"p-4",children:e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-3",children:[e.jsx("div",{className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-blue-100 text-blue-600 dark:bg-blue-900/30 dark:text-blue-400",children:e.jsx(ed,{className:"h-4 w-4"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("h3",{className:"truncate text-sm font-semibold tracking-tight",children:"Faculty Portal"}),e.jsxs("p",{className:"hidden truncate text-xs text-muted-foreground sm:block",children:["Manage your sessions, slides, and bio for ",t]})]})]}),e.jsxs(g,{onClick:a,disabled:s.isPending,className:"shrink-0 bg-blue-600 font-medium text-white hover:bg-blue-700",size:"sm",children:[s.isPending?"Openingâ¦":"Open portal",e.jsx(Rs,{className:"ml-1.5 h-3.5 w-3.5"})]})]})})})}function $3({open:t,onOpenChange:s,pollId:a}){const{data:n,isLoading:r}=b3(t?a:void 0),i=j3(),[l,m]=o.useState({});o.useEffect(()=>{t&&m({})},[t,a]);const c=(u,h)=>{m(p=>({...p,[u]:h}))},d=u=>{if(u.preventDefault(),!n)return;const h=n.questions.map(p=>({question_id:p.id,answer_value:l[p.id]||null}));i.mutate({pollId:a,data:{answers:h}},{onSuccess:()=>s(!1)})};return e.jsx(Fe,{open:t,onOpenChange:s,children:e.jsxs(Te,{className:"max-h-[90vh] max-w-lg overflow-y-auto",children:[e.jsx(Ae,{children:e.jsx(Ee,{className:"tracking-tight",children:n?.title||"Loadingâ¦"})}),r?e.jsxs("div",{className:"space-y-4",children:[e.jsx(Y,{className:"h-8 w-full"}),e.jsx(Y,{className:"h-24 w-full"})]}):n?e.jsxs("form",{onSubmit:d,className:"space-y-5",children:[n.description&&e.jsx("p",{className:"text-sm leading-relaxed text-muted-foreground",children:n.description}),n.is_anonymous&&e.jsxs("span",{className:"inline-flex items-center gap-1.5 whitespace-nowrap",children:[e.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-muted-foreground/60"}),e.jsx("span",{className:"text-xs font-medium",children:"Anonymous poll"})]}),n.questions.map(u=>e.jsx(q3,{question:u,value:l[u.id]||"",onChange:h=>c(u.id,h)},u.id)),i.isError&&e.jsx("p",{className:"text-sm font-medium text-red-600 dark:text-red-400",children:i.error?.response?.data?.detail||"Failed to submit response"}),e.jsxs(Ge,{children:[e.jsx(g,{type:"button",variant:"outline",onClick:()=>s(!1),children:"Cancel"}),e.jsx(g,{type:"submit",disabled:i.isPending,className:"bg-blue-600 font-medium text-white hover:bg-blue-700",children:i.isPending?"Submittingâ¦":"Submit response"})]})]}):null]})})}function q3({question:t,value:s,onChange:a}){const{type:n,question_text:r,options:i,is_required:l}=t;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs(T,{className:"text-sm font-medium text-foreground",children:[r,l&&e.jsx("span",{className:"ml-1 text-red-500",children:"*"})]}),n==="text"&&e.jsx(It,{value:s,onChange:m=>a(m.target.value),placeholder:"Your answerâ¦",rows:3,required:l,className:"text-foreground"}),n==="rating"&&e.jsx("div",{className:"flex gap-2",children:[1,2,3,4,5].map(m=>e.jsx("button",{type:"button",onClick:()=>a(String(m)),className:`h-10 w-10 rounded-md border text-sm font-medium transition-colors ${s===String(m)?"border-blue-600 bg-blue-600 text-white":"border-border text-muted-foreground hover:bg-muted"}`,children:m},m))}),n==="single_choice"&&Array.isArray(i)&&e.jsx("div",{className:"space-y-2",children:i.map(m=>e.jsxs("label",{className:"flex cursor-pointer items-center gap-2",children:[e.jsx("input",{type:"radio",name:t.id,value:m,checked:s===m,onChange:c=>a(c.target.value),required:l,className:"accent-blue-600"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:m})]},m))}),n==="multi_choice"&&Array.isArray(i)&&e.jsx(I3,{options:i,value:s,onChange:a}),n==="scale"&&i&&typeof i=="object"&&!Array.isArray(i)&&e.jsx(O3,{min:i.min??1,max:i.max??10,value:s,onChange:a})]})}function I3({options:t,value:s,onChange:a}){let n=[];try{n=s?JSON.parse(s):[]}catch{n=[]}const r=i=>{const l=n.includes(i)?n.filter(m=>m!==i):[...n,i];a(JSON.stringify(l))};return e.jsx("div",{className:"space-y-2",children:t.map(i=>e.jsxs("label",{className:"flex cursor-pointer items-center gap-2",children:[e.jsx("input",{type:"checkbox",checked:n.includes(i),onChange:()=>r(i),className:"accent-blue-600"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:i})]},i))})}function O3({min:t,max:s,value:a,onChange:n}){const r=a?Number(a):t;return e.jsxs("div",{className:"space-y-1",children:[e.jsx("input",{type:"range",min:t,max:s,value:r,onChange:i=>n(i.target.value),className:"w-full accent-blue-600"}),e.jsxs("div",{className:"flex justify-between text-xs text-muted-foreground",children:[e.jsx("span",{children:t}),e.jsx("span",{className:"font-medium text-muted-foreground",children:r}),e.jsx("span",{children:s})]})]})}const U3={text:"Free text",rating:"Rating",single_choice:"Single choice",multi_choice:"Multiple choice",scale:"Scale"};function z3({open:t,onOpenChange:s,pollId:a}){const{data:n,isLoading:r}=v3(t?a:void 0);return e.jsx(Fe,{open:t,onOpenChange:s,children:e.jsxs(Te,{className:"max-h-[90vh] max-w-2xl overflow-y-auto",children:[e.jsx(Ae,{children:e.jsx(Ee,{className:"tracking-tight",children:n?`Results: ${n.title}`:"Poll results"})}),r?e.jsxs("div",{className:"space-y-4",children:[e.jsx(Y,{className:"h-8 w-48"}),e.jsx(Y,{className:"h-48 w-full"})]}
3950):n?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("p",{className:"text-[11px] font-semibold uppercase tracking-wider text-muted-foreground",children:[n.total_responses.toLocaleString()," total response",n.total_responses!==1?"s":""]}),n.questions.map(i=>e.jsx(B3,{question:i},i.question_id))]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"No results available."})]})})}function B3({question:t}){const{question_text:s,type:a,total_answers:n,data:r}=t;return e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsxs(ne,{className:"pb-2",children:[e.jsxs(ie,{className:"flex items-center gap-2.5",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg",style:{backgroundColor:"var(--portal-primary-light)",color:"var(--portal-primary)"},children:e.jsx(zl,{className:"h-4 w-4"})}),s]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[n," answer",n!==1?"s":""," · ",U3[a]||a]})]}),e.jsxs($,{children:[a==="text"&&Array.isArray(r)&&e.jsx("div",{className:"max-h-40 space-y-1 overflow-y-auto",children:r.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No responses"}):r.map((i,l)=>e.jsx("p",{className:"border-b border-border pb-1.5 text-sm leading-relaxed text-muted-foreground last:border-0",children:i},l))}),(a==="single_choice"||a==="multi_choice")&&r&&typeof r=="object"&&"counts"in r&&e.jsx("div",{className:"h-40",children:e.jsx(nn,{width:"100%",height:"100%",children:e.jsxs(mi,{data:Object.entries(r.counts).map(([i,l])=>({name:i,value:l})),layout:"vertical",children:[e.jsx(_n,{type:"number"}),e.jsx(rn,{type:"category",dataKey:"name",width:100,tick:{fontSize:12}}),e.jsx(ln,{}),e.jsx(Nr,{dataKey:"value",fill:"#3b82f6",radius:[0,4,4,0]})]})})}),(a==="rating"||a==="scale")&&r&&typeof r=="object"&&"average"in r&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-2xl font-semibold tracking-tight text-foreground",children:r.average}),e.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-wider text-muted-foreground",children:"Average"}),r.distribution&&e.jsx("div",{className:"h-28",children:e.jsx(nn,{width:"100%",height:"100%",children:e.jsxs(mi,{data:Object.entries(r.distribution).sort(([i],[l])=>Number(i)-Number(l)).map(([i,l])=>({name:i,value:l})),children:[e.jsx(_n,{dataKey:"name"}),e.jsx(rn,{}),e.jsx(ln,{}),e.jsx(Nr,{dataKey:"value",fill:"#8b5cf6",radius:[4,4,0,0]})]})})})]})]})]})}const K3=[{selector:'[data-tour="portal-hero"]',title:"Your Membership Hub",description:"See your membership status, renewal date, and a personalized welcome message.",placement:"bottom"},{selector:'[data-tour="portal-stats"]',title:"Membership Stats",description:"Track your tenure, renewal countdown, membership streak, and auto-renew status.",placement:"bottom"},{selector:'[data-tour="portal-nav"]',title:"Portal Navigation",description:"Browse events, shop for products, or jump to your dashboard from the top menu.",desktopOnly:!0,placement:"bottom"},{selector:'[data-tour="portal-directory"]',title:"Member Directory",description:"Search and browse fellow members by name, location, or organization.",desktopOnly:!0,module:"directory",placement:"bottom"},{selector:'[data-tour="portal-account-menu"]',title:"My Account",description:"Access payments, invoices, subscription management, and profile settings.",desktopOnly:!0,placement:"bottom"},{selector:'[data-tour="portal-news-polls"]',title:"News & Polls",description:"Stay up to date with society announcements and vote on active polls.",placement:"bottom"},{selector:'[data-tour="portal-upcoming-events"]',title:"Upcoming Events",description:"Browse and register for upcoming events hosted by your society.",module:"commerce",placement:"bottom"},{selector:'[data-tour="portal-membership-details"]',title:"Membership Details",description:"View your membership type, join date, renewal amount, and toggle auto-renew.",placement:"top"},{selector:'[data-tour="portal-donations"]',title:"Donations",description:"Support your society by making a donation to an active campaign.",module:"commerce",placement:"top"},{selector:'[data-tour="portal-quick-actions"]',title:"Quick Actions",description:"Edit your profile, view payment history, or manage your subscription with one click.",placement:"top"}],Q3={active:"bg-emerald-500",pending:"bg-amber-500",grace:"bg-orange-500",lapsed:"bg-red-500",expired:"bg-red-500",cancelled:"bg-muted-foreground
3950/60",suspended:"bg-red-500",archived:"bg-red-500"};function Ji(t){return Number(t).toLocaleString("en-US",{style:"currency",currency:"USD"})}function W3(t){const s=/\[([^\]]+)\]\((https?:\/\/(?:[^()\s]|\([^()\s]*\))+)\)|(https?:\/\/[^\s<>"]+)/g,a=[];let n=0,r,i=0;for(;(r=s.exec(t))!==null;){r.index>n&&a.push(t.slice(n,r.index));const[l,m,c,d]=r,u=c??d;a.push(e.jsx("a",{href:u,target:"_blank",rel:"noopener noreferrer",className:`text-blue-600 underline hover:text-blue-700 ${m?"break-words":"break-all"}`,children:m??d},i++)),n=r.index+l.length}return n<t.length&&a.push(t.slice(n)),a}function V3(){const{member:t}=ft(),s=us(),a=ar(),n=xg(),r=Qa(),{data:i,isLoading:l}=a,{data:m}=n,c=m!==void 0,d=n.isError&&!c,u=n.isLoading&&!c,{data:h}=r,p=h?.is_real_member===!0,x=gg(),{data:f}=p3(p),{data:b}=y3(p),{data:N}=w3(p),{data:j}=sy(p),{data:w}=ay(p),[v,k]=o.useState(null),[S,_]=o.useState(null),[y,C]=o.useState(!1),[P,A]=o.useState(new Set),{data:E}=Qw(),Q=h?.feature_modules?.commerce_enabled===!0,U=h?.feature_modules?.committees_enabled===!0,D=h?.feature_modules?.directory_enabled===!0,K=b&&b.length>0||N&&N.length>0,xe=o.useCallback(()=>jn.listCredentials(),[]),z=`ams_portal_tour_done_${t?.id??"unknown"}`,ae=o.useMemo(()=>({commerce:Q,committees:U,directory:D}),[Q,U,D]),ue=[a,r];if(ue.some(ce=>ce.isError&&ce.data===void 0)){const ce=ue.some(ke=>ke.isFetching);return e.jsxs(L,{role:"alert",children:[e.jsx(ne,{children:e.jsx(ie,{children:"Unable to load your dashboard"})}),e.jsxs($,{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"We couldnât load your account information. Please try again."}),e.jsx(g,{disabled:ce,onClick:()=>{Promise.all(ue.map(ke=>ke.refetch()))},children:ce?"Trying againâ¦":"Try again"})]})]})}if(l||h===void 0)return e.jsxs("div",{className:"space-y-6",children:[e.jsx(Y,{className:"h-32 w-full rounded-xl"}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-3",children:[e.jsx(Y,{className:"h-24"}),e.jsx(Y,{className:"h-24"}),e.jsx(Y,{className:"h-24"})]}),e.jsx(Y,{className:"h-48"})]});const _e=i||t,ee=_e?.membership_end_date,se=ee?Jp(pt(ee),new Date):null,le=!!m?.term_length_years,oe=m?.auto_renew??!1,Pe=c&&(_e?.status==="lapsed"||_e?.status==="expired"||_e?.status==="archived"),M=h?.tenure_years??0,I=h?.join_date?Be(pt(h.join_date),"yyyy"):null,R=h?.events_attended??0,X=M>=1?`${M} Year${M!==1?"s":""}`:"New Member",Se=I?`Since ${I}`:null;return e.jsxs(Bg,{steps:K3,storageKey:z,modules:ae,children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{"data-tour":"portal-hero",className:"relative overflow-hidden rounded-xl border border-border bg-card shadow-sm",children:[e.jsx("div",{"aria-hidden":!0,className:"absolute inset-0 opacity-[0.05] dark:opacity-[0.12]",style:{background:"linear-gradient(135deg, var(--portal-primary) 0%, transparent 65%)"}}),e.jsx("div",{"aria-hidden":!0,className:"absolute -right-20 -top-20 h-56 w-56 rounded-full opacity-[0.08] blur-3xl dark:opacity-20",style:{backgroundColor:"var(--portal-primary)"}}),e.jsx("div",{className:"relative p-5 sm:p-7",children:e.jsxs("div",{className:"flex flex-col gap-5 sm:flex-row sm:items-end sm:justify-between",children:[e.jsxs("div",{className:"min-w-0 space-y-3",children:[_e?.society_name&&e.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-wider text-muted-foreground",children:_e.society_n
3950ame}),e.jsxs("h1",{className:"text-2xl font-semibold leading-tight tracking-tight text-foreground sm:text-3xl",children:["Welcome back, ",_e?.first_name]}),h?.personalized_message&&e.jsx("p",{className:"max-w-xl text-sm leading-relaxed text-muted-foreground",children:h.personalized_message}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 pt-1",children:[_e?.membership_type_name&&e.jsx("span",{className:"inline-flex items-center rounded-full px-2.5 py-1 text-xs font-medium",style:{backgroundColor:"var(--portal-primary-light)",color:"var(--portal-primary)"},children:_e.membership_type_name}),p&&e.jsxs("span",{className:"inline-flex items-center gap-1.5 whitespace-nowrap capitalize",children:[e.jsx("span",{className:`h-1.5 w-1.5 shrink-0 rounded-full ${Q3[_e?.status||""]||"bg-muted-foreground/60"}`}),e.jsx("span",{className:"text-xs font-medium",children:_e?.status||"Unknown"})]})]})]}),p&&M>=1&&e.jsx("div",{className:"hidden shrink-0 sm:block",children:e.jsxs("div",{className:"flex items-center gap-3 rounded-xl border border-border/60 bg-background/60 px-4 py-3 backdrop-blur-sm",style:{borderColor:"color-mix(in oklab, var(--portal-primary) 20%, transparent)"},children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg",style:{backgroundColor:"var(--portal-primary-light)",color:"var(--portal-primary)"},children:M>=5?e.jsx(qn,{className:"h-5 w-5"}):e.jsx(No,{className:"h-5 w-5"})}),e.jsxs("div",{className:"leading-tight",children:[e.jsx("div",{className:"text-lg font-semibold tracking-tight text-foreground",children:X}),Se&&e.jsx("div",{className:"text-[11px] text-muted-foreground",children:Se})]})]})})]})})]}),d&&e.jsx(L,{role:"alert",className:"min-w-0 overflow-hidden",children:e.jsxs($,{className:"flex flex-col gap-4 p-4 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex min-w-0 items-start gap-3",children:[e.jsx("div",{className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-amber-100 text-amber-600 dark:bg-amber-900/30 dark:text-amber-400",children:e.jsx(Bt,{className:"h-4 w-4"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-semibold tracking-tight",children:"Membership details are unavailable"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"The rest of your dashboard is still available. Try loading your membership details again."})]})]}),e.jsx(g,{variant:"outline",className:"shrink-0 text-foreground",disabled:n.isFetching,onClick:()=>{n.refetch()},children:n.isFetching?"Trying againâ¦":"Retry subscription"})]})}),le&&_e?.status==="active"&&se!==null&&se<=60&&e.jsxs("div",{className:"relative overflow-hidden rounded-xl border border-blue-200 bg-gradient-to-br from-blue-50 via-blue-50/40 to-transparent p-5 dark:border-blue-900/60 dark:from-blue-950/40 dark:via-blue-950/15 dark:to-transparent sm:p-6",children:[e.jsx("div",{"aria-hidden":!0,className:"pointer-events-none absolute -right-8 -top-8 h-40 w-40 rounded-full bg-blue-400/10 blur-3xl dark:bg-blue-500/10"}),e.jsxs("div",{className:"relative flex flex-col gap-4 sm:flex-row sm:items-center sm:gap-5",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-start gap-4",children:[e.jsx("div",{className:"shrink-0 rounded-xl bg-blue-100 p-2.5 ring-4 ring-blue-50/70 dark:bg-blue-900/40 dark:ring-blue-900/20",children:e.jsx(ea,{className:"h-5 w-5 text-blue-600 dark:text-blue-400"})}),e.jsxs("div",{className:"min-w-0 space-y-1",children:[e.jsxs("h2",{className:"text-base font-semibold tracking-tight text-blue-900 dark:text-blue-100 sm:text-lg",children:["Your ",_e?.membership_type_name," term ends soon"]}),e.jsxs("p",{className:"text-sm leading-relaxed text-blue-800/85 dark:text-blue-200/80",children:[se>0?`Your membership term ends in ${se} day${se!==1?"s":""}.`:"Your membership term ends today.",m?.converts_to_type_name?` Upgrade to ${m.converts_to_type_name} to continue your benefits.`:" Visit your subscription page for next steps."]})]})]}),e.jsx(g,{asChild:!0,className:"shrink-0 bg-blue-600 px-6 font-medium text-white shadow-sm hover:bg-blue-700",children:e.jsxs(je,{to:s("/subscription"),children:["Upgrade now",e.jsx(as,{className:"ml-2 h-4 w-4"})]})})]})]}),c&&_e?.status==="grace"&&e.jsxs("div",{className:"relative overflow-hidden rounded-xl border border-amber-200 bg-gradient-to-br from-amber-50 via-amber-50/40 to-transparent p-5 dark:border-amber-900/60 dark:from-amber-950/40 dark:via-amber-950/15 dark:to-transparent sm:p-6",children:[e.jsx("div",{"aria-hidden":!0,
3950className:"pointer-events-none absolute -right-8 -top-8 h-40 w-40 rounded-full bg-amber-400/10 blur-3xl dark:bg-amber-500/10"}),e.jsxs("div",{className:"relative flex flex-col gap-4 sm:flex-row sm:items-center sm:gap-5",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-start gap-4",children:[e.jsx("div",{className:"shrink-0 rounded-xl bg-amber-100 p-2.5 ring-4 ring-amber-50/70 dark:bg-amber-900/40 dark:ring-amber-900/20",children:e.jsx(Bt,{className:"h-5 w-5 text-amber-600 dark:text-amber-400"})}),e.jsxs("div",{className:"min-w-0 space-y-1",children:[e.jsx("h2",{className:"text-base font-semibold tracking-tight text-amber-900 dark:text-amber-100 sm:text-lg",children:le?`Your ${_e?.membership_type_name} term has ended`:"Your membership has expired"}),e.jsx("p",{className:"text-sm leading-relaxed text-amber-800/85 dark:text-amber-200/80",children:le?`Your membership term has ended${ee?` on ${Be(pt(ee),"MMM d, yyyy")}`:""}.${m?.converts_to_type_name?` Upgrade to ${m.converts_to_type_name} to maintain your benefits.`:" Visit your subscription page for next steps."}`:`You're in a grace period${ee?` â your membership ended ${Be(pt(ee),"MMM d, yyyy")}`:""}. Renew now to keep your benefits and avoid losing access.`})]})]}),e.jsx(g,{asChild:!0,className:"shrink-0 bg-amber-600 px-6 font-medium text-white shadow-sm hover:bg-amber-700",children:e.jsxs(je,{to:s("/subscription"),children:[le?"Upgrade now":"Renew now",e.jsx(as,{className:"ml-2 h-4 w-4"})]})})]})]}),Pe&&e.jsxs("div",{className:"relative overflow-hidden rounded-xl border border-red-200 bg-gradient-to-br from-red-50 via-red-50/40 to-transparent p-5 dark:border-red-900/60 dark:from-red-950/40 dark:via-red-950/15 dark:to-transparent sm:p-6",children:[e.jsx("div",{"aria-hidden":!0,className:"pointer-events-none absolute -right-8 -top-8 h-40 w-40 rounded-full bg-red-400/10 blur-3xl dark:bg-red-500/10"}),e.jsxs("div",{className:"relative flex flex-col gap-4 sm:flex-row sm:items-center sm:gap-5",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-start gap-4",children:[e.jsx("div",{className:"shrink-0 rounded-xl bg-red-100 p-2.5 ring-4 ring-red-50/70 dark:bg-red-900/40 dark:ring-red-900/20",children:e.jsx(Ca,{className:"h-5 w-5 text-red-600 dark:text-red-400"})}),e.jsxs("div",{className:"min-w-0 space-y-1",children:[e.jsx("h2",{className:"text-base font-semibold tracking-tight text-red-900 dark:text-red-100 sm:text-lg",children:le?`Your ${_e?.membership_type_name} membership has ended`:"Your membership has lapsed"}),e.jsx("p",{className:"text-sm leading-relaxed text-red-800/85 dark:text-red-200/80",children:le?`Your membership term and grace period have ended.${m?.converts_to_type_name?` Upgrade to ${m.converts_to_type_name} to restore your benefits.`:" Contact your society for next steps."}`:"Your grace period has ended and your membership is no longer active. Renew today to restore your benefits, member pricing, and access."})]})]}),e.jsx(g,{asChild:!0,className:"shrink-0 bg-red-600 px-6 font-medium text-white shadow-sm hover:bg-red-700",children:e.jsxs(je,{to:s("/subscription"),children:[le?"Upgrade now":"Renew now",e.jsx(as,{className:"ml-2 h-4 w-4"})]})})]})]}),t&&e.jsx(Ad,{subjectId:t.id,variant:"portal",settingsPath:s("/profile"),checkCredentials:xe}),i?.is_faculty&&h?.event_app_base_url&&e.jsx(L3,{societyName:i?.society_name||""}),e.jsx(F3,{}),p&&e.jsxs("div",{"data-tour":"portal-stats",className:`grid grid-cols-2 gap-3 ${f&&f.donation_count>0&&R>0?"sm:grid-cols-6":f&&f.donation_count>0||R>0?"sm:grid-cols-5":"sm:grid-cols-4"}`,children:[e.jsx(L,{className:"min-w-0 transition-shadow hover:shadow-sm",children:e.jsxs($,{className:"flex flex-col items-center gap-1.5 overflow-hidden p-3 text-center sm:p-4",children:[e.jsx("div",{className:`flex h-9 w-9 shrink-0 items-center justify-center rounded-lg ${M>=5?"bg-amber-100 text-amber-600 dark:bg-amber-900/30 dark:text-amber-400":M>=1?"":"bg-emerald-100 text-emerald-600 dark:bg-emerald-900/30 dark:text-emerald-400"}`,style:M>=1&&M<5?{backgroundColor:"var(--portal-primary-light)",color:"var(--portal-primary)"}:void 0,children:M>
3950=5?e.jsx(qn,{className:"h-4 w-4"}):M>=1?e.jsx(No,{className:"h-4 w-4"}):e.jsx(Hb,{className:"h-4 w-4"})}),e.jsx("span",{className:"max-w-full truncate text-base font-semibold tracking-tight sm:text-lg",children:X}),e.jsx("span",{className:"text-[11px] font-medium leading-tight text-muted-foreground sm:text-[10px] sm:uppercase sm:tracking-wider",children:Se||"Tenure"}),h?.tenure_badge&&e.jsxs("span",{className:"mt-0.5 inline-flex items-center gap-1.5 whitespace-nowrap",children:[e.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-emerald-500"}),e.jsx("span",{className:"text-xs font-medium",children:h.tenure_badge})]})]})}),c?e.jsx(L,{className:"min-w-0 transition-shadow hover:shadow-sm",children:e.jsxs($,{className:"flex flex-col items-center gap-1.5 overflow-hidden p-3 text-center sm:p-4",children:[e.jsx("div",{className:`flex h-9 w-9 shrink-0 items-center justify-center rounded-lg ${se!==null&&se<=30?"bg-orange-100 text-orange-600 dark:bg-orange-900/30 dark:text-orange-400":""}`,style:se===null||se>30?{backgroundColor:"var(--portal-primary-light)",color:"var(--portal-primary)"}:void 0,children:e.jsx(ea,{className:"h-4 w-4"})}),e.jsx("span",{className:"text-base font-semibold tracking-tight sm:text-lg",children:se!==null?se>0?se:0:"â"}),e.jsx("span",{className:"text-[11px] font-medium leading-tight text-muted-foreground sm:text-[10px] sm:uppercase sm:tracking-wider",children:le?"Days Remaining":"Days to Renew"}),ee&&e.jsx("span",{className:"max-w-full truncate text-[10px] text-muted-foreground",children:Be(pt(ee),"MMM d, yyyy")})]})}):e.jsx(L,{className:"min-w-0 transition-shadow hover:shadow-sm",children:e.jsxs($,{className:"flex flex-col items-center gap-1.5 overflow-hidden p-3 text-center sm:p-4",children:[e.jsx("div",{className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-muted text-muted-foreground",children:e.jsx(St,{className:"h-4 w-4"})}),e.jsx("span",{className:"text-base font-semibold tracking-tight text-muted-foreground sm:text-lg",children:u?"Loadingâ¦":"Unavailable"}),e.jsx("span",{className:"text-[11px] font-medium leading-tight text-muted-foreground sm:text-[10px] sm:uppercase sm:tracking-wider",children:"Renewal details"})]})}),e.jsx(L,{className:"min-w-0 transition-shadow hover:shadow-sm",children:e.jsxs($,{className:"flex flex-col items-center gap-1.5 overflow-hidden p-3 text-center sm:p-4",children:[e.jsx("div",{className:`flex h-9 w-9 shrink-0 items-center justify-center rounded-lg ${h&&h.renewal_streak>1?"bg-orange-100 text-orange-600 dark:bg-orange-900/30 dark:text-orange-400":"bg-muted text-muted-foreground"}`,children:e.jsx(Jb,{className:"h-4 w-4"})}),e.jsx("span",{className:"text-base font-semibold tracking-tight sm:text-lg",children:h?.renewal_streak??0}),e.jsx("span",{className:"text-[10px] font-medium uppercase tracking-wider text-muted-foreground",children:"Year Streak"})]})}),c?le?e.jsx(L,{className:"min-w-0 transition-shadow hover:shadow-sm",children:e.jsxs($,{className:"flex flex-col items-center gap-1.5 overflow-hidden p-3 text-center sm:p-4",children:[e.jsx("div",{className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-lg",style:{backgroundColor:"var(--portal-primary-light)",color:"var(--portal-primary)"},children:e.jsx(No,{className:"h-4 w-4"})}),e.jsxs("span",{className:"text-base font-semibold tracking-tight sm:text-lg",children:[m?.term_length_years,"yr"]}),e.jsx("span",{className:"text-[11px] font-medium leading-tight text-muted-foreground sm:text-[10px] sm:uppercase sm:tracking-wider",children:"Fixed Term"})]})}):e.jsx(L,{className:"min-w-0 transition-shadow hover:shadow-sm",children:e.jsx($,{className:"flex flex-col items-center gap-1.5 overflow-hidden p-3 text-center sm:p-4",children:oe?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-emerald-100 text-emerald-600 dark:bg-emerald-900/30 dark:text-emerald-400",children:e.jsx(ad,{className:"h-4 w-4"})}),e.jsx("span",{className:"max-w-full truncate text-base font-semibold tracking-tight sm:text-lg",children:h?.lifetime_savings?Ji(h.lifetime_savings):"On"}),h?.lifetime_savings?e.jsxs(fs,{children:[e.jsx(ys,{asChild:!0,children:e.jsx("span",{className:"cursor-help border-b border-dotted border-muted-foreground
3950/50 text-[10px] font-medium uppercase leading-tight tracking-wider text-muted-foreground",children:"Total Saved"})}),e.jsx(hs,{children:"Estimated savings from auto-renewal discounts over your membership lifetime"})]}):e.jsx("span",{className:"text-[11px] font-medium leading-tight text-muted-foreground sm:text-[10px] sm:uppercase sm:tracking-wider",children:"Auto-Renew"})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-muted text-muted-foreground",children:e.jsx(Zb,{className:"h-4 w-4"})}),e.jsx("span",{className:"text-base font-semibold tracking-tight text-muted-foreground sm:text-lg",children:"Off"}),e.jsx("span",{className:"text-[10px] font-medium uppercase tracking-wider text-muted-foreground",children:"Auto-Renew"})]})})}):e.jsx(L,{className:"min-w-0 transition-shadow hover:shadow-sm",children:e.jsxs($,{className:"flex flex-col items-center gap-1.5 overflow-hidden p-3 text-center sm:p-4",children:[e.jsx("div",{className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-muted text-muted-foreground",children:e.jsx(St,{className:"h-4 w-4"})}),e.jsx("span",{className:"text-base font-semibold tracking-tight text-muted-foreground sm:text-lg",children:u?"Loadingâ¦":"Unavailable"}),e.jsx("span",{className:"text-[11px] font-medium leading-tight text-muted-foreground sm:text-[10px] sm:uppercase sm:tracking-wider",children:"Subscription details"})]})}),f&&f.donation_count>0&&e.jsx(L,{className:"min-w-0 transition-shadow hover:shadow-sm",children:e.jsxs($,{className:"flex flex-col items-center gap-1.5 overflow-hidden p-3 text-center sm:p-4",children:[e.jsx("div",{className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-pink-100 text-pink-600 dark:bg-pink-900/30 dark:text-pink-400",children:e.jsx(br,{className:"h-4 w-4"})}),e.jsx("span",{className:"max-w-full truncate text-base font-semibold tracking-tight sm:text-lg",children:Ji(f.total_donated)}),e.jsx("span",{className:"text-[11px] font-medium leading-tight text-muted-foreground sm:text-[10px] sm:uppercase sm:tracking-wider",children:"Your Donations"})]})}),R>0&&e.jsx(L,{className:"group min-w-0 cursor-pointer transition-all hover:shadow-md",onClick:()=>C(!0),children:e.jsxs($,{className:"flex flex-col items-center gap-1.5 overflow-hidden p-3 text-center sm:p-4",children:[e.jsx("div",{className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-lg transition-transform group-hover:scale-105",style:{backgroundColor:"var(--portal-primary-light)",color:"var(--portal-primary)"},children:e.jsx(ml,{className:"h-4 w-4"})}),e.jsx("span",{className:"text-base font-semibold tracking-tight sm:text-lg",children:R}),e.jsxs("span",{className:"text-[11px] font-medium leading-tight text-muted-foreground sm:text-[10px] sm:uppercase sm:tracking-wider",children:["Event",R!==1?"s":""," Attended"]})]})})]}),Q&&e.jsx("div",{"data-tour":"portal-upcoming-events",children:e.jsx(M3,{eventAppBaseUrl:h?.event_app_base_url??null})}),p&&h?.badges&&h.badges.length>0&&e.jsx("div",{className:"flex flex-wrap items-start justify-center gap-3 sm:justify-start sm:gap-4",children:h.badges.map(ce=>e.jsxs(fs,{children:[e.jsx(ys,{asChild:!0,children:e.jsxs("div",{className:"flex flex-col items-center gap-1",children:[ce.badge_type_icon_url?e.jsx("img",{src:`${ds}${ce.badge_type_icon_url}`,alt:ce.badge_type_name,className:"h-16 w-16 object-contain sm:h-28 sm:w-28"}):e.jsx("div",{className:"flex h-16 w-16 items-center justify-center rounded-full sm:h-28 sm:w-28",style:{backgroundColor:ce.badge_type_color},children:e.jsx(qn,{className:"h-8 w-8 text-white sm:h-14 sm:w-14"})}),e.jsx("span",{className:"max-w-[68px] text-center text-[10px] font-medium leading-tight text-muted-foreground sm:max-w-[112px] sm:text-xs",children:ce.badge_type_name})]})}),e.jsx(hs,{children:ce.note||ce.badge_type_name})]},ce.badge_type_id))}),!p&&e.jsxs("div",{className:"space-y-3",children:[R>0&&e.jsx("div",{className:"grid grid-cols-2 gap-3 sm:grid-cols-4",children:e.jsx(L,{className:"min-w-0 cursor-pointer transition-shadow hover:ring-2 hover:ring-indigo-300",onClick:()=>C(!0),children:e.jsxs($,{className:"flex flex-col items-center gap-1 overflow-hidden p-3 text-center sm:p-4",children:[e.jsx(ml,{className:"h-5 w-5 shrink-0 text-indigo-500"}),e.jsx("span",{className:"text-base font-semibold tracking-tight sm:text-lg",children:R}),e.jsxs("span",{className:"max-w-full truncate text-xs text-muted-foreground",children:["Event",R!==1?"s":""," Attended"]})]})})}),e.jsx(L,{className:"border-blue-200 bg-blue-50 dark:border-blue-800 dark:bg-blue-950/30",children:e.jsxs($,{className:"flex flex-col gap-4 p-6 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"text-lg font-semibold text-foreground",children:"Become a Member"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Unlock member pricing on events, auto-renewal discounts, and full society benefits."})]}),e.jsx(g,{asChild:!0,className:"shrink-0 bg-blue-600 text-white hover:bg-blue-700",children:e.jsxs(je,{to:s("/subscription"),target:"_blank",children:["Join Now",e.jsx(as,{className:"ml-2 h-4 w-4"})]})})]})})]}),p&&K&&e.jsxs("div",{className:"space-y-4","data-tour":"portal-news-polls",children:[e.jsxs("h2",{className:"flex min-w-0 items-center gap-2.5 text-lg font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg",style:{backgroundColor:"var(--portal-primary-light)",color:"var(--portal-primary)"},children:e.jsx(Vn,{className:"h-4 w-4"})}),"News & Polls"]}),e.jsxs("div",{className:"grid grid-cols-1 gap-4 md:grid-cols-2",children:[N&&N.map(ce=>{const ke=P.has(ce.id),ve=(ce.content?.length??0)>150;return e.jsx(L,{className:"min-w-0 transition-shadow hover:shadow-sm",children:e.jsx($,{className:"overflow-hidden p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-amber-100 text-amber-600 dar
3950k:bg-amber-900/30 dark:text-amber-400",children:e.jsx(Vn,{className:"h-4 w-4"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("h3",{className:"text-sm font-semibold tracking-tight",children:ce.title}),ce.content&&e.jsx("p",{className:`mt-1 text-xs leading-relaxed text-muted-foreground ${!ke&&ve?"line-clamp-3":""}`,children:W3(ce.content)}),ve&&e.jsx("button",{type:"button",className:"mt-1.5 text-xs font-medium text-blue-600 hover:text-blue-700",onClick:()=>A(Ne=>{const Qe=new Set(Ne);return Qe.has(ce.id)?Qe.delete(ce.id):Qe.add(ce.id),Qe}),children:ke?"Show less":"Read more"})]})]})})},ce.id)}),b&&b.map(ce=>e.jsx(L,{className:"min-w-0 transition-shadow hover:shadow-sm",children:e.jsx($,{className:"overflow-hidden p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-blue-100 text-blue-600 dark:bg-blue-900/30 dark:text-blue-400",children:e.jsx(Sa,{className:"h-4 w-4"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("h3",{className:"text-sm font-semibold tracking-tight",children:ce.title}),ce.description&&e.jsx("p",{className:"mt-1 line-clamp-2 text-xs leading-relaxed text-muted-foreground",children:ce.description}),e.jsx("div",{className:"mt-2.5",children:ce.already_responded?ce.show_results_to_members?e.jsxs(g,{size:"sm",variant:"outline",onClick:()=>_(ce.id),className:"h-8 text-xs",children:[e.jsx(Sa,{className:"mr-1 h-3 w-3"}),"View Results"]}):e.jsxs("span",{className:"inline-flex items-center gap-1.5 whitespace-nowrap",children:[e.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-emerald-500"}),e.jsx("span",{className:"text-xs font-medium",children:"Responded"})]}):e.jsx(g,{size:"sm",onClick:()=>k(ce.id),className:"h-8 bg-blue-600 text-xs font-medium text-white hover:bg-blue-700",children:"Vote now"})})]})]})})},ce.id))]})]}),v&&e.jsx($3,{open:!!v,onOpenChange:ce=>!ce&&k(null),pollId:v}),S&&e.jsx(z3,{open:!!S,onOpenChange:ce=>!ce&&_(null),pollId:S}),p&&h?.feature_modules?.video_library_enabled&&e.jsx(D3,{societyName:i?.society_name||""}),p&&U&&w&&w.length>0&&e.jsx(L,{className:"min-w-0 overflow-hidden transition-shadow hover:shadow-sm",children:e.jsxs($,{className:"flex items-center justify-between gap-3 p-4",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-3",children:[e.jsx("div",{className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-lg",style:{backgroundColor:"var(--portal-primary-light)",color:"var(--portal-primary)"},children:e.jsx(Gl,{className:"h-4 w-4"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("p",{className:"truncate text-sm font-semibold tracking-tight",children:[w.length," Open Position",w.length!==1?"s":""]}),e.jsx("p",{className:"hidden truncate text-xs text-muted-foreground sm:block",children:"Committee positions accepting applications"})]})]}),e.jsx(g,{variant:"outline",size:"sm",asChild:!0,className:"shrink-0 text-foreground",children:e.jsx(je,{to:s("/committees"),target:"_blank",children:"View"})})]})}),p&&U&&j&&j.length>0&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h2",{className:"flex min-w-0 items-center gap-2.5 text-lg font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg",style:{backgroundColor:"var(--portal-primary-light)",color:"var(--portal-primary)"},children:e.jsx(Kn,{className:"h-4 w-4"})}),"My Committees"]}),e.jsx("div",{className:"grid grid-cols-1 gap-4 md:grid-cols-2",children:j.map(ce=>e.jsx(L,{className:"min-w-0 transition-shadow hover:shadow-sm",children:e.jsx($,{className:"overflow-hidden p-4",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("h3",{className:"text-sm font-semibold tracking-tight",children:ce.name}),ce.description&&e.jsx("p",{className:"mt-1 line-clamp-2 text-xs leading-relaxed text-muted-foreground",children:ce.description})]}),e.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1.5 whitespace-nowrap",children:[e.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-muted-foreground
3950/60"}),e.jsx("span",{className:"text-xs font-medium",children:ce.role==="vice_chair"?"Vice chair":ce.role.charAt(0).toUpperCase()+ce.role.slice(1)})]})]})})},ce.id))})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-4 sm:gap-6 md:grid-cols-2",children:[p&&e.jsxs(L,{"data-tour":"portal-membership-details",className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg",style:{backgroundColor:"var(--portal-primary-light)",color:"var(--portal-primary)"},children:e.jsx(Qt,{className:"h-4 w-4"})}),"Membership Details"]})}),e.jsxs($,{className:"space-y-2.5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"shrink-0 text-sm text-muted-foreground",children:"Type"}),e.jsx("span",{className:"text-sm font-semibold",children:_e?.membership_type_name||"N/A"})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"shrink-0 text-sm text-muted-foreground",children:"Member Since"}),e.jsx("span",{className:"text-sm font-semibold",children:_e?.join_date?Be(pt(_e.join_date),"MMM d, yyyy"):"N/A"})]}),c?le?ee&&e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"shrink-0 text-sm text-muted-foreground",children:"Term Ends"}),e.jsx("span",{className:"text-sm font-semibold",children:Be(pt(ee),"MMM d, yyyy")})]}):e.jsxs(e.Fragment,{children:[h?.renewal_date&&e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"shrink-0 text-sm text-muted-foreground",children:"Next Renewal"}),e.jsx("span",{className:"text-sm font-semibold",children:Be(pt(h.renewal_date),"MMM d, yyyy")})]}),h?.renewal_amount!=null&&e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"shrink-0 text-sm text-muted-foreground",children:"Renewal Amount"}),e.jsx("span",{className:"text-sm font-semibold",children:Ji(h.renewal_amount)})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"shrink-0 text-sm text-muted-foreground",children:"Auto-Renew"}),e.jsx(ss,{checked:oe,onCheckedChange:ce=>x.mutate(ce),disabled:x.isPending})]})]}):e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"shrink-0 text-sm text-muted-foreground",children:"Subscription"}),e.jsx("span",{className:"text-sm font-semibold text-muted-foreground",children:u?"Loadingâ¦":"Unavailable"})]}),c&&e.jsx("div",{className:"mt-2 border-t pt-3",children:e.jsx(g,{variant:"outline",className:"w-full justify-center text-foreground",asChild:!0,children:e.jsxs(je,{to:s("/subscription"),children:[e.jsx(St,{className:"mr-2 h-4 w-4"}),"Manage subscription"]})})})]})]}),e.jsxs("div",{className:"min-w-0 space-y-6",children:[p&&h&&h.active_member_count>=10&&e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 items-center justify-center rounded-lg",style:{backgroundColor:"var(--portal-primary-light)",color:"var(--portal-primary)"},children:e.jsx(Lt,{className:"h-4 w-4"})}),"Community"]})}),e.jsx($,{className:"space-y-2.5",children:e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"shrink-0 text-sm text-muted-foreground",children:"Active Members"}),e.jsx("span",{className:"text-sm font-semibold",children:h.active_member_count.toLocaleString()})]})})]}),p&&D&&e.jsx(L,{"data-tour":"portal-directory",className:"min-w-0 overflow-hidden transition-shadow hover:shadow-sm",children:e.jsxs($,{className:"flex items-center justify-between gap-3 p-4",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-3",children:[e.jsx("div",{className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-lg",style:{backgroundColor:"var(--portal-primary-light)",color:"var(--portal-primary)"},children:e.jsx(Lt,{className:"h-4 w-4"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate text-sm font-semibold tracking-tight",children:"Member Directory"}),e.jsx("p",{className:"hidden truncate text-xs text-muted-foreground sm:block",children:"Find and connect with other members"})]})]}),e.jsx(g,{variant:"outline",size:"sm",asChild:!0,className:"shrink-0 text-foreground",children:e.jsx(je,{to:s("/directory"),children:"Browse"})})]})}),p&&Q&&e.jsx("div",{"data-tour":"portal-donations",children:e.jsx(E3,{})}),e.jsxs(L,{"data-tour":"portal-quick-actions",className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg",style:{backgroundColor:"var(--portal-primary-light)",color:"var(--portal-primary)"},children:e.jsx(Ar,{className:"h-4 w-4"})}),"Quick Actions"]})}),e.jsx($,{children:e.jsxs("div",{className:"grid grid-cols-1 gap-1",children:[e.jsx(g,{variant:"ghost",className:"h-auto justify-start gap-3 p-2 text-sm font-medium",asChild:!0,children:e.jsxs(je,{to:s("/profile"),children:[e.jsx("span",{className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-lg",style:{backgroundColor:"var(--portal-primary-light)",color:"var(--portal-primary)"},children:e.jsx(kn,{className:"h-4 w-4"})}),e.jsx("span",{className:"min-w-0 flex-1 truncate text-left",children:"Edit profile"})]})}),e.jsx(g,{variant:"ghost",className:"h-auto justify-start gap-3 p-2 text-sm font-medium",asChild:!0,children:e.jsxs(je,{to:s("/payments"),target:"_blank",children:[e.jsx("span",{className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-lg",style:{backgroundColor:"var(--portal-primary-light)",color:"var(--portal-primary)"},children:e.jsx(Qt,{className:"h-4 w-4"})}),e.jsx("span",{className:"min-w-0 flex-1 truncate text-left",children:"Payment history"})]})}),e.jsx(g,{variant:"ghost",className:"h-auto justify-start gap-3 p-2 text-sm font-medium",asChild:!0,children:e.jsxs(je,{to:s("/invoices"),target:"_blank",children:[e.jsx("span",{className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-lg",style:{backgroundColor:"var(--portal-primary-light)",color:"var(--portal-primary)"},children:e.jsx(Qt,{className:"h-4 w-4"})}),e.jsx("span",{className:"min-w-0 flex-1 truncate text-left",children:"Invoices & receipts"})]})}),e.jsx(g,{variant:"ghost",className:"h-auto justify-start gap-3 p-2 text-sm font-medium",asChild:!0,children:e.jsxs(je,{to:s("/subscription"),target:"_blank",children:[e.jsx("span",{className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-lg",style:{backgroundColor:"var(--portal-primary-light)",color:"var(--portal-primary)"},children:e.jsx(St,{className:"h-4 w-4"})}),e.jsx("span",{className:"min-w-0 flex-1 truncate text-left",children:p?"Manage subscription":"Join as member"})]})})]})})]})]})]}),e.jsx(Fe,{open:y,onOpenChange:C,children:e.jsxs(Te,{className:"sm:max-w-md",children:[e.jsx(Ae,{children:e.jsxs(Ee,{className:"flex items-center gap-2",children:[e.jsx(ml,{className:"h-5 w-5 text-indigo-500"}),"Events Attended"]})}),e.jsx("div",{className:"max-h-[60vh] space-y-3 overflow-y-auto",children:E&&E.length>0?E.map(ce=>e.jsxs("div",{className:"flex items-start justify-between gap-2 rounded-md border p-3",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:ce.event_name}),e.jsxs("div",{className:"mt-1 flex flex-wrap gap-x-3 gap-y-1 text-xs text-muted-foreground",children:[ce.event_start_date&&e.jsx("span",{children:Be(pt(ce.event_start_date),"MMM d, yyyy")}),ce.event_location&&e.jsx("span",{className:"truncate",children:ce.event_location})]})]}),ce.price_paid>0&&e.jsx("span",{className:"shrink-0 text-xs text-muted-foreground",children:Ji(ce.price_paid)})]},ce.id)):e.jsx("p",{className:"py-4 text-center text-sm text-muted-foreground",children:"No events found"})})]})})]}),e.jsx(Qg,{variant:"portal"}),e.jsx(Kg,{variant:"portal"})]})}function Od(t){return re({queryKey:["signup-society-info",t],queryFn:()=>gt.getSignupInfo(t),enabled:!!t,staleTime:300*1e3})}const ny=[{code:"AL",name:"Alabama"},{code:"AK",name:"Alaska"},{code:"AS",name:"American Samoa"},{code:"AZ",name:"Arizona"},{code:"AR",name:"Arkansas"},{code:"CA",name:"California"},{code:"CO",name:"Colorado"},{code:"CT",name:"Connecticut"},{code:"DE",name:"Delaware"},{code:"DC",name:"District of Columbia"},{code:"FL",name:"Florida"},{code:"GA",name:"Georgia"},{code:"GU",name:"Guam"},{code:"HI",name:"Hawaii"},{code:"ID",name:"Idaho"},{code:"IL",name:"Illinois"},{code:"IN",name:"Indiana"},{code:"IA",name:"Iowa"},{code:"KS",name:"Kansas"},{code:"KY",name:"Kentucky"},{code:"LA",name:"Louisiana"},{code:"ME",name:"Maine"},{code:"MD",name:"Maryland"},{code:"MA",name:"Massachusetts"},{code:"MI",name:"Michigan"},{code:"MN",name:"Minnesota"},{code:"MS",name:"Mississippi"},{code:"MO",name:"Missouri"},{code:"MT",name:"Montana"},{code:"NE",name:"Nebraska"},{code:"NV",name:"Nevada"},{code:"NH",name:"New Hampshire"},{code:"NJ",name:"New Jersey"},{code:"NM",name:"New Mexico"},{code:"NY",name:"New York"},{code:"NC",name:"North Carolina"},{code:"ND",name:"North Dakota"},{code:"MP",name:"Northern Mariana Islands"},{code:"OH",name:"Ohio"},{code:"OK",name:"Oklahoma"},{code:"OR",name:"Oregon"},{code:"PA",name:"Pennsylvania"},{code:"PR",name:"Puerto Rico"},{code:"RI",name:"Rhode Island"},{code:"SC",name:"South Carolina"},{code:"SD",name:"South Dakota"},{code:"TN",name:"Tennessee"},{code:"TX",name:"Texas"},{code:"UT",name:"Utah"},{code:"VT",name:"Vermont"},{code:"VI",name:"Virgin Islands"},{code:"VA",name:"Virginia"},{code:"WA",name:"Washington"},{code:"WV",name:"West Virginia"},{code:"WI",name:"Wisconsin"},{code:"WY",name:"Wyoming"}];function G3({open:t,onOpenChange:s}){const a=Bw(),[n,r]=o.useState(null),{stripePromise:i,elementsKey:l}=Ei(t,n?.publishableKey??null);return o.useEffect(()=>{t&&!n&&!a.isPending&&a.mutate(void 0,{onSuccess:m=>{r({clientSecret:m.client_secret,publishableKey:m.publishable_key})}})},[t]),o.useEffect(()=>{t||(r(null),a.reset())},[t]),e.jsx(Fe,{open:t,onOpenChange:s,children:e.jsxs(Te,{className:"max-h-[90vh] w-[95vw] overflow-y-auto sm:max-w-[480px]",children:[e.jsxs(Ae,{children:[e.jsx(Ee,{children:"Update payment method"}),e.jsx(tt,{children:"Enter your new card details below."})]}),a.isPending&&e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-b-2 border-foreground"})}),a.isError&&e.jsx("div",{className:"rounded-md border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-800 dark:border-red-900/60 dark:bg-red-950/30 dark:text-red-300",children:a.error?.response?.data?.detail||"Failed to initialize card update. Check that Stripe is configured."}),n&&i&&e.jsx(dn,{stripe:i,options:{clientSecret:n.clientSecret,appearance:{theme:"stripe",variables:{colorPrimary:"#0f172a"}}},children:e.jsx(Y3,{onSuccess:()=>s(!1)})},l)]})})}function Y3({onSuccess:t}){const s=mn(),a=un(),n=Kw(),[r,i]=o.useState(!1),[l,m]=o.useState(null),[c,d]=o.use
3950State(!1),u=async h=>{if(h.preventDefault(),!s||!a)return;i(!0),m(null);const p=await s.confirmSetup({elements:a,confirmParams:{return_url:window.location.href},redirect:"if_required"});if(p.error)m(p.error.message||"Card update failed"),i(!1);else if(p.setupIntent?.status==="succeeded"){try{await n.mutateAsync({setup_intent_id:p.setupIntent.id}),d(!0)}catch(x){m(x?.response?.data?.detail||"Card was saved but we could not set it as default. Please try again.")}i(!1)}};return c?e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsx("div",{className:"rounded-md border border-emerald-200 bg-emerald-50 px-4 py-3 text-center dark:border-emerald-900/60 dark:bg-emerald-950/30",children:e.jsx("p",{className:"text-sm font-semibold text-emerald-800 dark:text-emerald-300",children:"Payment method updated successfully"})}),e.jsx(g,{className:"w-full font-medium",onClick:t,children:"Done"})]}):e.jsxs("form",{onSubmit:u,className:"space-y-4",children:[e.jsx(hn,{}),l&&e.jsx("div",{className:"rounded-md border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-800 dark:border-red-900/60 dark:bg-red-950/30 dark:text-red-300",children:l}),e.jsx(g,{type:"submit",className:"w-full bg-blue-600 font-medium text-white hover:bg-blue-700",disabled:!s||r,children:r?"Savingâ¦":"Save card"})]})}const H3={visa:"Visa",mastercard:"Mastercard",amex:"American Express",discover:"Discover",diners:"Diners Club",jcb:"JCB",unionpay:"UnionPay"};function J3(){const{data:t,isLoading:s}=zw(),[a,n]=o.useState(!1);if(s)return e.jsxs(L,{children:[e.jsx(ne,{children:e.jsxs(ie,{className:"flex items-center gap-2.5",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg",style:{backgroundColor:"var(--portal-primary-light)",color:"var(--portal-primary)"},children:e.jsx(Qt,{className:"h-4 w-4"})}),"Payment method"]})}),e.jsxs($,{className:"space-y-3",children:[e.jsx(Y,{className:"h-5 w-48"}),e.jsx(Y,{className:"h-5 w-32"}),e.jsx(Y,{className:"h-9 w-28"})]})]});const r=t?.has_payment_method;return e.jsxs(e.Fragment,{children:[e.jsxs(L,{children:[e.jsx(ne,{children:e.jsxs(ie,{className:"flex items-center gap-2.5",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg",style:{backgroundColor:"var(--portal-primary-light)",color:"var(--portal-primary)"},children:e.jsx(Qt,{className:"h-4 w-4"})}),"Payment method"]})}),e.jsx($,{children:r?e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Qt,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{className:"text-sm font-medium",children:[H3[t.brand||""]||t.brand||"Card"," ending in ",t.last4]})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Expires ",String(t.exp_month).padStart(2,"0"),"/",t.exp_year]}),e.jsx(g,{variant:"outline",size:"sm",onClick:()=>n(!0),children:"Update Card"})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"No payment method on file"}),e.jsx(g,{variant:"outline",size:"sm",onClick:()=>n(!0),children:"Add Payment Method"})]})})]}),e.jsx(G3,{open:a,onOpenChange:n})]})}function ry({listCredentials:t,getRegisterOptions:s,verifyRegistration:a,renameCredential:n,deleteCredential:r,queryKey:i,portalMode:l=!1}){const m=io(),c=J(),[d,u]=o.useState(!1),[h,p]=o.useState(""),[x,f]=o.useState(!1),[b,N]=o.useState(null),[j,w]=o.useState(""),[v,k]=o.useState(!1),[S,_]=o.useState(""),[y,C]=o.useState(""),[P,A]=o.useState(null),{data:E=[],isLoading:Q}=re({queryKey:[i],queryFn:t}),U=W({mutationFn:({id:ee,name:se})=>n(ee,se),onSuccess:()=>{c.invalidateQueries({queryKey:[i]}),k(!1)}}),D=W({mutationFn:ee=>r(ee),onSuccess:()=>{c.invalidateQueries({queryKey:[i]}),A(null)}}),K=async()=>{p(""),u(!0);try{const ee=await s(),se=await Yy({optionsJSON:ee});N(se),w("My Passkey"),f(!0)}catch(ee){ee instanceof Error&&ee.name==="NotAllowedError"?p(""):p(ee instanceof Error?ee.message:"Registration failed")}finally{u(!1)}},xe=async()=>{if(b)try{await a(b,j||"My Passkey"),c.invalidateQueries({queryKey:[i]}),f(!1),N(null)}catch(ee){p(ee instanceof Error?ee.message:"Failed to save passkey"),f(!1)}};if(!m)return null;const z=l?"bg-blue-600 hover:bg-blue-700 text-white":"",ae=l?"border-slate-300 text-slate-700 hover:bg-slate-50":"",ue=l?"bg-red-600 hover:bg-red-700 text-white":"",_e=ee=>{if(!ee)return"Never used";const se=Ct(ee),oe=new Date().getTime()-se.getTime(),Pe=Math.floor(oe/6e4);if(Pe<1)return"Just now";if(Pe<60)return`${Pe} min ago`;const M=Math.floor(Pe/60);if(M<24)return`${M} hour${M>1?"s":""} ago`;const I=Math.floor(M/24);return I<30?`${I} day${I>
39501?"s":""} ago`:se.toLocaleDateString()};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:`text-lg font-semibold ${l?"text-slate-900":""}`,children:"Passkeys"}),e.jsx("p",{className:`text-sm ${l?"text-slate-500":"text-muted-foreground"}`,children:"Sign in with biometrics (Face ID, fingerprint, Windows Hello) instead of a password."})]}),Q?e.jsx("div",{className:`text-sm ${l?"text-slate-500":"text-muted-foreground"}`,children:"Loading passkeys..."}):E.length===0?e.jsx("div",{className:`text-sm ${l?"text-slate-500":"text-muted-foreground"}`,children:"No passkeys registered yet."}):e.jsx("div",{className:"space-y-2",children:E.map(ee=>e.jsxs("div",{className:`flex items-center justify-between rounded-lg border p-3 ${l?"border-slate-200 bg-white":"border-border bg-card"}`,children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:`truncate font-medium ${l?"text-slate-900":""}`,children:ee.name}),e.jsx("span",{className:`rounded px-1.5 py-0.5 text-xs ${l?"bg-slate-100 text-slate-600":"bg-muted text-muted-foreground"}`,children:ee.rp_id}),ee.credential_backed_up&&e.jsx("span",{className:`rounded px-1.5 py-0.5 text-xs ${l?"bg-blue-50 text-blue-600":"bg-blue-100 text-blue-700 dark:bg-blue-900 dark:text-blue-300"}`,children:"Synced"})]}),e.jsxs("div",{className:`mt-0.5 text-xs ${l?"text-slate-500":"text-muted-foreground"}`,children:["Last used: ",_e(ee.last_used_at)," · ","Added ",_e(ee.created_at)]})]}),e.jsxs("div",{className:"ml-2 flex shrink-0 gap-1",children:[e.jsx(g,{variant:"ghost",size:"sm",className:l?"text-slate-600 hover:bg-slate-100 hover:text-slate-900":"",onClick:()=>{_(ee.id),C(ee.name),k(!0)},children:"Rename"}),e.jsx(g,{variant:"ghost",size:"sm",className:l?"text-red-600 hover:bg-red-50 hover:text-red-700":"text-destructive hover:text-destructive",onClick:()=>A(ee.id),children:"Delete"})]})]},ee.id))}),h&&e.jsx("p",{className:"text-sm text-red-600",children:h}),e.jsx(g,{onClick:K,disabled:d,className:z,children:d?"Waiting for device...":"+ Register new passkey"}),e.jsx(Fe,{open:x,onOpenChange:f,children:e.jsxs(Te,{className:l?"bg-white":"",children:[e.jsx(Ae,{children:e.jsx(Ee,{className:l?"text-slate-900":"",children:"Name your passkey"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(O,{value:j,onChange:ee=>w(ee.target.value),placeholder:"e.g., iPhone 15, MacBook Pro",maxLength:100,className:l?"text-slate-900":""}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(g,{variant:"outline",onClick:()=>f(!1),className:ae,children:"Cancel"}),e.jsx(g,{onClick:xe,className:z,children:"Save"})]})]})]})}),e.jsx(Fe,{open:v,onOpenChange:k,children:e.jsxs(Te,{className:l?"bg-white":"",children:[e.jsx(Ae,{children:e.jsx(Ee,{className:l?"text-slate-900":"",children:"Rename passkey"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(O,{value:y,onChange:ee=>C(ee.target.value),maxLength:100,className:l?"text-slate-900":""}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(g,{variant:"outline",onClick:()=>k(!1),className:ae,children:"Cancel"}),e.jsx(g,{onClick:()=>U.mutate({id:S,name:y}),disabled:U.isPending||!y.trim(),className:z,children:U.isPending?"Saving...":"Save"})]})]})]})}),e.jsx(Fe,{open:!!P,onOpenChange:()=>A(null),children:e.jsxs(Te,{className:l?"bg-white":"",children:[e.jsx(Ae,{children:e.jsx(Ee,{className:l?"text-slate-900":"",children:"Delete passkey?"})}),e.jsx("p",{className:`text-sm ${l?"text-slate-600":"text-muted-foreground"}`,children:"This passkey will no longer work for sign-in. You can always register a new one."}),e.jsxs("div",{className:"mt-4 flex justify-end gap-2",children:[e.jsx(g,{variant:"outline",onClick:()=>A(null),className:ae,children:"Cancel"}),e.jsx(g,{variant:"destructive",onClick:()=>P&&D.mutate(P),disabled:D.isPending,className:ue,children:D.isPending?"Deleting...":"Delete"})]})]})})]})}const Z3={succeeded:"bg-emerald-500",pending:"bg-amber-500",failed:"bg-red-500",refunded:"bg-muted-foreground/60",partially_refunded:"bg-muted-foreground
3950/60"};function X3({status:t}){return e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx("span",{className:me("h-1.5 w-1.5 rounded-full",Z3[t]||"bg-muted-foreground"),"aria-hidden":"true"}),e.jsx("span",{className:"text-xs font-medium capitalize text-foreground/85",children:t.replace("_"," ")})]})}const eP={initial:"Membership",renewal:"Renewal",auto_renewal:"Auto-renewal",upgrade:"Upgrade",manual:"Manual payment",donation:"Donation",product:"Purchase",event:"Event",other:"Other"};function tP(t){return Number(t).toLocaleString("en-US",{style:"currency",currency:"USD"})}function sP(){const{data:t,isLoading:s}=ar(),{data:a}=$w(),n=pg(),r=qw(),i=Iw(),{hasPassword:l,markPasswordSet:m,societySlug:c}=ft(),d=us(),{data:u,isLoading:h}=fg(1,5),{data:p}=Nc(1,3),{data:x}=bg(),f=x?.custom_field_labels||{},{data:b}=Od(c),N=b?.non_member_role_options??[],[j,w]=o.useState(!1),[v,k]=o.useState({}),[S,_]=o.useState({}),[y,C]=o.useState(""),[P,A]=o.useState(""),E=eN(),[Q,U]=o.useState(!1),[D,K]=o.useState(""),[xe,z]=o.useState(""),[ae,ue]=o.useState(""),[_e,ee]=o.useState(""),[se,le]=o.useState(""),[oe,Pe]=o.useState(""),[M,I]=o.use
3950State(""),[R,X]=o.useState(""),Se=nN(),ce=rN(),ke=o.useRef(null),[ve,Ne]=o.useState("");if(s)return e.jsxs("div",{className:"space-y-6",children:[e.jsx(Fu,{}),e.jsx(Y,{className:"h-64"}),e.jsx(Y,{className:"h-48"})]});if(!t)return null;const Qe=()=>{k({first_name:t.first_name,last_name:t.last_name,organization:t.organization,secondary_email:t.secondary_email,phone:t.phone,address_line1:t.address_line1,address_line2:t.address_line2,city:t.city,state:t.state,county:t.county,postal_code:t.postal_code,country:t.country,show_in_directory:t.show_in_directory,...t.is_non_member&&t.declared_role_type_id!=null?{declared_role_type_id:t.declared_role_type_id}:{}}),_({}),w(!0),C(""),A("")},Oe=async ye=>{ye.preventDefault(),A(""),C("");try{const Ke={...v};Object.keys(S).length>0&&(Ke.custom_fields=S),await n.mutateAsync(Ke),w(!1),C("Profile updated successfully")}catch{A("Failed to update profile")}},Ce=async ye=>{if(ye.preventDefault(),X(""),I(""),se!==oe){X("Passwords do not match");return}if(se.length<8){X("Password must be at least 8 characters");return}if(!l){try{await i.mutateAsync(se),m(),I("Password set successfully"),le(""),Pe("")}catch{X("Failed to set password")}return}try{await r.mutateAsync({current_password:_e,new_password:se}),I("Password changed successfully"),ee(""),le(""),Pe("")}catch(Ke){const ut=Ke?.response?.status;X(ut===400||ut===401?"Current password is incorrect":"Failed to change password")}},ze=(ye,Ke)=>{k(ut=>({...ut,[ye]:Ke}))},Ze=async ye=>{const Ke=ye.target.files?.[0];if(Ke){if(Ne(""),Ke.size>10*1024*1024){Ne("Image must be under 10 MB.");return}try{await Se.mutateAsync(Ke)}catch{Ne("Failed to upload photo.")}ke.current&&(ke.current.value="")}},Re=async()=>{Ne("");try{await ce.mutateAsync()}catch{Ne("Failed to remove photo.")}},de=Se.isPending||ce.isPending,ge=t.custom_fields||{},mt=Object.entries(ge);return e.jsxs("div",{className:"space-y-6",children:[e.jsx(Fu,{}),e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsxs(ne,{className:"flex flex-row items-center justify-between pb-3",children:[e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg",style:{backgroundColor:"var(--portal-primary-light)",color:"var(--portal-primary)"},children:e.jsx(kn,{className:"h-4 w-4"})}),"Personal information"]}),!j&&e.jsx(g,{variant:"outline",size:"sm",onClick:Qe,children:"Edit"})]}),e.jsxs($,{children:[e.jsxs("div",{className:"mb-6 flex items-center gap-4 border-b border-border pb-6",children:[e.jsxs("div",{className:"relative",children:[t.headshot_url?e.jsx("img",{src:`${ds}${t.headshot_url}`,alt:"",className:"h-16 w-16 rounded-full object-cover ring-1 ring-border"}):e.jsx("div",{className:"flex h-16 w-16 items-center justify-center rounded-full ring-1 ring-border",style:{backgroundColor:"var(--portal-primary-light)",color:"var(--portal-primary)"},children:e.jsxs("span",{className:"text-lg font-semibold tracking-tight",children:[t.first_name[0],t.last_name[0]]})}),de&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center rounded-full bg-black/40",children:e.jsx(He,{className:"h-5 w-5 animate-spin text-white"})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(g,{type:"button",variant:"outline",size:"sm",className:"text-xs font-medium",disabled:de,onClick:()=>ke.current?.click(),children:[e.jsx(Xb,{className:"mr-1 h-3.5 w-3.5"}),t.headshot_url?"Change photo":"Upload photo"]}),t.headshot_url&&e.jsxs(g,{type:"button",variant:"outline",size:"sm",className:"text-xs font-medium text-red-600 hover:bg-red-50 hover:text-red-700 dark:text-red-400 dark:hover:bg-red-950/30",disabled:de,onClick:Re,children:[e.jsx(Ft,{className:"mr-1 h-3.5 w-3.5"}),"Remove"]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"PNG, JPEG, or WebP. Max 5 MB."}),ve&&e.jsx("p",{className:"text-xs font-medium text-red-600 dark:text-red-400",children:ve})]}),e.jsx("input",{ref:ke,type:"file",accept:"image/png,image/jpeg,image/webp",className:"hidden",onChange:Ze})]}),y&&e.jsx("div",{className:"mb-4 rounded-md border border-emerald-200 bg-emerald-50 p-3 text-sm text-emerald-800 dark:border-emerald-900/60 dark:bg-emerald-950/30 dark:text-emerald-300",children:y}),P&&e.jsx("div",{className:"mb-4 rounded-md bg-destructive/10 p-3 text-sm text-destructive",children:P}),j?e.jsxs("form",{onSubmit:Oe,className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"first_name",children:"First name"}),e.jsx(O,{id:"first_name",autoComplete:"given-name",value:v.first_name||"",onChange:ye=>ze("first_name",ye.target.value),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"last_name",children:"Last name"}),e.jsx(O,{id:"last_name",autoComplete:"family-name",value:v.last_name||"",onChange:ye=>ze("last_name",ye.target.value),required:!0})]})]}),t.is_non_member&&N.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"declared-role",children:"Professional role"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Your role determines event pricing and membership offer eligibility."}),e.jsxs(qe,{value:v.declared_role_type_id??"",onValueChange:ye=>{ye&&ze("declared_role_type_id",ye)},children:[e.jsx(Le,{id:"declared-role",className:"w-full",children:e.jsx(Ie,{placeholder:"Select your role"})}),e.jsx($e,{children:N.map(ye=>e.jsx(q,{value:ye.id,className:"min-h-[44px]",children:ye.name},ye.id))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"phone",children:"Phone"}),e.jsx(O,{id:"phone",type:"tel",autoComplete:"tel",value:v.phone||"",onChange:ye=>ze("phone",ye.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"organization",children:"Organization"}),e.jsx(O,{id:"organization",autoComplete:"organization",value:v.organization||"",onChange:ye=>ze("organization",ye.target.value),placeholder:"Practice, institution, or employer"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"secondary_email",children:"Secondary email"}),e.jsx(O,{id:"secondary_email",type:"email",value:v.secondary_email||"",onChange:ye=>ze("secondary_email",ye.target.value),placeholder:"Alternate email address"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"address_line1",children:"Address line 1"}),e.jsx(O,{id:"address_line1",autoComplete:"address-line1",value:v.address_line1||"",onChange:ye=>ze("address_line1",ye.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"address_line2",children:"Address line 2"}),e.jsx(O,{id:"address_line2",autoComplete:"address-line2",value:v.address_line2||"",onChange:ye=>ze("address_line2",ye.target.value)})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"city",children:"City"}),e.jsx(O,{id:"city",autoComplete:"address-level2",value:v.city||"",onChange:ye=>ze("city",ye.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"state",children:"State"}),e.jsxs(qe,{value:v.state||"",onValueChange:ye=>ze("state",ye),children:[e.jsx(Le,{id:"state",children:e.jsx(Ie,{placeholder:"Select state"})}),e.jsx($e,{children:ny.map(ye=>e.jsx(q,{value:ye.code,children:ye.name},ye.code))})]})]})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"county",children:"County"}),e.jsx(O,{id:"county",value:v.county||"",onChange:ye=>ze("county",ye.target.value),placeholder:"Auto-fills from ZIP"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"postal_code",children:"Postal code"}),e.jsx(O,{id:"postal_code",autoComplete:"postal-code",value:v.postal_code||"",onChange:ye=>ze("postal_code",ye.target.value)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"country",children:"Country"}),e.jsx(O,{id:"country",autoComplete:"country-name",value:v.country||"",onChange:ye=>ze("country",ye.target.value)})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ss,{id:"show_in_directory",checked:v.show_in_directory??!1,onCheckedChange:ye=>ze("show_in_directory",ye)}
3950),e.jsx(T,{htmlFor:"show_in_directory",children:"Show in member directory"})]}),a&&a.length>0&&e.jsxs("div",{className:"space-y-3 border-t pt-4",children:[e.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-wider text-muted-foreground",children:"Additional fields"}),a.map(ye=>{const Ke=ye.key in S?S[ye.key]:ge[ye.key],ut=De=>_(he=>({...he,[ye.key]:De}));return e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:`cf-${ye.key}`,children:ye.label}),ye.field_type==="multi_select"?e.jsx("div",{className:"space-y-2",children:ye.options.map(De=>{const he=Array.isArray(Ke)?Ke:[];return e.jsxs("label",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(ot,{checked:he.includes(De),onCheckedChange:Xe=>ut(Xe?[...he,De]:he.filter(rt=>rt!==De))}),De]},De)})}):e.jsx(O,{id:`cf-${ye.key}`,value:String(Ke??""),onChange:De=>ut(De.target.value)})]},ye.key)})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(g,{type:"submit",className:"bg-blue-600 font-medium text-white hover:bg-blue-700",disabled:n.isPending,children:n.isPending?"Savingâ¦":"Save changes"}),e.jsx(g,{type:"button",variant:"outline",onClick:()=>w(!1),children:"Cancel"})]})]}):e.jsxs("dl",{className:"space-y-3",children:[e.jsx(yn,{label:"Name",value:`${t.first_name} ${t.last_name}`}),t.is_non_member&&e.jsx(yn,{label:"Professional role",value:t.declared_role_type_name}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("dt",{className:"text-sm text-muted-foreground",children:"Email"}),e.jsxs("dd",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium",children:t.email}),e.jsx(g,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>{U(!Q),z(""),ue(""),K("")},children:"Change"})]})]}),Q&&e.jsxs("div",{className:"space-y-3 rounded-md border bg-muted/30 p-3",children:[xe&&e.jsx("div",{className:"rounded-md border border-emerald-200 bg-emerald-50 p-2 text-sm text-emerald-800 dark:border-emerald-900/60 dark:bg-emerald-950/30 dark:text-emerald-300",children:xe}),ae&&e.jsx("div",{className:"rounded-md bg-destructive/10 p-2 text-sm text-destructive",children:ae}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(O,{type:"email",placeholder:"New email address",value:D,onChange:ye=>K(ye.target.value),className:"flex-1"}),e.jsx(g,{size:"sm",className:"bg-blue-600 font-medium text-white hover:bg-blue-700",disabled:!D||E.isPending,onClick:async()=>{ue(""),z("");try{const ye=await E.mutateAsync(D);z(ye.message),K("")}catch(ye){ue(ye?.response?.data?.detail||"Failed to send verification email")}},children:E.isPending?"Sendingâ¦":"Send verification"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"A verification email will be sent to the new address."})]}),e.jsx(yn,{label:"Secondary Email",value:t.secondary_email}),e.jsx(yn,{label:"Organization",value:t.organization}),e.jsx(yn,{label:"Phone",value:t.phone}),e.jsx(yn,{label:"Address",value:[t.address_line1,t.address_line2,t.city,t.state,t.county,t.postal_code,t.country].filter(Boolean).join(", ")}),e.jsx(yn,{label:"Show in Directory",value:t.show_in_directory?"Yes":"No"}),mt.map(([ye,Ke])=>e.jsx(yn,{label:f[ye]||uo(ye),value:Array.isArray(Ke)?Ke.join(", "):String(Ke??"")},ye))]})]})]}),e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg",style:{backgroundColor:"var(--portal-primary-light)",color:"var(--portal-primary)"},children:e.jsx(An,{className:"h-4 w-4"})}),l?"Change password":"Set password"]})}),e.jsxs($,{children:[M&&e.jsx("div",{className:"mb-4 rounded-md border border-emerald-200 bg-emerald-50 p-3 text-sm text-emerald-800 dark:border-emerald-900/60 dark:bg-emerald-950/30 dark:text-emerald-300",children:M}),R&&e.jsx("div",{className:"mb-4 rounded-md bg-destructive/10 p-3 text-sm text-destructive",children:R}),!l&&e.jsx("p",{className:"mb-3 text-sm text-muted-foreground",children:"You don't have a password set yet. Set one below to log in with your email and password."}),e.jsxs("form",{onSubmit:Ce,className:"space-y-4",children:[l&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"current_password",children:"Current password"}),e.jsx(O,{id:"current_password",type:"password",value:_e,onChange:ye=>ee(ye.target.value),required:!0,autoComplete:"current-password"}),e.jsx(je,{to:d("/forgot-password"),className:"inline-block text-xs font-medium text-blue-600 hover:text-blue-700 hover:underline dark:text-blue-400 dark:hover:text-blue-300",children:"Forgot your password?"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"new_password",children:l?"New password":"Password"}),e.jsx(O,{id:"new_password",type:"password",value:se,onChange:ye=>le(ye.target.value),required:!0,minLength:8,autoComplete:"new-password"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"confirm_password",children:l?"Confirm new password":"Confirm password"}),e.jsx(O,{id:"confirm_password",type:"password",value:oe,onChange:ye=>Pe(ye.target.value),required:!0,minLength:8,autoComplete:"new-password"})]}),e.jsx(g,{type:"submit",className:"bg-blue-600 font-medium text-white hover:bg-blue-700",disabled:r.isPending||i.isPending,children:r.isPending||i.isPending?"Savingâ¦":l?"Change password":"Set password"})]})]})]}),e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg",style:{backgroundColor:"var(--portal-primary-light)",color:"var(--portal-primary)"},children:e.jsx(Hc,{className:"h-4 w-4"})}),"Passkeys"]})}),e.jsx($,{children:e.jsx(ry,{listCredentials:jn.listCredentials,getRegisterOptions:jn.getRegisterOptions,verifyRegistration:jn.verifyRegistration,renameCredential:jn.renameCredential,deleteCredential:jn.deleteCredential,queryKey:"portal-passkeys",portalMode:!0})})]}),e.jsx(J3,{}),e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsxs(ne,{className:"flex flex-row items-center justify-between pb-3",children:[e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg",style:{backgroundColor:"var(--portal-primary-light)",color:"var(--portal-primary)"},children:e.jsx(Qt,{className:"h-4 w-4"})}),"Recent payments"]}),e.jsx(g,{variant:"ghost",size:"sm",asChild:!0,className:"text-muted-foreground hover:text-foreground",children:e.jsxs(je,{to:d("/payments"),className:"text-sm",children:["View all",e.jsx(as,{className:"ml-1 h-3.5 w-3.5"})]})})]}),e.jsx($,{children:h?e.jsx("div",{className:"space-y-2",children:Array.from({length:3}).map((ye,Ke)=>e.jsx(Y,{className:"h-10 w-full"},Ke))}):!u||u.length===0?e.jsx("p",{className:"py-4 text-center text-sm text-muted-foreground",children:"No payments yet."}):e.jsx("div",{className:"space-y-3",children:u.map(ye=>e.jsxs("div",{className:"flex items-center justify-between gap-3 border-b py-2 last:border-0",children:[e.jsxs("div",{className:"min-w-0 space-y-0.5",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:ye.description||eP[ye.payment_type]||ye.payment_type}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Be(pt(ye.created_at),"MMM d, yyyy")})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-3",children:[e.jsx("span",{className:"text-sm font-semibold",children:tP(ye.net_amount)}),e.jsx(X3,{status:ye.status})]})]},ye.id))})})]}),p&&p.items.length>0&&e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsxs(ne,{className:"flex flex-row items-center justify-between pb-3",children:[e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg",style:{backgroundColor:"var(--portal-primary-light)",color:"var(--portal-primary)"},children:e.jsx(cs,{className:"h-4 w-4"})}),"Recent invoices"]}),e.jsx(g,{variant:"ghost",size:"sm",asChild:!0,className:"text-muted-foreground hover:text-foreground",children:e.jsxs(je,{to:d("/invoices"),className:"text-sm",children:["View all",e.jsx(as,{className:"ml-1 h-3.5 w-3.5"})]})})]}),e.jsx($,{children:e.jsx("div",{className:"space-y-3",children:p.items.map(ye=>{const Ke=ye.status==="paid";return e.jsxs("div",{className:"flex items-center justify-between gap-3 border-b py-2 last:border-0",children:[e.jsxs("div",{className:"min-w-0 space-y-0.5",children:[e.jsx("p",{className:"truncate font-mono text-sm font-semibold",children:ye.invoice_number}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Ke?"Paid":"Due"," ",Be(pt(ye.due_date),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-3",children:[e.jsxs("span",{className:"text-sm font-semibold",children:["$",Number(ye.amount).toFixed(2)]}),e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx("span",{className:me("h-1.5 w-1.5 rounded-full",Ke?"bg-emerald-500":"bg-amber-500"),"aria-hidden":"true"}),e.jsx("span",{className:"text-xs font-medium capitalize text-foreground
3950/85",children:ye.status})]})]})]},ye.id)})})})]})]})}function Fu(){return e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg",style:{backgroundColor:"var(--portal-primary-light)",color:"var(--portal-primary)"},children:e.jsx(kn,{className:"h-5 w-5"})}),e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:"Profile"})]})}function yn({label:t,value:s}){return e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("dt",{className:"shrink-0 text-sm text-muted-foreground",children:t}),e.jsx("dd",{className:"text-right text-sm font-semibold",children:s||"â"})]})}const Ru=20,aP={succeeded:"bg-emerald-500",pending:"bg-amber-500",failed:"bg-red-500",refunded:"bg-muted-foreground/60",partially_refunded:"bg-muted-foreground/60"};function Mu({status:t}){return e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx("span",{className:me("h-1.5 w-1.5 rounded-full",aP[t]||"bg-muted-foreground"),"aria-hidden":"true"}),e.jsx("span",{className:"text-xs font-medium capitalize text-foreground/85",children:t.replace("_"," ")})]})}const Zi={initial:"Membership",renewal:"Renewal",auto_renewal:"Auto-renewal",upgrade:"Upgrade",manual:"Manual payment",donation:"Donation",product:"Purchase",event:"Event",other:"Other"};function Du(t){return Number(t).toLocaleString("en-US",{style:"currency",currency:"USD"})}function nP(){const[t,s]=o.useState(1),{data:a,isLoading:n}=fg(t,Ru),r=a?a.length>=Ru:!1,i=async l=>{if(!(!l.invoice_id||!l.invoice_number))try{const m=await Me.get(`/portal/invoices/${l.invoice_id}/pdf`,{responseType:"blob"}),c=window.URL.createObjectURL(m.data),d=document.createElement("a");d.href=c,d.download=`${l.invoice_number}.pdf`,d.click(),window.URL.revokeObjectURL(c)}catch{}};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg",style:{backgroundColor:"var(--portal-primary-light)",color:"var(--portal-primary)"},children:e.jsx(Qt,{className:"h-5 w-5"})}),e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:"Payment history"})]}),e.jsx(L,{className:"min-w-0 overflow-hidden",children:e.jsx($,{className:"p-0",children:n?e.jsx("div",{className:"space-y-2 p-4",children:Array.from({length:5}).map((l,m)=>e.jsx(Y,{className:"h-10 w-full"},m))}):!a||a.length===0?e.jsxs("div",{className:"space-y-3 py-12 text-center",children:[e.jsx(Qt,{className:"mx-auto h-10 w-10 text-muted-foreground/60"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No payments found."})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"divide-y md:hidden",children:a.map(l=>{const m=pt(l.created_at),c=!!l.invoice_id;return e.jsxs("div",{className:me("space-y-2 p-4 transition-colors",c&&"cursor-pointer hover:bg-brand-navy/[0.04] active:bg-brand-navy/[0.06] dark:hover:bg-brand-navy/10"),onClick:c?()=>i(l):void 0,children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:Be(m,"MMM d, yyyy")}),e.jsx(Mu,{status:l.status})]}),e.jsx("p",{className:"text-sm font-medium",children:l.description||Zi[l.payment_type]||l.payment_type.replace("_"," ")}),e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-sm font-semibold",children:Du(l.net_amount)}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:Zi[l.payment_type]||l.payment_type.replace("_"," ")}),c&&e.jsx(vs,{className:"h-3.5 w-3.5 text-blue-600"})]})]})]},l.id)})}),e.jsx("div",{className:"hidden md:block",children:e.jsxs(Pt,{children:[e.jsx(At,{className:"bg-muted/30",children:e.jsxs(Ue,{className:"hover:bg-transparent",children:[e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Date"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground
3950/80",children:"Description"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Amount"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Type"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Status"}),e.jsx(H,{className:"h-10 w-10"})]})}),e.jsx(Et,{children:a.map((l,m)=>{const c=pt(l.created_at),d=c.getFullYear(),u=m>0?pt(a[m-1].created_at).getFullYear():null,h=u!==null&&d!==u,p=!!l.invoice_id;return e.jsxs(o.Fragment,{children:[h&&e.jsx(Ue,{className:"hover:bg-transparent",children:e.jsx(G,{colSpan:6,className:"bg-muted/40 py-2 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground",children:d})}),e.jsxs(Ue,{className:me(p&&"cursor-pointer hover:bg-brand-navy/[0.04] dark:hover:bg-brand-navy/10"),onClick:p?()=>i(l):void 0,children:[e.jsx(G,{className:"text-sm text-muted-foreground",children:Be(c,"MMM d, yyyy")}),e.jsx(G,{className:"text-sm",children:l.description||Zi[l.payment_type]||l.payment_type.replace("_"," ")}),e.jsx(G,{className:"text-sm font-semibold",children:Du(l.net_amount)}),e.jsx(G,{className:"text-sm text-muted-foreground",children:Zi[l.payment_type]||l.payment_type.replace("_"," ")}),e.jsx(G,{children:e.jsx(Mu,{status:l.status})}),e.jsx(G,{children:p&&e.jsx(vs,{className:"h-4 w-4 text-blue-600"})})]})]},l.id)})})]})})]})})}),a&&a.length>0&&e.jsxs("div",{className:"flex items-center justify-between pt-2",children:[e.jsx(g,{variant:"outline",size:"default",className:"min-h-[44px]",disabled:t<=1,onClick:()=>s(l=>l-1),children:"Previous"}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:["Page ",t]}),e.jsx(g,{variant:"outline",size:"default",className:"min-h-[44px]",disabled:!r,onClick:()=>s(l=>l+1),children:"Next"})]})]})}const rP={visa:"Visa",mastercard:"Mastercard",amex:"American Express",discover:"Discover"};function iP({open:t,onOpenChange:s,intentData:a}){const{stripePromise:n,elementsKey:r}=Ei(t,a?.publishable_key??null),[i,l]=o.useState(!0),[m,c]=o.useState(!1),[d,u]=o.useState(null),[h,p]=o.useState(!1),x=Jw(),f=!!a?.saved_payment_method;o.useEffect(()=>{t&&a&&(l(!!a.saved_payment_method),u(null),p(!1))},[t,a]);const b=async()=>{if(a){c(!0),u(null);try{await x.mutateAsync(a.payment_intent_id),p(!0)}catch(N){const j=N?.response;u(j?.data?.detail||"Payment failed. Please try again or use a different card.")}c(!1)}};return h?e.jsx(Fe,{open:t,onOpenChange:s,children:e.jsxs(Te,{className:"max-h-[90vh] w-[95vw] overflow-y-auto sm:max-w-[480px]",children:[e.jsx(Ae,{children:e.jsx(Ee,{children:"Renew membership"})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsx("div",{className:"rounded-md border border-emerald-200 bg-emerald-50 px-4 py-3 text-center dark:border-emerald-900/60 dark:bg-emerald-950/30",children:e.jsx("p",{className:"text-sm font-semibold text-emerald-800 dark:text-emerald-300",children:"Membership renewed successfully"})}),e.jsx(g,{className:"w-full font-medium",onClick:()=>s(!1),children:"Done"})]})]})}):e.jsx(Fe,{open:t,onOpenChange:s,children:e.jsxs(Te,{className:"max-h-[90vh] w-[95vw] overflow-y-auto sm:max-w-[480px]",children:[e.jsxs(Ae,{children:[e.jsx(Ee,{children:"Renew Membership"}),e.jsx(tt,{children:a&&e.jsxs(e.Fragment,{children:[a.membership_type_name," â $",a.amount.toFixed(2),a.period_end&&e.jsxs(e.Fragment,{children:[" (through ",Ps(a.period_end).toLocaleDateString(),")"]}),a.auto_renew_opt_in!=null&&e.jsx("span",{className:"mt-1 block text-xs font-medium",children:a.auto_renew_opt_in?"Auto-renews each cycle":"One-time renewal"})]})})]}),a&&f&&i?e.jsx(lP,{savedCard:a.saved_payment_method,onUseSavedCard:b,onUseNewCard:()=>l(!1),isProcessing:m,error:d}):a&&n?e.jsxs("div",{children:[e.jsx(dn,{stripe:n,options:{clientSecret:a.client_secret,appearance:{theme:"stripe",variables:{colorPrimary:"#0f172a"}}},children:e.jsx(oP,{onSuccess:()=>p(!0)})},r),f&&e.jsxs("button",{type:"button",onClick:()=>l(!0),className:"mt-2 w-full py-2 text-sm text-muted-foreground hover:text-foreground",children:["â Use saved card (",a.saved_payment_method.brand," ","â¢â¢â¢â¢ ",a.saved_payment_method.last4,")"]})]}):null]})})}function lP({savedCard:t,onUseSavedCard:s,onUseNewCard:a,isProcessing:n,error:r}){return e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"rounded-lg border bg-muted/30 p-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex h-10 w-14 shrink-0 items-center justify-center rounded border bg-background",children:e.jsx(Qt,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("p",{className:"truncate font-semibold tracking-tight text-foreground",children:[rP[t.brand.toLowerCase()]||t.brand," â¢â¢â¢â¢"," ",t.last4]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Expires ",t.exp_month.toString().padStart(2,"0"),"/",t.exp_year]})]}),e.jsx(Xt,{className:"h-5 w-5 shrink-0 text-emerald-600 dark:text-emerald-400"})]})}),r&&e.jsxs("div",{className:"flex items-center gap-2 text-sm text-red-600 dark:text-red-400",children:[e.jsx(Dt,{className:"h-4 w-4 shrink-0"}),r]}),e.jsx(g,{onClick:s,disabled:n,className:"w-full bg-blue-600 font-medium text-white hover:bg-blue-700",size:"lg",children:n?e.jsxs(e.Fragment,{children:[e.jsx(He,{className:"mr-2 h-4 w-4 animate-spin"}),"Processingâ¦"]}):e.jsxs(e.Fragment,{children:[e.jsx(Ys,{className:"mr-2 h-4 w-4"}),"Pay with saved card"]})}),e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute inset-0 flex items-center",children:e.jsx("span",{className:"w-full border-t"})}),e.jsx("div",{className:"relative flex justify-center text-[10px] font-semibold uppercase tracking-wider",children:e.jsx("span",{className:"bg-card px-2 text-muted-foreground",children:"or"})})]}),e.jsx("button",{type:"button",onClick:a,className:"w-full py-2 text-sm text-muted-foreground transition-colors hover:text-foreground",children:"Use a different payment method"})]})}function oP({onSuccess:t}){const s=mn(),a=un(),n=Hw(),[r,i]=o.useState(!1),[l,m]=o.useState(!1),[c,d]=o.use
3950State(null),u=async h=>{if(h.preventDefault(),!s||!a||!l)return;i(!0),d(null);const p=await s.confirmPayment({elements:a,confirmParams:{return_url:window.location.href},redirect:"if_required"});if(p.error)d(p.error.message||"Payment failed"),i(!1);else if(p.paymentIntent?.status==="succeeded"){try{await n.mutateAsync(p.paymentIntent.id),t()}catch(x){const f=x?.response;d(f?.data?.detail||"Payment succeeded but renewal confirmation failed. Please contact support.")}i(!1)}};return e.jsxs("form",{onSubmit:u,className:"space-y-4",children:[e.jsx(hn,{onReady:()=>m(!0)}),c&&e.jsx("div",{className:"rounded-md border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-800 dark:border-red-900/60 dark:bg-red-950/30 dark:text-red-300",children:c}),e.jsx(g,{type:"submit",className:"w-full bg-blue-600 font-medium text-white hover:bg-blue-700",disabled:!s||!l||r,children:r?"Processingâ¦":"Pay & renew"})]})}const cP={active:"bg-emerald-500",pending:"bg-amber-500",grace:"bg-orange-500",lapsed:"bg-red-500",expired:"bg-muted-foreground
3950/60",cancelled:"bg-muted-foreground/60",suspended:"bg-amber-500"};function Lu({status:t,label:s}){return e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx("span",{className:me("h-1.5 w-1.5 rounded-full",cP[t]||"bg-muted-foreground"),"aria-hidden":"true"}),e.jsx("span",{className:"text-xs font-medium capitalize text-foreground/85",children:s||t})]})}function dP(){const{data:t,isLoading:s}=xg(),a=gg(),n=Ow(),r=Uw(),i=Gw(),l=Yw(),m=qs(),{data:c}=ma(m||void 0),d=!!c?.settings?.enable_check_payment,u=tN(),h=iN(),[p,x]=o.useState(!1),[f,b]=o.useState(!1),[N,j]=o.useState(!1),[w,v]=o.useState(null),[k,S]=o.useState(""),[_,y]=o.useState(""),[C,P]=o.useState(!0),[A,E]=o.useState(null),[Q,U]=o.useState(!0),[D,K]=o.useState(!1),[xe,z]=o.useState(null),{stripePromise:ae,elementsKey:ue}=Ei(D,xe?.publishableKey??null),[_e,ee]=o.useState(""),[se,le]=o.useState(""),oe=async(ke,ve,Ne)=>{ee(""),le("");try{const Qe=await u.mutateAsync({membership_type_id:ke,auto_renew:ve});Qe.requires_payment?Qe.client_secret&&Qe.publishable_key&&(z({clientSecret:Qe.client_secret,publishableKey:Qe.publishable_key,amount:Qe.amount,membershipTypeName:Qe.membership_type_name}),K(!0)):(le(Qe.message||Ne),E(null))}catch(Qe){ee(Qe?.response?.data?.detail||"Failed to start upgrade. Please try again.")}};if(s)return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg",style:{backgroundColor:"var(--portal-primary-light)",color:"var(--portal-primary)"},children:e.jsx(St,{className:"h-5 w-5"})}),e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:"Subscription"})]}),e.jsx(Y,{className:"h-48"})]});if(!t)return null;if(!t.membership_type_name){const ke=c?.membership_types??[],ve=async()=>{A&&await oe(A.id,Q,"Your membership application is under review.")};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg",style:{backgroundColor:"var(--portal-primary-light)",color:"var(--portal-primary)"},children:e.jsx(fa,{className:"h-5 w-5"})}),e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:"Join as a member"})]}),e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex items-center gap-2.5",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg",style:{backgroundColor:"var(--portal-primary-light)",color:"var(--portal-primary)"},children:e.jsx(jp,{className:"h-4 w-4"})}),"Choose a membership"]})}),e.jsxs($,{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Upgrade your account to access member pricing on events, renewal discounts, and full society benefits."}),_e&&e.jsx("div",{className:"rounded-md bg-destructive/10 p-3 text-sm text-destructive",children:_e}),se&&e.jsx("div",{className:"rounded-md border border-emerald-200 bg-emerald-50 p-3 text-sm text-emerald-800 dark:border-emerald-900/60 dark:bg-emerald-950/30 dark:text-emerald-300",children:se}),!se&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"space-y-2",children:ke.map(Ne=>{const Qe=A?.id===Ne.id,Oe=Number(Ne.price);return e.jsxs("button",{type:"button",onClick:()=>E(Ne),className:"flex w-full items-center justify-between rounded-lg border-2 px-4 py-3 text-left transition-colors",style:Qe?{borderColor:"var(--portal-primary)",backgroundColor:"color-mix(in oklab, var(--portal-primary-light) 60%, transparent)"}:void 0,children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[e.jsx("div",{className:"flex h-5 w-5 shrink-0 items-center justify-center rounded-full border-2 transition-colors",style:Qe?{borderColor:"var(--portal-primary)",backgroundColor:"var(--portal-primary)"}:{borderColor:"var(--border)"},children:Qe&&e.jsx(Xt,{className:"h-3 w-3",style:{color:"var(--portal-primary-fg)"}})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("span",{className:"text-sm font-semibold tracking-tight text-foreground",children:Ne.name}),Ne.description&&e.jsx("p",{className:"mt-0.5 truncate text-xs text-muted-foreground",children:Ne.description}),Oe>0&&Ne.auto_renew_enabled&&Ne.auto_renew_discount_percent>0&&e.jsxs("p",{className:"mt-0.5 text-xs font-medium text-emerald-600 dark:text-emerald-400",children:["Save ",Ne.auto_renew_discount_percent,"% with auto-renew"]})]})]}),e.jsxs("span",{className:"ml-4 shrink-0 text-sm font-semibold tracking-tight text-foreground",children:[Oe===0?"Free":`$${Oe.toFixed(2)}`,Oe>0&&e.jsxs("span",{className:"text-xs font-normal text-muted-foreground",children:["/",Ne.duration_type==="annual"?"yr":Ne.duration_type]})]})]},Ne.id)})}),A&&Number(A.price)>0&&A.auto_renew_enabled&&A.auto_renew_discount_percent>0&&e.jsx("div",{className:"rounded-lg border border-border bg-muted/30 p-4",children:e.jsxs("label",{className:"flex cursor-pointer items-start gap-3",children:[e.jsx(ot,{checked:Q,onCheckedChange:Ne=>U(!!Ne),className:"mt-0.5"}),e.jsxs("div",{children:[e.jsx("span",{className:"text-sm font-semibold tracking-tight text-foreground",children:"Enable auto-renew"}),Q?e.jsxs("p",{className:"mt-1 text-sm text-muted-foreground",children:[e.jsxs("span",{className:"line-through",children:["$",Number(A.price).toFixed(2)]})," ",e.jsxs("span",{className:"font-semibold text-emerald-600 dark:text-emerald-400",children:["$",(Number(A.price)*(1-A.auto_renew_discount_percent/100)).toFixed(2)]}),e.jsxs("span",{className:"ml-2 text-xs font-medium text-emerald-600 dark:text-emerald-400",children:["â ",A.auto_renew_discount_percent,"% discount"]})]}):e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"You'll need to renew manually each year"})]})]})}),e.jsx(g,{onClick:ve,disabled:!A||u.isPending,className:"bg-blue-600 font-medium text-white hover:bg-blue-700",children:u.isPending?"Processingâ¦":A&&Number(A.price)===0?"Apply for membership":"Continue to payment"})]})]})]}),e.jsx(Fe,{open:D,onOpenChange:K,children:e.jsxs(Te,{className:"max-w-md",children:[e.jsxs(Ae,{children:[e.jsx(Ee,{children:"Complete payment"}),e.jsxs(tt,{children:[xe?.membershipTypeName," membership â $",((xe?.amount??0)/100).toFixed(2)]})]}),xe&&ae&&e.jsx(dn,{stripe:ae,options:{clientSecret:xe.clientSecret,appearance:{theme:"stripe"}},children:e.jsx(mP,{amount:xe.amount,onSuccess:async Ne=>{try{await h.mutateAsync({payment_intent_id:Ne}),K(!1),le("Welcome! Your membership is now active."),E(null)}catch{ee("Payment succeeded but confirmation failed. Please contact support."),K(!1)}},onError:Ne=>{ee(Ne),K(!1)}})},ue)]})})]})}const Pe=async()=>{try{await n.mutateAsync(f),x(!1)}catch{}},M=async()=>{try{await r.mutateAsync()}catch{}},I=!!t.term_length_years,R=t.membership_end_date||t.current_period_end,X=t.has_subscription&&t.cancel_at_period_end,Se=t.auto_renew,ce=R?Jp(pt(R),new Date):null;return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg",style:{backgroundColor:"var(--portal-primary-light)",color:"var(--portal-primary)"},children:e.jsx(St,{className:"h-5 w-5"})}),e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:"Subscription"})]}),e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex items-center gap-2.5",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg",style:{backgroundColor:"var(--portal-primary-light)",color:"var(--portal-primary)"},children:e.jsx(fa,{className:"h-4 w-4"})}),"Membership details"]}
3950)}),e.jsxs($,{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"shrink-0 text-sm text-muted-foreground",children:"Membership type"}),e.jsx("span",{className:"text-sm font-semibold",children:t.membership_type_name||"N/A"})]}),t.price!=null&&(()=>{const ke=t.price,ve=t.auto_renew&&t.auto_renew_discount_percent!=null&&t.auto_renew_discount_percent>0,Ne=ve?ke*(1-t.auto_renew_discount_percent/100):ke;return e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"shrink-0 text-sm text-muted-foreground",children:"Price"}),e.jsxs("span",{className:"text-sm font-semibold",children:["$",Ne.toFixed(2)]})]}),ve&&e.jsxs("p",{className:"text-right text-xs font-medium text-emerald-600 dark:text-emerald-400",children:["Includes ",t.auto_renew_discount_percent,"% auto-renew discount (was $",ke.toFixed(2),")"]})]})})(),e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"shrink-0 text-sm text-muted-foreground",children:"Status"}),X?e.jsx(Lu,{status:"cancelled",label:"Cancelling"}):e.jsx(Lu,{status:t.status})]}),t.membership_start_date&&e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"shrink-0 text-sm text-muted-foreground",children:"Start date"}),e.jsx("span",{className:"text-sm font-semibold",children:Be(pt(t.membership_start_date),"MMM d, yyyy")})]}),R&&e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"shrink-0 text-sm text-muted-foreground",children:X?"Access until":ce!==null&&ce<0?"Expired":"Expires"}),e.jsxs("span",{className:"text-right text-sm font-semibold",children:[Be(pt(R),"MMM d, yyyy"),ce!==null&&e.jsxs("span",{className:`ml-1 font-normal ${ce<=30?"text-orange-600 dark:text-orange-400":"text-muted-foreground"}`,children:["(",ce>0?`in ${ce} days`:ce===0?"today":`${Math.abs(ce)} days ago`,")"]})]})]}),!I&&e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx(T,{htmlFor:"auto-renew",className:"shrink-0 text-sm text-muted-foreground",children:"Auto-renew"}),e.jsx(ss,{id:"auto-renew",checked:Se,onCheckedChange:ke=>a.mutate(ke),disabled:a.isPending})]})]})]}),t.has_subscription?e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex items-center gap-2.5",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg",style:{backgroundColor:"var(--portal-primary-light)",color:"var(--portal-primary)"},children:e.jsx(cn,{className:"h-4 w-4"})}),"Subscription actions"]})}),e.jsx($,{children:X?e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Your subscription is set to cancel at the end of the current period. You can reactivate it to continue your membership."}),e.jsx(g,{onClick:M,disabled:r.isPending,className:"font-medium",children:r.isPending?"Reactivatingâ¦":"Reactivate subscription"})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Your subscription is active. You can cancel if needed."}),e.jsx(g,{variant:"destructive",onClick:()=>x(!0),className:"font-medium",children:"Cancel subscription"})]})})]}):I?e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex items-center gap-2.5",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg",style:{backgroundColor:"var(--portal-primary-light)",color:"var(--portal-primary)"},children:e.jsx(Yt,{className:"h-4 w-4"})}),["grace","lapsed","archived"].includes(t.status)?"Action required":"Membership term"]})}),e.jsxs($,{className:"space-y-3",children:[["grace","lapsed","archived"].includes(t.status)&&e.jsxs("div",{className:"flex items-start gap-3 rounded-md border border-orange-200 bg-orange-50 p-3 text-sm text-orange-800 dark:border-orange-900/60 dark:bg-orange-950/30 dark:text-orange-300",children:[e.jsx(Bt,{className:"mt-0.5 h-4 w-4 shrink-0 text-orange-600 dar
3950k:text-orange-400"}),e.jsxs("span",{children:["Your ",t.membership_type_name," membership has ended.",t.converts_to_type_name?` Upgrade to ${t.converts_to_type_name} to maintain your benefits.`:" Contact your society for next steps."]})]}),t.status==="active"&&t.converts_to_type_name&&R&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Your ",t.membership_type_name," membership ends"," ",Be(pt(R),"MMM d, yyyy"),".",t.converts_to_type_price!=null&&t.converts_to_type_price>0?` Upgrade to ${t.converts_to_type_name} for $${t.converts_to_type_price.toFixed(2)}/yr.`:t.converts_to_type_name?` Upgrade to ${t.converts_to_type_name} when ready.`:""]}),t.converts_to_type_id&&t.converts_to_type_name&&e.jsxs(g,{className:"bg-blue-600 font-medium text-white hover:bg-blue-700",disabled:u.isPending,onClick:()=>oe(t.converts_to_type_id,!0,"Your membership has been upgraded."),children:[e.jsx(yl,{className:"mr-2 h-4 w-4"}),u.isPending?"Processingâ¦":`Upgrade to ${t.converts_to_type_name}`]}),_e&&e.jsx("div",{className:"rounded-md bg-destructive/10 p-3 text-sm text-destructive",children:_e}),se&&e.jsx("div",{className:"rounded-md border border-emerald-200 bg-emerald-50 p-3 text-sm text-emerald-800 dark:border-emerald-900/60 dark:bg-emerald-950/30 dark:text-emerald-300",children:se})]})]}):e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex items-center gap-2.5",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg",style:{backgroundColor:"var(--portal-primary-light)",color:"var(--portal-primary)"},children:e.jsx(St,{className:"h-4 w-4"})}),"Renewal"]})}),e.jsx($,{className:"space-y-3",children:["active","grace","lapsed"].includes(t.status)&&!(t.status==="active"&&!R)?e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:t.status==="active"?"Renew your membership early to maintain continuous coverage.":"Your membership needs renewal. Renew now to restore your benefits."}),k&&e.jsx("div",{className:"rounded-md bg-destructive/10 p-3 text-sm text-destructive",children:k}),_&&e.jsx("div",{className:"rounded-md border border-emerald-200 bg-emerald-50 p-3 text-sm text-emerald-800 dark:border-emerald-900/60 dark:bg-emerald-950/30 dark:text-emerald-300",children:_}),t.auto_renew_enabled&&e.jsx("div",{className:"rounded-lg border border-border bg-muted/30 p-4",children:e.jsxs("label",{className:"flex cursor-pointer items-start gap-3",children:[e.jsx(ot,{checked:C,onCheckedChange:ke=>P(!!ke),className:"mt-0.5"}),e.jsxs("div",{children:[e.jsx("span",{className:"text-sm font-semibold tracking-tight text-foreground",children:"Auto-renew my membership"}),C?e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:(()=>{const ke=t.price??0,ve=t.auto_renew_discount_percent??0,Ne=ke*(1-ve/100),Qe=t.projected_period_end?jj(Ps(t.projected_period_end),7):null,Oe=Qe&&vj(Qe,new Date)?Be(Qe,"MMM d, yyyy"):null;return e.jsxs(e.Fragment,{children:[ve>0&&e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"line-through",children:["$",ke.toFixed(2)]})," ",e.jsxs("span",{className:"font-semibold text-emerald-600 dark:text-emerald-400",children:["$",Ne.toFixed(2)]}),e.jsxs("span",{className:"ml-2 text-xs font-medium text-emerald-600 dark:text-emerald-400",children:["â ",ve,"% auto-renew discount"]}),e.jsx("br",{})]}),"Your card will be charged $",Ne.toFixed(2)," automatically",Oe?` around ${Oe}`:""," and around the same time each cycle after. Renewal prices may change. Turn auto-renew off anytime on this page â doing so doesn't cancel your current membership."]})})()}):e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"One-time renewal â you'll need to renew manually next year."})]})]})}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(g,{onClick:async()=>{S(""),y("");try{const ke=await i.mutateAsync(C);v(ke),j(!0)}catch(ke){S(ke?.response?.data?.detail||"Failed to start renewal. Please try again.")}},disabled:i.isPending,className:"font-medium",children:i.isPending?"Preparingâ¦":"Renew now"}),d&&e.jsx(g,{variant:"outline",onClick:async()=>{S(""),y("");try{const ke=await l.mutateAsync();y(ke.message)}catch(ke){S(ke?.response?.data?.detail||"Failed to request check renew
3950al. Please try again.")}},disabled:l.isPending,children:l.isPending?"Requestingâ¦":"Renew by check"})]})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Contact your society for renewal options."})})]}),e.jsx(iP,{open:N,onOpenChange:j,intentData:w}),e.jsx(Fe,{open:p,onOpenChange:x,children:e.jsxs(Te,{children:[e.jsxs(Ae,{children:[e.jsx(Ee,{children:"Cancel subscription"}),e.jsx(tt,{children:"Choose how you would like to cancel your subscription."})]}),e.jsxs("div",{className:"space-y-3 py-4",children:[e.jsxs("label",{className:"flex cursor-pointer items-start gap-3",children:[e.jsx("input",{type:"radio",name:"cancelType",checked:!f,onChange:()=>b(!1),className:"mt-1"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-semibold tracking-tight",children:"Cancel at period end"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Keep access until your current period ends",R&&` (${Be(pt(R),"MMM d, yyyy")})`,"."]})]})]}),e.jsxs("label",{className:"flex cursor-pointer items-start gap-3",children:[e.jsx("input",{type:"radio",name:"cancelType",checked:f,onChange:()=>b(!0),className:"mt-1"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-semibold tracking-tight",children:"Cancel immediately"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Lose access right away. No refund will be issued."})]})]})]}),e.jsxs(Ge,{children:[e.jsx(g,{variant:"outline",onClick:()=>x(!1),children:"Keep subscription"}),e.jsx(g,{variant:"destructive",onClick:Pe,disabled:n.isPending,className:"font-medium",children:n.isPending?"Cancellingâ¦":"Confirm cancel"})]})]})})]})}function mP({amount:t,onSuccess:s,onError:a}){const n=mn(),r=un(),[i,l]=o.useState(!1),[m,c]=o.useState(!1),[d,u]=o.useState(null),h=async p=>{if(p.preventDefault(),!n||!r||!m)return;l(!0),u(null);const x=await n.confirmPayment({elements:r,confirmParams:{return_url:window.location.href},redirect:"if_required"});if(x.error){const f=x.error.message||"Payment failed";u(f),l(!1),a(f)}else x.paymentIntent?.status==="succeeded"&&(l(!1),s(x.paymentIntent.id))};return e.jsxs("form",{onSubmit:h,className:"space-y-4",children:[e.jsx(hn,{onReady:()=>c(!0)}),d&&e.jsx("div",{className:"rounded-md bg-destructive/10 p-3 text-sm text-destructive",children:d}),e.jsx(g,{type:"submit",disabled:!n||!m||i,className:"w-full bg-blue-600 font-medium text-white hover:bg-blue-700",children:i?"Processingâ¦":`Pay $${(t/100).toFixed(2)}`})]})}function iy({email:t,loginPath:s}){return e.jsxs("div",{className:"rounded-lg border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-900",children:["An account with this email already exists, but its membership payment wasn't completed."," ",e.jsx(je,{to:s,state:{email:t},className:"font-semibold underline",children:"Log in to finish your payment"}),"."]})}function ly({email:t,societySlug:s,loginHref:a}){const[n,r]=o.useState("idle"),[i,l]=o.useState(""),m=async()=>{r("sending"),l("");try{await Me.post("/portal/magic-link",{email:t,society_slug:s}),r("sent")}catch(c){const d=c?.response;l(d?.status===429?"Too many requests. Please wait a minute and try again.":"Could not send the link. Please try again."),r("error")}};return n==="sent"?e.jsx("div",{className:"rounded-lg border border-emerald-200 bg-emerald-50 px-4 py-3 text-sm text-emerald-800",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Kt,{className:"mt-0.5 h-4 w-4 shrink-0"}),e.jsxs("div",{children:[e.jsxs("p",{className:"font-medium",children:["Sign-in link sent to ",t]}),e.jsx("p",{className:"mt-1",children:"Check your inbox and click the link to sign in to your account. The link works for 4 hours."}),e.jsxs("p",{className:"mt-2",children:["Or"," ",e.jsx(je,{to:a,className:"font-medium underline",children:"sign in with your password"}),"."]})]})]})}):e.jsxs("div",{className:"rounded-lg border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-900",children:[e.jsx("p",{className:"font-medium",children:"An account with this email already exists."}),e.jsx("p",{className:"mt-1",children:"No need to sign up again â we can email you a secure sign-in link, no password required."}),e.jsxs("button",{type:"button",onClick:()=>{m()},disabled:n==="sending",className:"mt-3 inline-flex items-center gap-2 rounded-lg bg-blue-600 px-4 py-2 text-sm font-semibold text-white transition-colors hover:bg-blue-700 disabled:cursor-not-allowed disabled:opacity-50",children:[e.jsx($t,{className:"h-4 w-4"}),n==="sending"?"Sendingâ¦":"Email me a sign-in link"]}),n==="error"&&e.jsx("p",{className:"mt-2 text-red-700",children:i}),e.jsxs("p",{className:"mt-2 text-amber-800",children:["Or"," ",e.jsx(je,{to:a,className:"font-medium underline",children:"sign in with your password"}),"."]})]})}function oy({slug:t,resumeToken:s,initialPayment:a,startSettling:n=!1,primaryColor:r,contactEmail:i,loginHref:l,onActivated:m,onBack:c}
3950){const[d]=o.useState(s),[u,h]=o.useState(a&&!n?"pay":d?"loading":"expired"),[p,x]=o.useState(a??null),[f,b]=o.useState(null),[N,j]=o.useState(0),[w,v]=o.useState(!1),k=p?.publishableKey??null,S=Td(k,N);o.useEffect(()=>{let xe=!0;return S?.then(z=>{xe&&!z&&v(!0)}),()=>{xe=!1}},[S]);const _=o.useRef(null),y=o.useRef(!1),C=o.useRef(null),P=o.useRef(!0),A=o.useRef(null),E=o.useRef(null),Q=o.useRef(m);o.useEffect(()=>{Q.current=m},[m]);const U=()=>{C.current!==null&&(window.clearTimeout(C.current),C.current=null)},D=o.useCallback(async()=>{if(y.current||!P.current)return;if(!d){h("expired");return}y.current=!0,U();const xe=z=>{const ae=A.current;if(ae===null||Date.now()+z>ae){E.current==="processing"?(Ln(t),h("processing_timeout")):h("unknown");return}C.current=window.setTimeout(()=>{D()},z)};try{const z=await gt.resumeSignupPayment(t,d);if(!P.current)return;switch(E.current=z.outcome,z.outcome){case"pay":A.current=null,b(_.current),_.current=null,x({clientSecret:z.client_secret,publishableKey:z.publishable_key,amount:z.amount,memberName:z.member_name,membershipTypeName:z.membership_type_name,memberId:z.member_id}),h("pay");break;case"processing":h("processing"),A.current===null&&(A.current=Date.now()+_o),xe(Oj);break;case"activated":Ln(t),h("activated"),Q.current?.();break;case"activation_pending":Ln(t),h("activation_pending");break;default:Ln(t),h("contact_office")}}catch(z){if(!P.current)return;on(z)===401?(Ln(t),h("expired")):A.current!==null?xe(Uj):h("unknown")}finally{y.current=!1}},[t,d]),K=o.useCallback((xe="Your payment wasn't completed. Please try again.")=>{_.current=xe,A.current=Date.now()+_o,E.current=null,h("settling"),D()},[D]);return o.useEffect(()=>(P.current=!0,n?K():a||D(),()=>{P.current=!1,U()}),[]),u==="pay"&&p&&w?e.jsx(bn,{icon:e.jsx(Qt,{className:"h-6 w-6 text-slate-500"}),title:"We couldn't load the secure card form",body:"Please check your connection (or any content blocker) and try again.",action:e.jsx(g,{type:"button",className:"signup-cta-btn",onClick:()=>{v(!1),j(xe=>xe+1)},children:"Try again"})}):u==="pay"&&p?e.jsxs(dn,{stripe:S,options:{clientSecret:p.clientSecret,appearance:{theme:"stripe",variables:{colorPrimary:r}}},children:[f&&e.jsx("div",{className:"mb-4 rounded-lg border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-900",children:f}),e.jsx(uP,{slug:t,payment:p,onSubmitting:()=>b(null),onSettle:K,onBack:c})]},`${p.clientSecret}:${N}`):u==="loading"||u==="settling"||u==="processing"?e.jsx(bn,{icon:e.jsx(ea,{className:"h-6 w-6 text-slate-500"}),title:u==="loading"?"Loading your paymentâ¦":"Confirming your paymentâ¦",body:u==="loading"?null:"Your payment is being processed. This page will update automatically.",busy:!0}):u==="activated"?e.jsx(bn,{tone:"success",icon:e.jsx(Kt,{className:"h-7 w-7 text-emerald-500"}),title:"Your membership is active",body:"Thank you â your payment went through. You can now log in to your member portal.",action:e.jsx(Xi,{to:l,children:"Log in"})}):u==="processing_timeout"?e.jsx(bn,{icon:e.jsx(ea,{className:"h-6 w-6 text-slate-500"}),title:"Your payment is processing",body:"We'll email you when your membership is active. There's no need to pay again.",action:e.jsx(Xi,{to:l,children:"Go to login"})}):u==="unknown"?e.jsx(bn,{icon:e.jsx(ea,{className:"h-6 w-6 text-slate-500"}),title:"We couldn't confirm your payment status",body:"Your payment may still be going through. Please check again in a moment rather than paying again.",action:e.jsx(g,{type:"button",onClick:()=>{A.current=Date.now()+_o,h("settling"),D()},className:"signup-cta-btn",children:"Check again"})}):u==="expired"?n?e.jsx(bn,{icon:e.jsx(ea,{className:"h-6 w-6 text-slate-500"}),title:"Log in to check your payment",body:"Your payment may have gone through. Log in to see your membership â please don't pay again first.",action:e.jsx(Xi,{to:l,children:"Log in"})}):e.jsx(bn,{icon:e.jsx(ea,{className:"h-6 w-6 text-slate-500"}),title:"Log in to finish your payment",body:"For your security, this payment page has expired. Log in again to continue â if you already paid, logging in will show your membership.",action:e.jsx(Xi,{to:l,children:"Log in"})}):e.jsx(bn,{icon:e.jsx($t,{className:"h-6 w-6 text-slate-500"}),title:u==="activation_pending"?"We've received your payment":"Please contact the society office",body:u==="activation_pending"?"Your membership hasn't been activated yet. Please contact the society office so they can finish setting it up â there's no need to pay again.":"We couldn't reopen your payment online. If you chose to pay by check, your membership starts once your payment is received. Otherwise, the society office can help you finish setting up your membership.",action:i?e.jsx("a",{href:`mailto:${i}`,className:"inline-flex items-center gap-1.5 text-sm font-medium hover:underline",style:{color:"var(--portal-primary)"},children:i}):null})}function Xi({to:t,children:s}){return e.jsx(je,{to:t,className:"inline-flex items-center gap-1.5 text-sm font-medium hover:underline",style:{color:"var(--portal-primary)"},children:s})}function bn({icon:t,title:s,body:a,action:n,tone:r,busy:i}){return e.jsxs("div",{className:"py-4 text-center",role:"status","aria-busy":i||void 0,children:[e.jsx("div",{className:`mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-full ${r==="success"?"bg-emerald-50":"bg-slate-100"}`,children:t}),e.jsx("h2",{className:"text-lg font-semibold text-slate-900",children:s}),a&&e.jsx("p",{className:"mt-2 text-sm leading-relaxed text-slate-500",children:a}),n&&e.jsx("div",{className:"mt-5",children:n})]})}function uP({slug:t,payment:s,onSubmitting:a,onSettle:n,onBack:r}){const i=mn(),l=un(),[m,c]=o.useState(!1),[d,u]=o.useState(null),[h,p]=o.use
3950State(!1),x=async f=>{if(f.preventDefault(),!i||!l||!h)return;c(!0),u(null),a?.(),Mj(t,Dj(s.clientSecret));const b=await i.confirmPayment({elements:l,confirmParams:{return_url:window.location.href},redirect:"if_required"});if(b.error){if(zj(b.error)){u(b.error.message||"Payment failed"),c(!1);try{await gt.logSignupPaymentFailure(t,{member_id:s.memberId,error_code:b.error.code||void 0,decline_code:b.error.decline_code||void 0,error_message:b.error.message||void 0,payment_intent_id:b.error.payment_intent?.id||void 0})}catch{}return}n(b.error.message?`Your payment didn't go through: ${b.error.message}`:"Your payment didn't go through. Please try again.");return}if(b.paymentIntent?.status==="succeeded")try{await gt.confirmSignupPayment(t,b.paymentIntent.id,s.memberId)}catch(N){console.error("Backend confirm failed:",N)}n("Your payment wasn't completed. Please try again.")};return e.jsxs("form",{onSubmit:x,className:"space-y-5",children:[e.jsx("div",{className:"rounded-xl border-2 border-slate-200 bg-slate-50 p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-semibold text-slate-900",children:s.membershipTypeName}),e.jsx("p",{className:"text-xs text-slate-500",children:s.memberName})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Qt,{className:"h-4 w-4 text-slate-400"}),e.jsxs("p",{className:"text-lg font-semibold tracking-tight text-slate-900",children:["$",(s.amount/100).toFixed(2)]})]})]})}),e.jsx(hn,{onReady:()=>p(!0)}),d&&e.jsx("div",{className:"rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700",children:d}),e.jsxs("div",{className:`flex items-center border-t border-slate-100 pt-5 ${r?"justify-between":"justify-end"}`,children:[r&&e.jsxs(g,{type:"button",variant:"ghost",onClick:r,disabled:m,className:"text-slate-400 hover:text-slate-600",children:[e.jsx(es,{className:"mr-1.5 h-4 w-4"}),"Back"]}),e.jsx(g,{type:"submit",size:"lg",disabled:!i||!h||m,className:"signup-cta-btn w-full sm:w-auto",children:m?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"mr-2 inline-block h-4 w-4 animate-spin rounded-full border-2 border-white/30 border-t-white"}),"Processing..."]}):`Pay $${(s.amount/100).toFixed(2)}`})]})]})}const $u="h-11 w-full rounded-lg border-border bg-card pl-11 pr-10 text-sm text-foreground placeholder:text-muted-foreground focus-visible:ring-2 focus-visible:ring-blue-500/20 focus-visible:ring-offset-0 focus-visible:border-blue-400 transition-colors";function ec(t){return t.length>=8&&/[A-Z]/.test(t)&&/[a-z]/.test(t)&&/\d/.test(t)}function qu(t){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)}function hP(t){if(!t)return{score:0,label:""};let s=0;return t.length>=8&&s++,t.length>=12&&s++,/[A-Z]/.test(t)&&/[a-z]/.test(t)&&s++,/\d/.test(t)&&s++,/[^A-Za-z0-9]/.test(t)&&s++,s<=1?{score:1,label:"Weak"}:s===2?{score:2,label:"Fair"}:s===3?{score:3,label:"Good"}:{score:4,label:"Strong"}}const pP={1:"active-weak",2:"active-fair",3:"active-good",4:"active-strong"},xP={1:"text-red-500",2:"text-amber-500",3:"text-blue-500",4:"text-emerald-500"};function gP(t){if(!t.start_date)return"";const a=new Date(t.start_date+"T00:00:00").toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"});if(!t.end_date||t.end_date===t.start_date)return a;const r=new Date(t.end_date+"T00:00:00").toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"});return`${a} â ${r}`}function dr({label:t,required:s,hint:a,children:n}){return e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(T,{className:"block text-[11px] font-semibold tracking-wide text-slate-500",children:[t,s&&e.jsx("span",{className:"ml-0.5 text-red-400",children:"*"})]}),n,a&&e.jsx("p",{className:"text-[10px] text-slate-400",children:a})]})}function el({icon:t,valid:s,trailing:a,...n}){return e.jsxs("div",{className:"premium-input-wrapper",children:[e.jsx(t,{className:"input-icon"}),e.jsx(O,{...n,className:a?`${$u} pr-16`:$u}),a&&e.jsx("div",{className:"pointer-events-none absolute right-0 top-0 flex h-full items-center pr-3",children:e.jsx("div",{className:"pointer-events-auto",children:a})}),s&&e.jsx(Kt,{className:"input-check",style:a?{right:"2.5rem"}:void 0})]})}function fP({slug:t,eventId:s,event:a}){const n=us(),r=kt(),{login:i}=ft(),{data:l,isLoading:m}=ma(t||void 0),c=yg();Ra(l?.society?.favicon_url);const[d,u]=o.useState({first_name:"",last_name:"",email:"",password:""}
3950),[h,p]=o.useState(""),[x,f]=o.useState(null),[b,N]=o.useState(""),[j,w]=o.useState(!1),[v,k]=o.useState(!1),[S,_]=o.useState(!1),[y,C]=o.useState(""),[P,A]=o.useState(null),E=o.useMemo(()=>hP(d.password),[d.password]),Q=a?.eligible_non_member_roles??l?.non_member_role_options??[],U=a?.signup_membership_types??[],D=U.length>0,K=D?U.length===1?U[0].id:b:"",xe=l?.society?.logo_url,z=xe?`${ds}${xe}`:null,ae=l?.society?.primary_color||"#1a365d",ue=Si(ae),_e=n(`/login?redirect=${encodeURIComponent(`/events/${s}`)}`),ee=d.first_name.trim().length>=1&&d.last_name.trim().length>=1&&qu(d.email)&&ec(d.password)&&(D?K!=="":h!=="")&&j&&!c.isPending,se=async le=>{if(le.preventDefault(),!(!ee||!t)){C(""),f(null),A(null);try{await c.mutateAsync({slug:t,data:{email:d.email,password:d.password,first_name:d.first_name,last_name:d.last_name,...D?{membership_type_id:K}:{declared_role_type_id:h},marketing_consent:v,auto_renew:!1}});try{await i(d.email,d.password,t)}catch{}r(n(`/events/${s}`),{replace:!0})}catch(oe){const Pe=oe?.response,M=Pe?.status,I=Pe?.data?.detail;if(M===429)C("Too many attempts. Please wait a moment and try again.");else if(M===409)I==="account_exists_pending_approval"?C("An account with this email already exists and is awaiting approval. You'll receive an email once it's approved â no need to sign up again."):I==="account_exists_payment_incomplete"?A(d.email):I==="account_exists_payment_pending"?C(cx):I==="account_exists_contact_support"?C("An account with this email already exists. Please contact the society office for help with your account."):f(d.email);else if(typeof I=="string")if(I==="free_dues_type_not_eligible_as_role"){const R=Q.find(Se=>Se.id===h)?.name??"that category",X=l?.society?.name??"the society";C(`To register as ${R}, you must first join ${X} as a member â that membership requires verification by our staff. Please choose a different option above, or sign in if you already have an account.`)}else C(I);else if(Array.isArray(I)){const R=I.map(X=>{const Se=X.msg?.replace(/^Value error, /i,"").replace(/^value is not a valid /,"Invalid ")||"Invalid field",ce=X.loc?.slice(-1)[0];return ce?`${ce.replace(/_/g," ")}: ${Se}`:Se});C(R.join(` 3951`))}else C("Signup failed. Please try again.")}}};return m?e.jsx("div",{className:"signup-page-bg flex items-center justify-center px-4",children:e.jsxs("div",{className:"w-full max-w-xl space-y-4",children:[e.jsx(Y,{className:"mx-auto h-16 w-48"}),e.jsx(Y,{className:"mx-auto h-6 w-64"}),e.jsx(Y,{className:"h-72 rounded-2xl"})]})}):l?e.jsxs("div",{className:"min-h-screen bg-background",style:ue,children:[e.jsx("div",{className:"h-1.5 w-full",style:{backgroundColor:"var(--portal-primary)"}}),e.jsx("div",{className:"signup-page-bg px-4 py-6 sm:py-10",children:e.jsxs("div",{className:"mx-auto w-full max-w-xl",children:[e.jsx("div",{className:"mb-6 text-center",children:z?e.jsx("img",{src:z,alt:l.society.name,className:"mx-auto h-12 object-contain"}):e.jsx("div",{className:"mx-auto flex h-12 w-12 items-center justify-center rounded-xl text-xl font-semibold",style:{backgroundColor:"var(--portal-primary)",color:"var(--portal-primary-fg)"},children:l.society.name.charAt(0)})}),e.jsxs("div",{className:"signup-container",children:[a&&e.jsxs("div",{className:"mb-5 space-y-1",children:[e.jsxs("h1",{className:"text-xl font-semibold tracking-tight text-slate-900",children:["Register for ",a.name]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 text-sm text-slate-500",children:[a.start_date&&e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Yt,{className:"h-3.5 w-3.5 shrink-0"}),gP(a)]}),(a.venue||a.location)&&e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Fa,{className:"h-3.5 w-3.5 shrink-0"}),a.venue??a.location]})]})]}),!a&&e.jsxs("div",{className:"mb-5",children:[e.jsx("h1",{className:"text-xl font-semibold tracking-tight text-slate-900",children:"Register for this event"}),e.jsx("p",{className:"mt-1 text-sm text-slate-500",children:"Create an account to complete your registration."})]}),e.jsxs("div",{className:"mb-5 flex items-center justify-between rounded-xl border-2 border-blue-100 bg-blue-50 px-4 py-3",children:[e.jsx("span",{className:"text-sm text-slate-700",children:D?"Already have an account?":`Already a ${l?.society?.name?`${l.society.name} `:""}member?`}),e.jsxs(je,{to:_e,"data-testid":"sign-in-link",className:"inline-flex items-center gap-1.5 text-sm font-semibold text-blue-600 transition-colors hover:text-blue-700",children:["Sign in",e.jsx(as,{className:"h-3.5 w-3.5"})]})]}),e.jsxs("div",{className:"relative mb-5",children:[e.jsx("div",{className:"absolute inset-0 flex items-center",children:e.jsx("div",{className:"w-full border-t border-slate-200"})}),e.jsx("div",{className:"relative flex justify-center",children:e.jsx("span",{className:"bg-card px-3 text-xs font-medium text-slate-400",children:"New here? Create an account to register"})})]}),e.jsxs("form",{onSubmit:le=>{se(le)},className:"space-y-4",noValidate:!0,children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsx(dr,{label:"First name",required:!0,children:e.jsx(el,{icon:kn,id:"first_name",autoComplete:"given-name",value:d.first_name,onChange:le=>u(oe=>({...oe,first_name:le.target.value})),placeholder:"Jane",required:!0,valid:d.first_name.trim().length>=1})}),e.jsx(dr,{label:"Last name",required:!0,children:e.jsx(el,{icon:kn,id:"last_name",autoComplete:"family-name",value:d.last_name,onChange:le=>u(oe=>({...oe,last_name:le.target.value})),placeholder:"Smith",required:!0,valid:d.last_name.trim().length>=1})})]}),e.jsx(dr,{label:"Email",required:!0,children:e.jsx(el,{icon:$t,id:"email",type:"email",autoComplete:"email",value:d.email,onChange:le=>{f(null),A(null),u(oe=>({...oe,email:le.target.value}))},placeholder:"[email protected]",required:!0,valid:qu(d.email)})}),e.jsxs(dr,{label:"Password",required:!0,hint:"8+ characters, uppercase, lowercase, and a number",children:[e.jsx(el,{icon:Ys,id:"password",type:S?"text":"password",autoComplete:"new-password",value:d.password,onChange:le=>u(oe=>({...oe,password:le.target.value})),placeholder:"Create a secure password",required:!0,minLength:8,valid:ec(d.password),trailing:e.jsx("button",{type:"button",onClick:()=>_(le=>!le),"aria-label":S?"Hide password":"Show password",className:"text-slate-400 transition-colors hover:text-slate-600",children:S?e.jsx(Er,{className:"h-4 w-4"}):e.jsx(ca,{className:"h-4 w-4"})})}),d.password.length>0&&e.jsxs("div",{className:"mt-2",children:[e.jsx("div",{className:"strength-meter",children:[1,2,3,4].map(le=>e.jsx("div",{className:`bar ${E.score>=le?pP[E.score]:""}`},le))}),e.jsx("p",{className:`mt-1 text-[11px] font-medium ${xP[E.score]||"text-slate-400"}`,children:E.label}),!ec(d.password)&&e.jsx("ul",{className:"mt-2 space-y-0.5",children:[{met:d.password.length>=8,label:"At least 8 characters"},{met:/[A-Z]/.test(d.password),label:"One uppercase letter"},{met:/[a-z]/.test(d.password),label:"One lowercase letter"},{met:/\d/.test(d.password),label:"One number"}].map(le=>e.jsxs("li",{className:`flex items-center gap-1.5 text-[11px] ${le.met?"text-emerald-600":"text-slate-500"}`,children:[le.met?e.jsx(Xt,{className:"h-3 w-3 shrink-0"}):e.jsx("span",{className:"h-3 w-3 shrink-0 rounded-full border border-slate-300"}),le.label]},le.label))})]})]}),D?e.jsx(dr,{label:"Registering as",required:!0,children:U.length===1?e.jsx("div",{className:"flex h-11 w-full items-center rounded-lg border border-border bg-muted/40 px-4 text-sm font-medium text-foreground",children:U[0].name}):e.jsxs("div",{className:"relative",children:[e.jsxs("select",{id:"signup_membership_type_id",value:b,onChange:le=>N(le.target.value),required:!0,"aria-label":"Registering as",className:"h-11 w-full appearance-none rounded-lg border border-border bg-card px-4 pr-10 text-sm text-foreground focus:border-blue-400 focus:outline-none focus:ring-2 focus:ring-blue-500/20",children:[e.jsx("option",{value:"",children:"Selectâ¦"}),U.map(le=>e.jsx("option",{value:le.id,children:le.name}
3951,le.id))]}),e.jsx("div",{className:"pointer-events-none absolute right-3 top-1/2 -translate-y-1/2",children:e.jsx("svg",{className:"h-4 w-4 text-slate-400",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M19 9l-7 7-7-7"})})})]})}):e.jsxs(dr,{label:"Professional role",required:!0,children:[e.jsxs("div",{className:"relative",children:[e.jsxs("select",{id:"declared_role_type_id",value:h,onChange:le=>p(le.target.value),required:!0,"aria-label":"Professional role",className:"h-11 w-full appearance-none rounded-lg border border-border bg-card px-4 pr-10 text-sm text-foreground focus:border-blue-400 focus:outline-none focus:ring-2 focus:ring-blue-500/20",children:[e.jsx("option",{value:"",children:"Select your role"}),Q.map(le=>e.jsx("option",{value:le.id,children:le.name},le.id))]}),e.jsx("div",{className:"pointer-events-none absolute right-3 top-1/2 -translate-y-1/2",children:e.jsx("svg",{className:"h-4 w-4 text-slate-400",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M19 9l-7 7-7-7"})})})]}),Q.length===0&&!m&&e.jsx("p",{className:"text-[10px] text-amber-600",children:"No roles available â contact the society."})]}),e.jsxs("div",{className:"space-y-3 rounded-lg border border-slate-200 bg-slate-50 p-4",children:[e.jsxs("label",{className:"flex cursor-pointer items-start gap-3",children:[e.jsx("input",{type:"checkbox",checked:j,onChange:le=>w(le.target.checked),className:"mt-0.5 h-4 w-4 rounded border-slate-300 text-blue-600 focus:ring-blue-500","aria-label":"I agree to the Terms of Service and Privacy Policy"}),e.jsxs("span",{className:"text-sm text-slate-700",children:["I agree to the"," ",e.jsx(je,{to:n("/terms"),target:"_blank",className:"font-medium text-blue-600 underline hover:text-blue-700",onClick:le=>le.stopPropagation(),children:"Terms of Service"})," ","and"," ",e.jsx(je,{to:n("/privacy"),target:"_blank",className:"font-medium text-blue-600 underline hover:text-blue-700",onClick:le=>le.stopPropagation(),children:"Privacy Policy"})," ",e.jsx("span",{className:"text-red-500",children:"*"})]})]}),e.jsxs("label",{className:"flex cursor-pointer items-start gap-3",children:[e.jsx("input",{type:"checkbox",checked:v,onChange:le=>k(le.target.checked),className:"mt-0.5 h-4 w-4 rounded border-slate-300 text-blue-600 focus:ring-blue-500","aria-label":"I'd like to receive email updates and announcements"}),e.jsx("span",{className:"text-sm text-slate-600",children:"I'd like to receive email updates and announcements"})]})]}),y&&e.jsx("div",{className:"whitespace-pre-line rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700",children:y}),P&&e.jsx(iy,{email:P,loginPath:n("/login")}),x&&e.jsx(ly,{email:x,societySlug:t,loginHref:_e}),e.jsx("button",{type:"submit",disabled:!ee,"data-testid":"event-signup-submit",className:"w-full rounded-lg bg-blue-600 px-6 py-3 text-sm font-semibold text-white transition-colors hover:bg-blue-700 disabled:cursor-not-allowed disabled:opacity-50",children:c.isPending?e.jsxs("span",{className:"flex items-center justify-center gap-2",children:[e.jsx("span",{className:"inline-block h-4 w-4 animate-spin rounded-full border-2 border-white/30 border-t-white"}),"Creating account..."]}):e.jsxs("span",{className:"flex items-center justify-center gap-1.5",children:["Create account & continue",e.jsx(as,{className:"h-4 w-4"})]})})]})]})]})})]}):e.jsx("div",{className:"signup-page-bg flex items-center justify-center px-4",children:e.jsxs("div",{className:"signup-container max-w-md text-center",children:[z&&e.jsx("img",{src:z,alt:"Logo",className:"mx-auto mb-6 h-14 object-contain"}),e.jsx("div",{className:"mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-red-50",children:e.jsx(ad,{className:"h-6 w-6 text-red-500"})}),e.jsx("h2",{className:"text-lg font-semibold text-slate-900",children:"Something Went Wrong"}),e.jsx("p",{className:"mt-2 text-sm leading-relaxed text-slate-500",children:"We were unable to load the signup page. Please try again later."})]})})}
3951const yP=[{key:"select-type",label:"Choose Plan"},{key:"personal-info",label:"Your Details"},{key:"review",label:"Review"},{key:"payment",label:"Payment"}],bP=[{key:"browse-events",label:"Browse Events"},{key:"select-type",label:"Save on Events"},{key:"personal-info",label:"Create Account"},{key:"review",label:"Review"},{key:"payment",label:"Payment"}],jP=[{key:"select-type",label:"Membership"},{key:"personal-info",label:"Create Account"},{key:"review",label:"Review"},{key:"payment",label:"Payment"}],Iu="h-11 w-full rounded-lg border-border bg-card pl-11 pr-10 text-sm text-foreground placeholder:text-muted-foreground focus-visible:ring-2 focus-visible:ring-blue-500/20 focus-visible:ring-offset-0 focus-visible:border-blue-400 transition-colors",cy="h-11 w-full rounded-lg border-border bg-card px-4 text-sm text-foreground placeholder:text-muted-foreground focus-visible:ring-2 focus-visible:ring-blue-500/20 focus-visible:ring-offset-0 focus-visible:border-blue-400 transition-colors";function vP(t){if(!t)return{score:0,label:""};let s=0;return t.length>=8&&s++,t.length>=12&&s++,/[A-Z]/.test(t)&&/[a-z]/.test(t)&&s++,/\d/.test(t)&&s++,/[^A-Za-z0-9]/.test(t)&&s++,s<=1?{score:1,label:"Weak"}:s===2?{score:2,label:"Fair"}:s===3?{score:3,label:"Good"}:{score:4,label:"Strong"}}const wP={1:"active-weak",2:"active-fair",3:"active-good",4:"active-strong"},NP={1:"text-red-500",2:"text-amber-500",3:"text-blue-500",4:"text-emerald-500"};function Ou(t){const s=t.replace(/\D/g,"").slice(0,15);return s.length>10||s.length<=3?s:s.length<=6?`(${s.slice(0,3)}) ${s.slice(3)}`:`(${s.slice(0,3)}) ${s.slice(3,6)}-${s.slice(6)}`}function Uu(t){if(!t)return!1;const s=t.replace(/\D/g,"");return s.length>=10&&s.length<=15}function zu(t){return t?t.trim().length>=3:!1}function Bu(t){if(!/^[\d-]*$/.test(t))return t;const a=t.replace(/\D/g,"").slice(0,9);return a.length<=5?a:`${a.slice(0,5)}-${a.slice(5)}`}function tc(t){return t.length>=8&&/[A-Z]/.test(t)&&/[a-z]/.test(t)&&/\d/.test(t)}function tl(t){return t?new Date(t+"T00:00:00").toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):""}function Ku(){const t=qs(),s=us(),[a]=ws(),n=a.get("mode")==="event-registration",r=a.get("event"),i=r&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(r)?r:null,l=a.get("product"),m=a.get("redirect"),c=a.get("membership_type"),{data:d,isLoading:u,error:h}=ma(t||void 0),{data:p,isLoading:x}=Ww(n&&!l&&t||void 0),{data:f}=Vw(l&&t||void 0,l),b=yg();Ra(d?.society?.favicon_url);const N=n&&!!l,[j,w]=o.useState(n),[v,k]=o.useState(n&&!l?"browse-events":"select-type"),[S,_]=o.useState(null),[y,C]=o.useState(null),[P,A]=o.useState(null),[E,Q]=o.useState({email:"",password:"",first_name:"",last_name:"",organization:"",phone:"",address_line1:"",city:"",state:"",postal_code:"",country:"",fellowship_end_date:"",residency_end_date:""}),[U,D]=o.useState({}),[K,xe]=o.useState(!0),[z,ae]=o.useState("card"),[ue,_e]=o.useState(!1),[ee,se]=o.useState(""),[le,oe]=o.useState(null),[Pe,M]=o.useState(!1),[I,R]=o.useState(!1),[X,Se]=o.useState(!1),[ce,ke]=o.useState(""),[ve,Ne]=o.useState(null),[Qe,Oe]=o.useState(""),[Ce,ze]=o.useState(!1),[Ze,Re]=o.useState(null),[de,ge]=o.useState(null),[mt,ye]=o.useState(null),Ke=kt(),{login:ut,member:De}=ft(),[he,Xe]=o.useState(""),rt=o.useMemo(()=>vP(E.password),[E.password]),[yt,dt]=o.useState(!1),jt=o.useRef(E),Ot=o.useRef(()=>{});o.useEffect(()=>{jt.current=E},[E]),o.useEffect(()=>{Ot.current=(Z,We)=>{let Ve=We;Z==="phone"&&(Ve=Ou(We)),Z==="postal_code"&&(Ve=Bu(We)),Q(xt=>({...xt,[Z]:Ve}))}}),o.useEffect(()=>{const Z=We=>{const Ve=We;if(Ve.animationName!=="ams-autofill-start")return;const xt=Ve.target;if(!xt?.id||xt.value==null)return;const Ht=xt.id,Zt=jt.current[Ht];typeof Zt=="string"&&Zt!==xt.value&&Ot.current(xt.id,xt.value)};return document.addEventListener("animationstart",Z,!0),()=>document.removeEventListener("animationstart",Z,!0)},[]);const be=ta(),[lt]=o.useState(()=>hx(be.search));o.useEffect(()=>{if(!t)return;const Z=mx(t,{locationKey:be.key,stripeReturnPaymentIntent:ux(be.search)});lt?Ke(s("/complete-payment")+be.search,{replace:!0,state:{settle:!0,pass:Z}}):Z&&Ke(s("/complete-payment"),{replace:!0,state:{pass:Z}})},[t]),o.useEffect(()=>{!De||!n||!i||Ke(s(`/events/${i}`),{replace:!0})},[De,n,i,Ke,s]),o.useEffect(()=>{if(!i||!p||y)return;const Z=p.find(We=>We.id===i);Z&&(Z.spots_left===null||Z.spots_left>0)&&(C(Z),k("select-type"))},[i,p,y]),o.useEffect(()=>{!f||P||A(f)},[f,P]),o.useEffect(()=>{if(!c||!d?.membership_types||S)return;const Z=d.membership_types.find(We=>We.id===c);Z&&(_(Z),w(!1),k("personal-info"))},[c,d?.membership_types,S]),o.useEffect(()=>{if(!Pe||!t||!j&&S&&Number(S.price)>0&&!Ze)return;const Z=!j&&S&&Number(S.price)===0,We=[];P&&P.price>0&&We.push({type:"product",id:P.id,name:P.name,unitPrice:P.price,quantity:1}),We.length>0&&Xj(t,We);let Ve=!1;return(async()=>{try{if(await ut(E.email,E.password,t),!Ve){let xt;Z?xt=s("/dashboard"):P&&P.price>0?xt=s("/cart"):y?xt=s(`/events/${y.id}`):j?xt=s(m||"/events"):xt=s("/dashboard"),Ke(xt,{replace:!0})}}catch{}})(),()=>{Ve=!0}},[Pe,j,Ze,t,E.email,E.password,ut,Ke,y,P,S]),o.useEffect(()=>{d&&D(Z=>{const We={};for(const Ve of d.custom_fields)!Ve.applicableMembershipTypeIds||Ve.applicableMembershipTypeIds.length===0?Z[Ve.key]!==void 0&&(We[Ve.key]=Z[Ve.key]):!j&&S&&Ve.applicableMembershipTypeIds.includes(S.id)&&Z[Ve.key]!==void 0&&(We[Ve.key]=Z[Ve.key]);return We})},[S,j,d]);const ht=j?null:S?.training_end_date_field??null,zt=ht==="residency_end_date"?"Residency end date":"Fellowship end date",Tt=!!d?.settings?.enable_check_payment,Jt=!j&&S?Number(S.price)>0:!1,is=Jt&&z!=="check",nt=(N?jP:n?bP:yP).filter(Z=>!(Z.key==="payment"&&!is)),Vt=nt.findIndex(Z=>Z.key===v),et=(Vt+1)/nt.length*100,bt=d?.society?.logo_url,qt=bt?`${ds}${bt}`:null,xs=d?.society?.primary_color||"#1a365d",ns=Nd(xs),ua=qd(qt);if(n&&!l&&!De&&!u&&t){const Z=i?p?.find(We=>We.id===i)??null:null;return e.jsx(fP,{slug:t,eventId:i??"",event:Z})}if(u)return e.jsx("div",{className:"signup-page-bg flex items-center justify-center px-4",children:e.jsxs("div",{className:"w-full max-w-2xl space-y-4",children:[e.jsx(Y,{className:"mx-auto h-16 w-48"}),e.jsx(Y,{className:"mx-auto h-6 w-64"}),e.jsx(Y,{className:"h-72 rounded-2xl"})]})});if(h||!d){const Z=h?.response?.status;return e.jsx("div",{className:"signup-page-bg flex items-center justify-center px-4",children:e.jsxs("div",{className:"signup-container max-w-md text-center",children:[qt&&e.jsx("img",{src:qt,alt:"Logo",className:"mx-auto mb-6 h-14 object-contain"}),e.jsx("div",{className:"mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-red-50",children:e.jsx(ad,{
3951className:"h-6 w-6 text-red-500"})}),e.jsx("h2",{className:"text-lg font-semibold text-slate-900",children:Z===404?"Society Not Found":"Something Went Wrong"}),e.jsx("p",{className:"mt-2 text-sm leading-relaxed text-slate-500",children:Z===404?"We couldn't find a society with that URL. Please double-check and try again.":"We were unable to load the signup page. Please try again later."})]})})}if(Pe){const Z=!j&&S&&Number(S.price)===0;return e.jsx("div",{className:"signup-page-bg flex items-center justify-center px-4",children:e.jsxs("div",{className:"signup-container max-w-md text-center",children:[qt&&e.jsx("img",{src:qt,alt:d.society.name,className:"mx-auto mb-6 h-14 object-contain"}),e.jsx("div",{className:"mx-auto mb-5 flex h-14 w-14 items-center justify-center rounded-full bg-emerald-50",children:e.jsx(Kt,{className:"h-7 w-7 text-emerald-500"})}),e.jsx("h2",{className:"text-xl font-semibold text-slate-900",children:j?"Account Created!":Ze?"Welcome!":ue?"Invoice Sent!":"Application Submitted"}),e.jsx("p",{className:"mt-3 text-sm leading-relaxed text-slate-500",children:j?P?"Your account has been created. Redirecting you to complete your purchase...":y?"Your account has been created. Redirecting you to complete your event registration...":"Your account has been created. Redirecting you to events...":Ze?P?"Your membership is now active. Redirecting you to complete your purchase...":y?"Your membership is now active. Redirecting you to complete your event registration...":"Your payment was successful and your membership is now active.":ue?"We've emailed you an invoice for your membership. Your membership will be activated once we receive your payment.":"Your membership application is under review. You'll receive an email once it has been approved."}),e.jsxs(je,{to:s("/login"),className:"mt-6 inline-flex items-center gap-1.5 text-sm font-medium transition-colors",style:{color:xs},children:["Go to login",e.jsx(as,{className:"h-3.5 w-3.5"})]})]})})}const aa=async()=>{if(!j&&!S||!t)return;se(""),oe(null),ye(null);const Z={};for(const[Ve,xt]of Object.entries(U)){const Ht=d.custom_fields.find(Zt=>Zt.key===Ve);Ht&&(!Ht.applicableMembershipTypeIds||Ht.applicableMembershipTypeIds.length===0||!j&&S&&Ht.applicableMembershipTypeIds.includes(S.id))&&(Z[Ve]=xt)}const We={email:E.email,password:E.password,first_name:E.first_name,last_name:E.last_name,organization:E.organization||null,phone:E.phone||null,address_line1:E.address_line1||null,city:E.city||null,state:E.state||null,postal_code:E.postal_code||null,country:E.country||void 0,membership_type_id:j?void 0:S.id,declared_role_type_id:j&&!S&&he?he:void 0,custom_fields:Object.keys(Z).length>0?Z:void 0,auto_renew:j||z==="check"?!1:K,payment_method:z==="check"?"check":void 0,fellowship_end_date:ht==="fellowship_end_date"&&E.fellowship_end_date||void 0,residency_end_date:ht==="residency_end_date"&&E.residency_end_date||void 0,promo_code:ve?.code||void 0,marketing_consent:X};try{const Ve=await b.mutateAsync({slug:t,data:We});if(Ve.is_non_member){M(!0);return}Ve.payment_method==="check"?(_e(!0),M(!0)):Ve.requires_payment&&Ve.client_secret&&Ve.publishable_key?(Ve.resume_token&&(fd(t,Ve.resume_token,{historyKey:be.key}),ge(Ve.resume_token)),Re({clientSecret:Ve.client_secret,publishableKey:Ve.publishable_key,amount:Ve.amount,memberName:Ve.member_name,membershipTypeName:Ve.membership_type_name,memberId:Ve.member_id}),k("payment")):M(!0)}catch(Ve){const xt=Ve?.response,Ht=xt?.status,Zt=xt?.data?.detail;if(Ht===429)se("Too many attempts. Please wait a moment and try again.");else if(Ht===409)Zt==="account_exists_pending_approval"?se("An account with this email already exists and is awaiting approval. You'll receive an email once it's approved â no need to sign up again."):Zt==="account_exists_payment_incomplete"?ye(E.email):Zt==="account_exists_payment_pending"?se(cx):Zt==="account_exists_contact_support"?se("An account with this email already exists. Please contact the society office for help with your account."):oe(E.email);else if(typeof Zt=="string")se(Zt);else if(Array.isArray(Zt)){const Cs=Zt.map(Ga=>{const Is=Ga.msg?.replace(/^Value error, /i,"").replace(/^value is not a valid /,"Invalid ")||"Invalid field",na=Ga.loc?.slice(-1)[0];return na?`${na.replace(/_/g," ")}: ${Is}`:Is});se(Cs.join(` 3952`))}else se("Signup failed. Please try again.")}},_s=(Z,We)=>{let Ve=We;Z==="phone"&&(Ve=Ou(We)),Z==="postal_code"&&(Ve=Bu(We)),Z==="email"&&(oe(null),ye(null)),Q(xt=>({...xt,[Z]:Ve}))},Ls=()=>v==="browse-events"?"Upcoming Events":v==="select-type"?N&&P?`Purchase ${P.name}`:n&&y?"Save on Events":`Join ${d.society.name}`:v==="personal-info"?"Create Your Account":v==="review"?"Review & Submit":"Complete Payment",pe=()=>v==="browse-events"?`Select an event from ${d.society.name} to get started.`:v==="select-type"?N&&P?"Optionally add a membership to save on future purchases, or continue without one.":n&&y?"Members get discounted event pricing. Choose a membership or continue without one.":d.society.description||"Select the membership that's right for you.":v==="personal-info"?P?`An account is required to purchase ${P.name}.`:y?`An account is required to register for ${y.name}.`:"Fill in your details below.":v==="review"?"Confirm everything looks correct.":"Enter your card details to activate your membership.";return e.jsxs("div",{className:"min-h-screen bg-background lg:grid lg:grid-cols-2",style:ns,children:[e.jsx("div",{className:"signup-page-bg px-4 py-6 sm:py-14",children:e.jsxs("div",{className:"mx-auto w-full max-w-2xl",children:[e.jsxs("div",{className:"animate-fade-slide-up mb-5 text-center sm:mb-8 lg:hidden",children:[qt&&ua!=="failed"?e.jsx("img",{src:qt,alt:
3952d.society.name,className:"mx-auto h-12 object-contain sm:h-20"}):e.jsx("div",{className:"mx-auto flex h-12 w-12 items-center justify-center rounded-xl text-xl font-semibold sm:h-14 sm:w-14 sm:text-2xl",style:{backgroundColor:"var(--portal-primary)",color:"var(--portal-primary-fg)"},children:d.society.name.charAt(0)}),d.society.website_url&&e.jsxs("a",{href:d.society.website_url,target:"_blank",rel:"noopener noreferrer",className:"mt-3 inline-flex items-center gap-1.5 text-sm text-slate-500 transition-colors hover:text-slate-700",children:[e.jsx(Rs,{className:"h-3.5 w-3.5"}),"Back to ",d.society.name," website"]})]}),e.jsxs("div",{className:"signup-container animate-fade-slide-up-delay-1",children:[e.jsxs("div",{className:"mb-5 sm:mb-7",children:[e.jsxs("div",{className:"mb-2 flex items-center justify-between",children:[e.jsxs("span",{className:"text-xs font-semibold text-slate-600",children:["Step ",Vt+1," of ",nt.length]}),e.jsx("span",{className:"text-xs font-medium text-slate-400",children:nt[Vt]?.label})]}),e.jsx("div",{className:"h-1.5 w-full overflow-hidden rounded-full bg-slate-100",children:e.jsx("div",{className:"h-full rounded-full transition-all duration-500 ease-out",style:{width:`${et}%`,backgroundColor:"var(--portal-primary)"}})})]}),e.jsx("h1",{className:"mb-1 text-lg font-semibold tracking-tight text-slate-900 sm:text-2xl",children:Ls()}),e.jsx("p",{className:"mb-5 text-[13px] text-slate-500 sm:mb-7",children:pe()}),ee&&e.jsx("div",{className:"mb-5 whitespace-pre-line rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700",children:ee}),mt&&e.jsx("div",{className:"mb-5",children:e.jsx(iy,{email:mt,loginPath:s("/login")})}),le&&t&&e.jsx("div",{className:"mb-5",children:e.jsx(ly,{email:le,societySlug:t,loginHref:s("/login")})}),v==="browse-events"&&e.jsx("div",{className:"animate-fade-slide-up-delay-2",children:x?e.jsxs("div",{className:"space-y-3",children:[e.jsx(Y,{className:"h-28 rounded-xl"}),e.jsx(Y,{className:"h-28 rounded-xl"}),e.jsx(Y,{className:"h-28 rounded-xl"})]}):!p||p.length===0?e.jsxs("div",{className:"py-10 text-center",children:[e.jsx(Yt,{className:"mx-auto mb-3 h-10 w-10 text-slate-300"}),e.jsx("p",{className:"text-sm font-medium text-slate-700",children:"No upcoming events"}),e.jsx("p",{className:"mt-1 text-xs text-slate-400",children:"Check back later for new events."}),e.jsxs(je,{to:s("/login"),className:"mt-4 inline-flex items-center gap-1.5 text-sm font-medium transition-colors",style:{color:xs},children:["Already a member? Sign in",e.jsx(as,{className:"h-3.5 w-3.5"})]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs(je,{to:s("/login?redirect=/events"),className:"flex items-center justify-between rounded-xl border-2 border-blue-100 bg-blue-50 px-4 py-3 transition-colors hover:border-blue-200",children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx(Lt,{className:"h-4 w-4 shrink-0 text-blue-600"}),e.jsx("span",{className:"text-sm font-medium text-blue-900",children:"Already a member? Sign in to purchase"})]}),e.jsx(as,{className:"h-4 w-4 shrink-0 text-blue-400"})]}),p.map(Z=>{const We=Z.spots_left!==null&&Z.spots_left<=0,Ve=Z.regular_price===0,xt=Z.member_price!=null?Z.regular_price-Z.member_price:0;return e.jsxs("button",{type:"button",disabled:We,onClick:()=>{C(Z),k("select-type")},className:`w-full rounded-xl border-2 px-4 py-4 text-left transition-colors ${We?"cursor-not-allowed border-slate-100 bg-slate-50 opacity-60":"border-slate-200 bg-white hover:border-slate-300 hover:shadow-sm"}`,children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-sm font-semibold text-slate-900",children:Z.name}),Z.start_date&&e.jsxs("div",{className:"mt-1.5 flex items-center gap-1.5",children:[e.jsx(Yt,{className:"h-3.5 w-3.5 shrink-0 text-slate-400"}),e.jsxs("span",{className:"text-xs text-slate-500",children:[tl(Z.start_date),Z.end_date&&Z.end_date!==Z.start_date&&` â ${tl(Z.end_date)}`]})]}),Z.location&&e.jsxs("div",{className:"mt-1 flex items-center gap-1.5",children:[e.jsx(Fa,{className:"h-3.5 w-3.5 shrink-0 text-slate-400"}),e.jsx("span",{className:"truncate text-xs text-slate-500",children:Z.location})]})]}),e.jsx("div",{className:"shrink-0 text-right",children:We?e.jsx("span",{className:"inline-block rounded-full bg-red-50 px-2.5 py-1 text-xs font-semibold text-red-600",children:"Sold Out"}):Ve?e.jsx("span",{className:"text-sm font-semibold tracking-tight text-slate-900",children:"Free"}):e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"text-sm font-semibold tracking-tight text-slate-900",children:["$",Z.regular_price.toFixed(2)]}),xt>0&&e.jsxs("div",{className:"mt-1 flex items-center justify-end gap-1",children:[e.jsx(xa,{
3952className:"h-3 w-3 text-emerald-600"}),e.jsxs("span",{className:"text-[11px] font-semibold text-emerald-600",children:["Members save $",xt.toFixed(2)]})]})]})})]}),Z.capacity!==null&&!We&&Z.spots_left!==null&&Z.spots_left<=10&&e.jsxs("p",{className:"mt-2 text-[11px] font-medium text-amber-600",children:["Only ",Z.spots_left," spot",Z.spots_left!==1?"s":""," left"]})]},Z.id)})]})}),v==="select-type"&&e.jsxs("div",{className:"animate-fade-slide-up-delay-2",children:[n&&y&&e.jsx("div",{className:"mb-5 rounded-xl border-2 border-slate-200 bg-slate-50 px-4 py-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wider text-slate-400",children:"Selected Event"}),e.jsx("p",{className:"mt-0.5 text-sm font-semibold text-slate-900",children:y.name}),y.start_date&&e.jsx("p",{className:"mt-0.5 text-xs text-slate-500",children:tl(y.start_date)})]}),e.jsxs("div",{className:"ml-3 shrink-0 text-right",children:[e.jsx("p",{className:"text-xs text-slate-400",children:"Non-member price"}),e.jsxs("p",{className:"text-sm font-semibold tracking-tight text-slate-900",children:["$",y.regular_price.toFixed(2)]})]})]})}),y?.offer_free_membership_enabled&&e.jsx("div",{className:"mb-5 rounded-xl border-2 border-emerald-200 bg-emerald-50 px-4 py-3.5",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(ci,{className:"mt-0.5 h-5 w-5 shrink-0 text-emerald-600"}),e.jsxs("div",{className:"min-w-0 text-sm",children:[e.jsx("p",{className:"font-semibold text-emerald-900",children:"This course includes 1 free year of membership"}),e.jsxs("p",{className:"mt-1 text-emerald-800",children:["New to ",d.society.name,"? Scroll down and pick"," ",e.jsx("strong",{children:'"Continue without membership"'})," â your free year is granted automatically after you register. Selecting a paid membership type below means you pay for it and forfeit the free year."]})]})]})}),N&&P&&e.jsx("div",{className:"mb-5 rounded-xl border-2 border-slate-200 bg-slate-50 px-4 py-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wider text-slate-400",children:"Selected Product"}),e.jsxs("div",{className:"mt-0.5 flex items-center gap-2",children:[e.jsx(Cr,{className:"h-4 w-4 shrink-0 text-slate-400"}),e.jsx("p",{className:"text-sm font-semibold text-slate-900",children:P.name})]}),P.description&&e.jsx("p",{className:"mt-0.5 line-clamp-2 text-xs text-slate-500",children:P.description})]}),e.jsxs("div",{className:"ml-3 shrink-0 text-right",children:[e.jsx("p",{className:"text-xs text-slate-400",children:"Price"}),e.jsx("p",{className:"text-sm font-semibold tracking-tight text-slate-900",children:P.price===0?"Free":`$${P.price.toFixed(2)}`})]})]})}),e.jsxs("div",{className:"space-y-2",children:[d.membership_types.map(Z=>{const We=S?.id===Z.id,Ve=Number(Z.price),xt=Ve===0,Ht=xt&&n,Zt=y?.member_price!=null&&y.regular_price>0?y.regular_price-y.member_price:0;return e.jsxs("button",{type:"button",onClick:()=>{_(Z),w(!1)},className:`type-card flex w-full items-center justify-between rounded-xl border-2 px-4 py-3 text-left ${We?"":"border-slate-200 bg-white hover:border-slate-300"}`,style:We?{borderColor:"var(--portal-primary)",backgroundColor:"var(--portal-primary-light)"}:void 0,children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[e.jsx("div",{className:`flex h-5 w-5 shrink-0 items-center justify-center rounded-full border-2 transition-colors ${We?"":"border-slate-300"}`,style:We?{borderColor:"var(--portal-primary)",backgroundColor:"var(--portal-primary)"}:void 0,children:We&&e.jsx(Xt,{className:"h-3 w-3 text-white"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("span",{className:"text-sm font-semibold text-slate-900",children:Z.name}),Z.description&&e.jsx("p",{className:"mt-0.5 hidden truncate text-xs text-slate-400 sm:block",children:Z.description}),Ht&&e.jsx("p",{className:"mt-0.5 text-xs font-medium text-amber-600",children:"Requires verification â member pricing not immediate"}),Number(Z.price)>0&&Z.auto_renew_enabled&&Z.auto_renew_discount_percent>0&&e.jsxs("p",{className:"mt-0.5 text-xs font-medium text-emerald-600",children:["Save ",Z.auto_renew_discount_percent,"% with auto-renew"]}),n&&!Ht&&Zt>0&&e.jsxs("p",{className:"mt-0.5 text-xs font-medium text-emerald-600",children:["Your event price: $",y.member_price.toFixed(2)," ",e.jsxs("span",{className:"text-emerald-500",children:["(save $",Zt.toFixed(2),"!)"]})]})]})]}),e.jsxs("span",{className:"ml-4 shrink-0 text-sm font-semibold tracking-tight text-slate-900 sm:text-base",children:[xt?"Free*":`$${Ve.toFixed(2)}`,Ve>0&&e.jsxs("span",{className:"text-xs font-normal text-slate-400",children:["/",Z.duration_type==="annual"?"yr":Z.duration_type]})]})]}
3952,Z.id)}),d.membership_types.some(Z=>Number(Z.price)===0)&&e.jsxs("p",{className:"px-1 text-[11px] text-amber-600",children:["* Free memberships require admin verification before activation.",n?" Member pricing will not apply until approved.":""]}),e.jsx("button",{type:"button",onClick:()=>{w(!0),_(null)},className:`type-card flex w-full items-center justify-between rounded-xl border-2 px-4 py-3 text-left ${j?"":"border-dashed border-slate-200 bg-white hover:border-slate-300"}`,style:j?{borderColor:"var(--portal-primary)",backgroundColor:"var(--portal-primary-light)"}:void 0,children:e.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[e.jsx("div",{className:`flex h-5 w-5 shrink-0 items-center justify-center rounded-full border-2 transition-colors ${j?"":"border-slate-300"}`,style:j?{borderColor:"var(--portal-primary)",backgroundColor:"var(--portal-primary)"}:void 0,children:j&&e.jsx(Xt,{className:"h-3 w-3 text-white"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"text-sm font-semibold text-slate-900",children:n?"Continue without membership":"Non-Member Event Access"}),y?.offer_free_membership_enabled&&e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full bg-emerald-100 px-2 py-0.5 text-[10px] font-semibold uppercase tracking-wide text-emerald-700",children:[e.jsx(ci,{className:"h-3 w-3"}),"Recommended â free year included"]}),!n&&e.jsx("span",{className:"inline-flex items-center rounded-full bg-brand-amber/15 px-2 py-0.5 text-[10px] font-semibold uppercase tracking-wide text-amber-700 dark:bg-brand-amber/20 dark:text-amber-300",children:"Public rate"})]}),e.jsx("p",{className:"mt-0.5 hidden text-xs text-slate-500 sm:block",children:"Register for individual events without membership"}),n&&y&&y.regular_price>0&&e.jsxs("p",{className:"mt-0.5 text-xs text-slate-400",children:["Event price: $",y.regular_price.toFixed(2)]}),!n&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"mt-1.5 hidden text-[11px] text-slate-400 sm:block",children:"Member discounts and benefits not included"}),e.jsx("p",{className:"mt-1 hidden text-[11px] font-medium sm:block",style:{color:"var(--portal-primary)"},children:"Upgrade to membership anytime for discounted event pricing"})]})]})]})})]}),j&&!S&&!n&&e.jsxs("div",{className:"mt-3 rounded-xl border border-slate-200 bg-slate-50 px-4 py-3",children:[e.jsxs("label",{htmlFor:"non-member-role-select",className:"mb-1.5 block text-[11px] font-semibold tracking-wide text-slate-500",children:["What's your professional role? ",e.jsx("span",{className:"text-red-400",children:"*"})]}),e.jsxs("div",{className:"relative",children:[e.jsxs("select",{id:"non-member-role-select",value:he,onChange:Z=>Xe(Z.target.value),required:!0,"aria-label":"Professional role","data-testid":"non-member-role-select",className:"h-10 w-full appearance-none rounded-lg border border-border bg-card px-3 pr-10 text-sm text-foreground focus:border-blue-400 focus:outline-none focus:ring-2 focus:ring-blue-500/20",children:[e.jsx("option",{value:"",children:"Select your role"}),(d.non_member_role_options??[]).map(Z=>e.jsx("option",{value:Z.id,children:Z.name},Z.id))]}),e.jsx("div",{className:"pointer-events-none absolute right-3 top-1/2 -translate-y-1/2",children:e.jsx("svg",{className:"h-4 w-4 text-slate-400",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M19 9l-7 7-7-7"})})})]}),e.jsx("p",{className:"mt-1 text-[10px] text-slate-400",children:"Pricing for events varies by professional role."})]}),S&&Number(S.price)>0&&S.auto_renew_enabled&&S.auto_renew_discount_percent>0&&(()=>{const Z=Number(S.price),We=S.auto_renew_discount_percent,Ve=Z*(1-We/100),xt=S.duration_type==="annual"?"yr":S.duration_type;return e.jsx("div",{className:"mt-4 rounded-xl border-2 border-slate-200 bg-white p-4",children:e.jsxs("label",{className:"flex cursor-pointer items-start gap-3",children:[e.jsx(ot,{checked:K,onCheckedChange:Ht=>xe(!!Ht),className:"mt-0.5"}),e.jsxs("div",{children:[e.jsx("span",{className:"text-sm font-semibold text-slate-900",children:"Enable auto-renew"}),K?e.jsxs("p",{className:"mt-1 text-sm text-slate-600",children:[e.jsxs("span",{className:"text-slate-400 line-through",children:["$",Z.toFixed(2)]})," ",e.jsxs("span",{className:"font-semibold text-emerald-600",children:["$",Ve.toFixed(2)]}),e.jsxs("span",{className:"text-slate-400",children:["/",xt]}),e.jsxs("span",{className:"ml-2 text-xs font-medium text-emerald-600",children:["â ",We,"% auto-renew discount"]})]}):e.jsxs("p",{className:"mt-1 text-xs text-slate-400",children:["You'll need to renew manually each"," ",xt==="yr"?"year":xt]})]})]})})})(),e.jsx("div",{className:"sticky bottom-0 -mx-6 mt-6 border-t border-slate-100 bg-white px-6 py-3 sm:static sm:mx-0 sm:border-0 sm:bg-transparent sm:px-0 sm:py-0",children:e.jsxs("div",{className:"flex items-center justify-between",children:[n&&!N&&e.jsxs(g,{variant:"ghost",onClick:()=>{C(null),k("browse-events")},className:"text-slate-400 hover:text-slate-600",children:[e.jsx(es,{className:"mr-1.5 h-4 w-4"}),"Back"]}),e.jsx("div",{className:n&&!N?"":"ml-auto",children:e.jsxs(g,{size:"lg",disabled:!S&&!j||j&&!S&&!n&&!he,onClick:()=>k("personal-info"),className:"signup-cta-btn",children:["Continue",e.jsx(as,{className:"ml-2 h-4 w-4"})]})})]})})]}),v==="personal-info"&&e.jsxs("div",{className:"animate-fade-slide-up-delay-2 space-y-4",children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsx(Us,{label:"First Name",required:!0,children:e.jsx(Na,{icon:kn,id:"first_name",autoComplete:"given-name",value:E.first_name,onChange:Z=>_s("first_name",Z.target.value),placeholder:"Jane",required:!0,valid:E.first_name.length>=2})}),e.jsx(Us,{label:"Last Name",required:!0,children:e.jsx(Na,{icon:kn,id:"last_name",autoComplete:"family-name",value:E.last_name,onChange:Z=>_s("last_name",Z.target.value),placeholder:"Smith",required:!0,valid:E.last_name.length>=2})})]}),e.jsx(Us,{label:"Email",required:!0,children:e.jsx(Na,{icon:$t,id:"email",type:"email",autoComplete:"email",value:E.email,onChange:Z=>_s("email",Z.target.value),placeholder:"[email protected]",required:!0,valid:/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(E.email)})}),e.jsxs(Us,{label:"Password",required:!0,hint:"8+ characters, uppercase, lowercase, and a number",children:[e.jsx(Na,{icon:Ys,id:"password",type:yt?"text":"password",value:E.password,onChange:Z=>_s("password",Z.target.value),placeholder:"Create a secure password",required:!0,minLength:8,valid:tc(E.password),trailing:e.jsx("button",{type:"button",onClick:()=>dt(Z=>!Z),"aria-label":yt?"Hide password":"Show password",className:"text-slate-400 transition-colors hover:text-slate-600",children:yt?e.jsx(Er,{className:"h-4 w-4"}):e.jsx(ca,{className:"h-4 w-4"})})}),E.password.length>0&&e.jsxs("div",{className:"mt-2",children:[e.jsx("div",{className:"strength-meter",children:[1,2,3,4].map(Z=>e.jsx("div",{className:`bar ${rt.score>=Z?wP[rt.score]:""}`},Z))}),e.jsx("p",{className:`mt-1 text-[11px] font-medium ${NP[rt.score]||"text-slate-400"}`,children:rt.label}),!tc(E.password)&&e.jsx("ul",{className:"mt-2 space-y-0.5",children:[{met:E.password.length>=8,label:"At least 8 characters"},{met:/[A-Z]/.test(E.password),label:"One uppercase letter"},{met:/[a-z]/.test(E.password),label:"One lowercase letter"},{met:/\d/.test(E.password),label:"One number"}].map(Z=>e.jsxs("li",{className:`flex items-center gap-1.5 text-[11px] ${Z.met?"text-emerald-600":"text-slate-500"}`,children:[Z.met?e.jsx(Xt,{className:"h-3 w-3 shrink-0"}):e.jsx(ms,{className:"h-3 w-3 shrink-0 text-slate-300"}),Z.label]},Z.label))})]})]}),e.jsx(Us,{label:"Phone",hint:"US: (555) 123-4567 â or include + and country code",children:e.jsx(Na,{icon:Jc,id:"phone",type:"tel",autoComplete:"tel",value:E.phone,onChange:Z=>_s("phone",Z.target.value),placeholder:"(555) 123-4567",valid:Uu(E.phone)})}),e.jsx(Us,{label:"Organization",children:e.jsx(Na,{icon:ga,id:"organization",autoComplete:"organization",value:E.organization,onChange:Z=>_s("organization",Z.target.value),placeholder:"Practice, institution, or employer"})}),e.jsx(Us,{label:"Address",children:e.jsx(Na,{icon:Fa,id:"address_line1",autoComplete:"address-line1",value:E.address_line1,onChange:Z=>_s("address_line1",Z.target.value),placeholder:"123 Main Street"})}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-3",children:[e.jsx(Us,{label:"City",children:e.jsx(Na,{icon:ga,id:"city",autoComplete:"address-level2",value:E.city,onChange:Z=>_s("city",Z.target.value),placeholder:"Miami"})}),e.jsx(Us,{label:"State",children:e.jsxs("select",{id:"state",autoComplete:"address-level1",value:E.state,onChange:Z=>_s("state",Z.target.value),className:`${cy} appearance-none bg-[url('data:image/svg+xml;charset=utf-8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%2216%22%20height%3D%2216%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22%2394a3b8%22%20stroke-width%3D%222%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%3Cpath%20d%3D%22m6%209%206%206%206-6%22/%3E%3C/svg%3E')] bg-[position:right_12px_center] bg-no-repeat pr-9`,children:[e.jsx("option",{value:"",children:"--"}),ny.map(Z=>e.jsx("option",{value:Z.code,children:Z.name},Z.code))]})}),e.jsx(Us,{label:"Zip Code",children:e.jsx(Na,{icon:ej,id:"postal_code",autoComplete:"postal-code",inputMode:"numeric",value:E.postal_code,onChange:Z=>_s("postal_code",Z.target.value),placeholder:"33101",valid:zu(E.postal_code)})})]}),e.jsx(Us,{label:"Country",hint:"2-letter code (e.g. US, CA, GB)",children:e.jsx(Na,{icon:bl,id:"country",autoComplete:"country",maxLength:2,value:E.country,onChange:Z=>_s("country",Z.target.value.toUpperCase()),placeholder:"US",valid:E.country.length===2})}),ht&&e.jsx(Us,{label:zt,htmlFor:ht,required:!0,children:e.jsx(Na,{icon:Yt,id:ht,type:"date",value:E[ht],onChange:Z=>_s(ht,Z.target.value),required:!0})}),(()=>{const Z=d.custom_fields.filter(We=>!We.applicableMembershipTypeIds||We.applicableMembershipTypeIds.length===0?!0:j||!S?!1:We.applicableMembershipTypeIds.includes(S.id));return Z.length===0?null:e.jsxs("div",{className:"space-y-4 border-t border-slate-100 pt-5",children:[e.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-wider text-slate-400",children:"Additional Information"}),Z.map(We=>e.jsx(kP,{field:We,value:U[We.key],onChange:Ve=>D(xt=>({...xt,[We.key]:Ve}))},We.key))]})})(),e.jsx("div",{className:"sticky bottom-0 -mx-6 border-t border-slate-100 bg-white px-6 py-3 sm:static sm:mx-0 sm:border-0 sm:bg-transparent sm:px-0 sm:py-0",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(g,{variant:"ghost",onClick:()=>k("select-type"),className:"text-slate-400 hover:text-slate-600",children:[e.jsx(es,{className:"mr-1.5 h-4 w-4"}),"Back"]}),e.jsxs(g,{size:"lg",onClick:()=>k("review"),disabled:!E.first_name||!E.last_name||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(E.email)||!tc(E.password)||E.phone!==""&&!Uu(E.phone)||E.postal_code!==""&&!zu(E.postal_code)||!!ht&&!E[ht],className:"signup-cta-btn",children:["Review",e.jsx(as,{className:"ml-2 h-4 w-4"})]})]})})]}),v==="review"&&(j||S)&&e.jsxs("div",{className:"animate-fade-slide-up-delay-2 space-y-5",children:[y&&e.jsxs(Rn,{title:"Event Registration",children:[e.jsx(ra,{label:"Event",value:y.name}),y.start_date&&e.jsx(ra,{label:"Date",value:tl(y.start_date)}),(()=>{if(y.regular_price===0)return e.jsx(ra,{label:"Price",value:"Free â register after account creation"});const Ve=!j&&S&&y.member_price!=null?y.member_price:y.regular_price;return e.jsx(ra,{label:"Event Price",value:`$${Ve.toFixed(2)}`})})()]}),P&&e.jsxs(Rn,{title:"Product",children:[e.jsx(ra,{label:"Product",value:P.name}),e.jsx(ra,{label:"Price",value:P.price===0?"Free":`$${P.price.toFixed(2)}`})]}),e.jsx(Rn,{title:j?"Account Type":"Membership",children:j?e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm font-medium text-slate-900",children:"Event Registration Only"}),e.jsx("span",{className:"text-sm font-semibold text-slate-900",children:"Free"})]}):S&&(()=>
3952{const Z=Number(S.price),We=z==="check"?!1:K,Ve=Z>0&&We&&S.auto_renew_enabled&&S.auto_renew_discount_percent>0,xt=S.auto_renew_discount_percent,Ht=Ve?Z*(1-xt/100):Z,Zt=Z-Ht,Cs=S.duration_type==="annual"?"year":S.duration_type;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm font-medium text-slate-900",children:S.name}),e.jsxs("span",{className:"text-sm font-semibold text-slate-900",children:[Z===0?"Free":`$${Ht.toFixed(2)}`,Z>0&&e.jsxs("span",{className:"font-normal text-slate-400",children:[" / ",Cs]})]})]}),Ve&&e.jsxs("p",{className:"text-xs font-medium text-emerald-600",children:["Includes ",xt,"% auto-renew discount (save $",Zt.toFixed(2),")"]}),Z>0&&z!=="check"&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-xs text-slate-400",children:"Auto-renew"}),e.jsx("span",{className:"text-xs font-medium text-slate-600",children:K?"On":"Off"})]})]})})()}),y&&!j&&S&&Number(S.price)===0&&e.jsx("div",{className:"rounded-lg border border-amber-200 bg-amber-50 px-4 py-3",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Lt,{className:"mt-0.5 h-4 w-4 shrink-0 text-amber-600"}),e.jsx("p",{className:"text-sm text-amber-800",children:"This membership requires admin approval. You can register for events once your membership is approved."})]})}),Jt&&Tt&&e.jsx(Rn,{title:"Payment Method",children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("button",{type:"button",onClick:()=>ae("card"),className:`flex w-full items-center gap-3 rounded-lg border-2 px-4 py-3 text-left transition-colors ${z==="card"?"border-blue-500 bg-blue-50":"border-slate-200 bg-white hover:border-slate-300"}`,children:[e.jsx("div",{className:`flex h-5 w-5 shrink-0 items-center justify-center rounded-full border-2 transition-colors ${z==="card"?"border-blue-500 bg-blue-500":"border-slate-300"}`,children:z==="card"&&e.jsx(Xt,{className:"h-3 w-3 text-white"})}),e.jsx(Qt,{className:`h-4 w-4 ${z==="card"?"text-blue-600":"text-slate-400"}`}),e.jsx("span",{className:"text-sm font-medium text-slate-900",children:"Pay with Card"})]}),e.jsxs("button",{type:"button",onClick:()=>ae("check"),className:`flex w-full items-center gap-3 rounded-lg border-2 px-4 py-3 text-left transition-colors ${z==="check"?"border-blue-500 bg-blue-50":"border-slate-200 bg-white hover:border-slate-300"}`,children:[e.jsx("div",{className:`flex h-5 w-5 shrink-0 items-center justify-center rounded-full border-2 transition-colors ${z==="check"?"border-blue-500 bg-blue-500":"border-slate-300"}`,children:z==="check"&&e.jsx(Xt,{className:"h-3 w-3 text-white"})}),e.jsx(cs,{className:`h-4 w-4 ${z==="check"?"text-blue-600":"text-slate-400"}`}),e.jsx("span",{className:"text-sm font-medium text-slate-900",children:"Pay by Check / Invoice Me"})]}),z==="check"&&e.jsx("div",{className:"mt-2 rounded-lg border border-amber-200 bg-amber-50 px-4 py-3",children:e.jsx("p",{className:"text-sm text-amber-800",children:"We'll email you an invoice. Your membership will be activated once payment is received."})})]})}),Jt&&z!=="check"&&e.jsx(Rn,{title:"Promo Code",children:ve?e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xa,{className:"h-4 w-4 text-emerald-600"}),e.jsx("span",{className:"font-mono text-sm font-semibold text-emerald-700",children:ve.code}),e.jsxs("span",{className:"text-sm text-emerald-600",children:["â ",ve.message]})]}),e.jsx("button",{type:"button",onClick:()=>{Ne(null),ke("")},className:"text-slate-400 hover:text-slate-600",children:e.jsx(ms,{className:"h-4 w-4"})})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(O,{value:ce,onChange:Z=>ke(Z.target.value.toUpperCase()),placeholder:"Enter promo code",className:"font-mono uppercase text-slate-900",onKeyDown:Z=>{if(Z.key==="Enter"){if(Z.preventDefault(),!ce.trim()||Ce)return;ze(!0),Oe(""),gt.validateSignupPromoCode(t,ce.trim()).then(We=>{We.valid?(Ne({code:We.code||"",discount_type:We.discount_type||"",discount_value:We.discount_value??0,message:We.message||""}),Oe("")):Oe(We.message||"Invalid code")}).catch(()=>Oe("Failed to validate code")).finally(()=>ze(!1))}}}),e.jsx(g,{type:"button",variant:"outline",disabled:Ce||!ce.trim(),onClick:()=>{ce.trim()&&(ze(!0),Oe(""),gt.validateSignupPromoCode(t,ce.trim()).then(
3952Z=>{Z.valid?(Ne({code:Z.code||"",discount_type:Z.discount_type||"",discount_value:Z.discount_value??0,message:Z.message||""}),Oe("")):Oe(Z.message||"Invalid code")}).catch(()=>Oe("Failed to validate code")).finally(()=>ze(!1)))},className:"shrink-0",children:Ce?"Checking...":"Apply"})]}),Qe&&e.jsx("p",{className:"text-sm text-red-600",children:Qe})]})}),e.jsxs(Rn,{title:"Personal Information",children:[e.jsx(ra,{label:"Name",value:`${E.first_name} ${E.last_name}`}),e.jsx(ra,{label:"Email",value:E.email}),E.organization&&e.jsx(ra,{label:"Organization",value:E.organization}),E.phone&&e.jsx(ra,{label:"Phone",value:E.phone}),E.address_line1&&e.jsx(ra,{label:"Address",value:[E.address_line1,E.city,E.state,E.postal_code,E.country].filter(Boolean).join(", ")}),ht&&E[ht]&&e.jsx(ra,{label:zt,value:E[ht]})]}),(()=>{const Z=Object.entries(U).filter(([We])=>{const Ve=d.custom_fields.find(xt=>xt.key===We);return Ve?!Ve.applicableMembershipTypeIds||Ve.applicableMembershipTypeIds.length===0?!0:j||!S?!1:Ve.applicableMembershipTypeIds.includes(S.id):!1});return Z.length===0?null:e.jsx(Rn,{title:"Additional Information",children:Z.map(([We,Ve])=>{const xt=d.custom_fields.find(Ht=>Ht.key===We);return e.jsx(ra,{label:xt?.label??We,value:Array.isArray(Ve)?Ve.join(", "):String(Ve)},We)})})})(),e.jsxs("div",{className:"space-y-3 rounded-lg border border-slate-200 bg-slate-50 p-4",children:[e.jsxs("label",{className:"flex cursor-pointer items-start gap-3",children:[e.jsx("input",{type:"checkbox",checked:I,onChange:Z=>R(Z.target.checked),className:"mt-0.5 h-4 w-4 rounded border-slate-300 text-blue-600 focus:ring-blue-500"}),e.jsxs("span",{className:"text-sm text-slate-700",children:["I agree to the"," ",e.jsx(je,{to:s("/terms"),target:"_blank",className:"font-medium text-blue-600 underline hover:text-blue-700",onClick:Z=>Z.stopPropagation(),children:"Terms of Service"})," ","and"," ",e.jsx(je,{to:s("/privacy"),target:"_blank",className:"font-medium text-blue-600 underline hover:text-blue-700",onClick:Z=>Z.stopPropagation(),children:"Privacy Policy"})," ",e.jsx("span",{className:"text-red-500",children:"*"})]})]}),e.jsxs("label",{className:"flex cursor-pointer items-start gap-3",children:[e.jsx("input",{type:"checkbox",checked:X,onChange:Z=>Se(Z.target.checked),className:"mt-0.5 h-4 w-4 rounded border-slate-300 text-blue-600 focus:ring-blue-500"}),e.jsx("span",{className:"text-sm text-slate-600",children:"I'd like to receive email updates and announcements"})]})]}),Ze&&e.jsx("p",{className:"rounded-lg border border-slate-200 bg-slate-50 px-4 py-3 text-sm text-slate-600",children:"Your account has been created. To change your plan or details, please contact the society office."}),e.jsx("div",{className:"sticky bottom-0 -mx-6 border-t border-slate-100 bg-white px-6 py-3 sm:static sm:mx-0 sm:border-0 sm:bg-transparent sm:px-0 sm:py-0",children:e.jsxs("div",{className:`flex items-center ${Ze?"justify-end":"justify-between"}`,children:[!Ze&&e.jsxs(g,{variant:"ghost",onClick:()=>k("personal-info"),className:"text-slate-400 hover:text-slate-600",children:[e.jsx(es,{className:"mr-1.5 h-4 w-4"}),"Back"]}),e.jsx(g,{size:"lg",onClick:Ze?()=>k("payment"):aa,disabled:b.isPending||!I,className:"signup-cta-btn w-full sm:w-auto",children:Ze?"Continue to payment":b.isPending?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"mr-2 inline-block h-4 w-4 animate-spin rounded-full border-2 border-white/30 border-t-white"}),"Submitting..."]}):j?"Create Account":"Sign Up"})]})})]}),v==="payment"&&Ze&&t&&e.jsx("div",{className:"animate-fade-slide-up-delay-2",children:e.jsx(oy,{slug:t,resumeToken:de,initialPayment:Ze,primaryColor:xs,contactEmail:d.society.contact_email,loginHref:s("/login"),onActivated:()=>M(!0),onBack:()=>k("review")})})]}),e.jsxs("div",{className:"animate-fade-slide-up-delay-3 mt-6 space-y-3 sm:mt-8",children:[e.jsxs("p",{className:"text-center text-[13px] text-slate-400",children:["Already have an account?"," ",e.jsx(je,{to:s("/login"),className:"font-semibold transition-colors",style:{color:"var(--portal-primary)"},children:"Sign in"})]}),e.jsxs("div",{className:"flex items-center justify-center gap-4 text-slate-300",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(tj,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"text-[11px]",children:"SSL Encrypted"})]}),e.jsx("div",{className:"h-3 w-px bg-slate-200"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Ys,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"text-[11px]",children:"Secure Signup"})]})]})]})]})}),e.jsx(Id,{societyName:d.society.name,logoUrl:qt,logoShape:ua,websiteUrl:d.society.website_url,eyebrow:"Join the society",tagline:"A few quick steps to set up your membership. You can save your card and renew automatically, with no spreadsheets and no friction.",className:"lg:sticky lg:top-0 lg:h-screen"})]})}function Us({label:t,htmlFor:s,required:a,hint:n,children:r}){return e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(T,{htmlFor:s,className:"block text-[11px] font-semibold tracking-wide text-slate-500",children:[t,a&&e.jsx("span",{className:"ml-0.5 text-red-400",children:"*"})]}),r,n&&e.jsx("p",{className:"text-[10px] text-slate-400",children:n})]})}function Na({icon:t,valid:s,trailing:a,...n}){return e.jsxs("div",{className:"premium-input-wrapper",children:[e.jsx(t,{className:"input-icon"}),e.jsx(O,{...n,className:a?`${Iu} pr-16`:Iu}),a&&e.jsx("div",{className:"pointer-events-none absolute right-0 top-0 flex h-full items-center pr-3",children:e.jsx("div",{className:"pointer-events-auto",children:a})}),s&&e.jsx(Kt,{className:"input-check",style:a?{right:"2.5rem"}:void 0})]})}function Rn({title:t,children:s}){return e.jsxs("div",{className:"space-y-2",children:[e.jsx("h3",{className:"text-[11px] font-semibold uppercase tracking-wider text-slate-400",children:t}),e.jsx("div",{className:"space-y-2 rounded-lg bg-slate-50 p-4",children:s})]})}function ra({label:t,value:s}){return e.jsxs("div",{className:"flex items-start justify-between gap-4 text-sm",children:[e.jsx("span",{className:"shrink-0 text-slate-400",children:t}),e.jsx("span",{className:"text-right font-medium text-slate-900",children:s})]})}function kP({field:t,value:s,onChange:a}){const n=`cf-${t.key}`;switch(t.type){case"checkbox":return e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(ot,{id:n,checked:!!s,onCheckedChange:r=>a(r),className:"mt-0.5"}),e.jsxs("div",{children:[e.jsxs(T,{htmlFor:n,className:"text-xs font-semibold text-slate-600",children:[t.label,t.required&&e.jsx("span",{className:"ml-0.5 text-red-400",children:"*"})]}),t.helpText&&e.jsx("p",{className:"mt-0.5 text-[11px] text-slate-400",children:t.helpText})]})]});case"dropdown":return e.jsx(Us,{label:t.label,required:t.required,hint:t.helpText||void 0,children:e.jsxs("select",{id:n,className:"flex h-11 w-full rounded-lg border border-slate-200 bg-white px-4 py-2.5 text-sm text-slate-800 transition-colors focus:border-blue-400 focus:outline-none focus:ring-2 focus:ring-blue-500/20",value:String(s??""),onChange:r=>
3952a(r.target.value),required:t.required,children:[e.jsx("option",{value:"",children:t.placeholder||"Select..."}),t.options?.map(r=>e.jsx("option",{value:r,children:r},r))]})});case"textarea":return e.jsx(Us,{label:t.label,required:t.required,hint:t.helpText||void 0,children:e.jsx("textarea",{id:n,className:"flex min-h-[100px] w-full rounded-lg border border-slate-200 bg-white px-4 py-3 text-sm text-slate-800 transition-colors placeholder:text-slate-400 focus:border-blue-400 focus:outline-none focus:ring-2 focus:ring-blue-500/20",value:String(s??""),onChange:r=>a(r.target.value),placeholder:t.placeholder||void 0,required:t.required})});case"multi_select":{const r=Array.isArray(s)?s:[];return e.jsx(Us,{label:t.label,required:t.required,hint:t.helpText||void 0,children:e.jsx("div",{className:"space-y-2",children:t.options?.map(i=>e.jsxs("label",{className:"flex items-center gap-2 text-sm text-slate-600",children:[e.jsx(ot,{checked:r.includes(i),onCheckedChange:l=>a(l?[...r,i]:r.filter(m=>m!==i))}),i]},i))})})}default:return e.jsx(Us,{label:t.label,required:t.required,hint:t.helpText||void 0,children:e.jsx(O,{id:n,type:t.type==="email"?"email":t.type==="number"?"number":t.type==="date"?"date":t.type==="phone"?"tel":t.type==="url"?"url":"text",value:String(s??""),onChange:r=>a(r.target.value),placeholder:t.placeholder||void 0,required:t.required,className:cy})})}}function Oa({children:t}){const s=qs(),{data:a,isLoading:n}=ma(s||void 0),r=Nd(a?.society?.primary_color);Ra(a?.society?.favicon_url);const i=a?.society?.name||s?.toUpperCase()||"Member Portal",l=a?.society?.website_url,m=a?.society?.logo_url,c=m?`${ds}${m}`:null,d=qd(c);return e.jsxs("div",{className:"portal-auth min-h-screen bg-background lg:grid lg:grid-cols-[minmax(480px,560px)_minmax(0,1fr)]",style:r,children:[e.jsxs("div",{className:"flex min-h-screen flex-col justify-between gap-10 px-5 pb-7 pt-8 lg:px-[clamp(24px,5.5vw,80px)] lg:pb-9 lg:pt-11",children:[e.jsx(Hf,{societyName:i,logoUrl:c,logoShape:d,loading:n||!s,adaptive:!0}),e.jsx("div",{className:"pl-rise mx-auto w-full max-w-[400px] [animation-delay:140ms] lg:mx-0",children:t}),e.jsxs("div",{className:"pl-fade flex items-center gap-2 text-xs text-muted-foreground [animation-delay:700ms]",children:[e.jsx("span",{children:"Powered by"}),e.jsx("img",{src:pn,alt:"Korevera",className:"h-3.5 w-auto object-contain dark:invert"})]})]}),e.jsx(Id,{societyName:i,logoUrl:c,logoShape:d,loading:n||!s,websiteUrl:l})]})}function Qu(){const t=qs(),s=us(),a=ta(),{isResolving:n,isCustomDomain:r}=da(),{data:i}=ma(t||void 0),l=a.state,[m]=o.useState(()=>hx(a.search)||l?.settle===!0),[c]=o.useState(()=>l?.pass??(l?.resumeToken?{resumeToken:l.resumeToken,expiresAt:0}
3952:null)),d=c?.resumeToken??null,[u]=o.useState(a.key),[h]=o.useState(a.search);o.useEffect(()=>{const b=Ij(a.search);if(b!==a.search||l){const N=window.history.state??{};window.history.replaceState({...N,usr:null},"",a.pathname+b+a.hash)}},[]);const p=o.useMemo(()=>t&&!d?mx(t,{locationKey:u,stripeReturnPaymentIntent:ux(h)}):null,[t,d,u,h]),x=p?.resumeToken??null,f=d??x;return o.useEffect(()=>{t&&f&&fd(t,f,{historyKey:u,paymentIntentId:(p??c)?.paymentIntentId,expiresAt:(p??c)?.expiresAt||void 0})},[t,f,u,p,c]),r&&n||!t?e.jsx(Oa,{children:e.jsx(Y,{className:"h-48 rounded-xl"})}):e.jsxs(Oa,{children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight text-foreground",children:"Complete your payment"}),e.jsx("p",{className:"mb-6 mt-2 text-sm text-muted-foreground",children:"Finish paying your membership dues to activate your membership."}),e.jsx(oy,{slug:t,resumeToken:f,startSettling:m,primaryColor:i?.society?.primary_color||"#1a365d",contactEmail:i?.society?.contact_email,loginHref:s("/login")})]})}function _P({open:t,onOpenChange:s,intentData:a,invoiceId:n}){const{stripePromise:r,elementsKey:i}=Ei(t,a?.publishable_key??null);return e.jsx(Fe,{open:t,onOpenChange:s,children:e.jsxs(Te,{className:"max-h-[90vh] w-[95vw] overflow-y-auto sm:max-w-[480px]",children:[e.jsxs(Ae,{children:[e.jsx(Ee,{children:"Pay invoice"}),e.jsx(tt,{children:a&&e.jsxs(e.Fragment,{children:[a.invoice_number," â $",a.amount.toFixed(2),a.description&&e.jsxs(e.Fragment,{children:[" (",a.description,")"]})]})})]}),a&&r&&n&&e.jsx(dn,{stripe:r,options:{clientSecret:a.client_secret,appearance:{theme:"stripe",variables:{colorPrimary:"#0f172a"}}},children:e.jsx(SP,{invoiceId:n,onSuccess:()=>s(!1)})},i)]})})}function SP({invoiceId:t,onSuccess:s}){const a=mn(),n=un(),r=Xw(),[i,l]=o.useState(!1),[m,c]=o.useState(null),[d,u]=o.useState(!1),[h,p]=o.useState(!1),x=async f=>{if(f.preventDefault(),!a||!n||!h)return;l(!0),c(null);const b=await a.confirmPayment({elements:n,confirmParams:{return_url:window.location.href},redirect:"if_required"});if(b.error)c(b.error.message||"Payment failed"),l(!1);else if(b.paymentIntent?.status==="succeeded"){try{await r.mutateAsync({invoiceId:t,paymentIntentId:b.paymentIntent.id}),u(!0)}catch(N){c(N?.response?.data?.detail||"Payment succeeded but confirmation failed. Please contact support.")}l(!1)}};return d?e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsx("div",{className:"rounded-md border border-emerald-200 bg-emerald-50 px-4 py-3 text-center dark:border-emerald-900/60 dark:bg-emerald-950/30",children:e.jsx("p",{className:"text-sm font-semibold text-emerald-800 dark:text-emerald-300",children:"Invoice paid successfully"})}),e.jsx(g,{className:"w-full font-medium",onClick:s,children:"Done"})]}):e.jsxs("form",{onSubmit:x,className:"space-y-4",children:[e.jsx(hn,{onReady:()=>p(!0)}),m&&e.jsx("div",{className:"rounded-md border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-800 dark:border-red-900/60 dark:bg-red-950/30 dark:text-red-300",children:m}),e.jsx(g,{type:"submit",className:"w-full bg-blue-600 font-medium text-white hover:bg-blue-700",disabled:!a||!h||i,children:i?"Processingâ¦":"Pay now"})]})}function CP(){const[t,s]=o.useState(1),[a,n]=o.useState(1),{data:r,isLoading:i}=Nc(t,10,"sent"),{data:l,isLoading:m}=Nc(a,10,"paid"),c=Zw(),[d,u]=o.useState(!1),[h,p]=o.useState(null),[x,f]=o.useState(null),b=async k=>{try{const S=await c.mutateAsync(k);p(S),f(k),u(!0)}catch{}},N=async(k,S)=>{try{const _=await Me.get(`/portal/invoices/${k}/pdf`,{responseType:"blob"}),y=window.URL.createObjectURL(_.data),C=document.createElement("a");C.href=y,C.download=`${S}.pdf`,C.click(),window.URL.revokeObjectURL(y)}catch{}},j=r?.items||[],w=l?.items||[];return i&&m?e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg",style:{backgroundColor:"var(--portal-primary-light)",color:"var(--portal-primary)"},children:e.jsx(cs,{className:"h-5 w-5"})}),e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:"Invoices & receipts"})]}),e.jsx(L,{className:"min-w-0 overflow-hidden",children:e.jsx($,{className:"p-6",children:e.jsx("div",{className:"space-y-3",children:Array.from({length:3}).map((k,S)=>e.jsx(Y,{className:"h-16 w-full"},S))})})})]}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg",style:{backgroundColor:"var(--portal-primary-light)",color:"var(--portal-primary)"},children:e.jsx(cs,{className:"h-5 w-5"})}),e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:"Invoices & receipts"})]}),e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-amber-100 text-amber-600 dar
3952k:bg-amber-900/30 dark:text-amber-400",children:e.jsx(cs,{className:"h-4 w-4"})}),"Open invoices"]})}),e.jsx($,{className:"p-0",children:i?e.jsx("div",{className:"space-y-3 p-6",children:Array.from({length:2}).map((k,S)=>e.jsx(Y,{className:"h-16 w-full"},S))}):j.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-10 text-muted-foreground",children:[e.jsx(cs,{className:"mb-2 h-8 w-8 text-muted-foreground"}),e.jsx("p",{className:"text-sm",children:"No open invoices."})]}):e.jsx("div",{className:"divide-y",children:j.map(k=>e.jsxs("div",{className:"flex flex-col gap-3 p-4 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"min-w-0 space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-mono text-sm font-semibold text-foreground",children:k.invoice_number}),e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-amber-500","aria-hidden":"true"}),e.jsx("span",{className:"text-xs font-medium text-foreground/85",children:"Due"})]})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:k.description}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Issued ",Be(pt(k.issue_date),"MMM d, yyyy")," · Due"," ",Be(pt(k.due_date),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-3",children:[e.jsxs("span",{className:"text-sm font-semibold text-foreground",children:["$",Number(k.amount).toFixed(2)]}),e.jsxs(g,{size:"default",className:"min-h-[44px] bg-blue-600 font-medium text-white hover:bg-blue-700",onClick:()=>b(k.id),disabled:c.isPending,children:[e.jsx(Qt,{className:"mr-1.5 h-4 w-4"}),"Pay now"]}),k.pdf_path&&e.jsxs(g,{variant:"outline",size:"default",className:"min-h-[44px] min-w-[44px]",onClick:()=>N(k.id,k.invoice_number),children:[e.jsx(vs,{className:"mr-1.5 h-4 w-4"}),"PDF"]})]})]},k.id))})})]}),r&&r.total>r.size&&e.jsxs("div",{className:"flex justify-center gap-2",children:[e.jsx(g,{variant:"outline",size:"default",className:"min-h-[44px]",disabled:t<=1,onClick:()=>s(t-1),children:"Previous"}),e.jsx(g,{variant:"outline",size:"default",className:"min-h-[44px]",disabled:t*r.size>=r.total,onClick:()=>s(t+1),children:"Next"})]}),e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-emerald-100 text-emerald-600 dark:bg-emerald-900/30 dark:text-emerald-400",children:e.jsx(ii,{className:"h-4 w-4"})}),"Receipts"]})}),e.jsx($,{className:"p-0",children:m?e.jsx("div",{className:"space-y-3 p-6",children:Array.from({length:2}).map((k,S)=>e.jsx(Y,{className:"h-16 w-full"},S))}):w.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-10 text-muted-foreground",children:[e.jsx(ii,{className:"mb-2 h-8 w-8 text-muted-foreground/60"}),e.jsx("p",{className:"text-sm",children:"No receipts yet."})]}):e.jsx("div",{className:"divide-y",children:w.map(k=>e.jsxs("div",{className:"flex flex-col gap-3 p-4 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"min-w-0 space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-mono text-sm font-semibold text-foreground",children:k.invoice_number}),e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-emerald-500","aria-hidden":"true"}),e.jsx("span",{className:"text-xs font-medium text-foreground/85",children:"Paid"})]})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:k.description}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Paid"," ",k.paid_at?Be(pt(k.paid_at),"MMM d, yyyy"):Be(pt(k.issue_date),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-3",children:[e.jsxs("span",{className:"text-sm font-semibold text-foreground",children:["$",Number(k.amount).toFixed(2)]}),k.pdf_path&&e.jsxs(g,{variant:"outline",size:"default",className:"min-h-[44px] min-w-[44px]",onClick:()=>N(k.id,k.invoice_number),children:[e.jsx(vs,{className:"mr-1.5 h-4 w-4"}),"PDF"]})]})]},k.id))})})]}),l&&l.total>l.size&&e.jsxs("div",{className:"flex justify-center gap-2",children:[e.jsx(g,{variant:"outline",size:"default",className:"min-h-[44px]",disabled:a<=1,onClick:()=>n(a-1),children:"Previous"}),e.jsx(g,{variant:"outline",size:"default",className:"min-h-[44px]",disabled:a*l.size>=l.total,onClick:()=>n(a+1),children:"Next"})]}),e.jsx(_P,{open:d,onOpenChange:u,intentData:h,invoiceId:x})]})}
3952function mr(t){return t.toLocaleString("en-US",{style:"currency",currency:"USD"})}function Wu(){return e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg",style:{backgroundColor:"var(--portal-primary-light)",color:"var(--portal-primary)"},children:e.jsx(Yt,{className:"h-5 w-5"})}),e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:"Events"})]})}function Vu(){return e.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1.5 rounded-full bg-emerald-100 px-2 py-0.5 text-[11px] font-medium text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400",children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-emerald-500","aria-hidden":"true"}),"Registered"]})}function PP(){const t=us(),{data:s}=Qa();if(s&&s.feature_modules?.commerce_enabled===!1)return e.jsx(_t,{to:t("/dashboard"),replace:!0});const{data:a,isLoading:n}=Zf();return n?e.jsxs("div",{className:"space-y-6",children:[e.jsx(Wu,{}),e.jsx("div",{className:"space-y-3",children:[1,2,3].map(r=>e.jsx(Y,{className:"h-32 w-full"},r))})]}):e.jsxs("div",{className:"space-y-6",children:[e.jsx(Wu,{}),a?.length?a.length===1?(()=>{const r=a[0];return e.jsx(L,{className:"min-w-0 overflow-hidden transition-shadow hover:shadow-sm",children:e.jsx($,{className:"p-5 sm:p-6",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0 space-y-2",children:[e.jsx(je,{to:t(`/events/${r.id}`),className:"block text-xl font-semibold tracking-tight text-foreground hover:underline",children:r.name}),r.is_registered&&e.jsx(Vu,{})]}),e.jsx("div",{className:"shrink-0 text-right",children:r.original_price&&r.price<r.original_price?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-sm text-muted-foreground line-through",children:mr(r.original_price)}),e.jsx("span",{className:"ml-1 text-xl font-semibold tracking-tight text-emerald-700 dark:text-emerald-400",children:mr(r.price)})]}):e.jsx("span",{className:"text-xl font-semibold tracking-tight text-foreground",children:r.price===0?"Free":mr(r.price)})})]}),e.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-1.5 text-sm text-muted-foreground",children:[r.start_date&&e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Yt,{className:"h-3.5 w-3.5"}),Be(pt(r.start_date),"EEEE, MMMM d, yyyy"),r.end_date&&r.end_date!==r.start_date&&e.jsxs(e.Fragment,{children:[" â ",Be(pt(r.end_date),"EEEE, MMMM d, yyyy")]})]}),r.location&&e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Fa,{className:"h-3.5 w-3.5"}),r.location]}),r.spots_left!==null&&e.jsxs("span",{className:r.spots_left<=10?"font-medium text-red-600 dark:text-red-400":"",children:[r.spots_left," spot",r.spots_left!==1?"s":""," left"]})]}),r.description&&e.jsx("p",{className:"text-sm leading-relaxed text-muted-foreground",children:r.description}),!r.is_registered&&e.jsx("div",{className:"border-t pt-4",children:e.jsx(g,{asChild:!0,className:"bg-blue-600 font-medium text-white hover:bg-blue-700",children:e.jsx(je,{to:t(`/events/${r.id}`),children:"View details"})})})]})})})})():e.jsx("div",{className:"space-y-3",children:a.map(r=>e.jsx(L,{className:"min-w-0 overflow-hidden transition-shadow hover:shadow-sm",children:e.jsx($,{className:"p-4",children:e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"mb-1.5 flex flex-wrap items-center gap-2",children:[e.jsx(je,{to:t(`/events/${r.id}`),className:"text-base font-semibold tracking-tight text-foreground hover:underline",children:r.name}),r.is_registered&&e.jsx(Vu,{})]}),r.description&&e.jsx("p",{className:"mb-2 line-clamp-2 text-sm leading-relaxed text-muted-foreground",children:r.description}),e.jsxs("div",{className:"flex flex-wrap gap-x-3 gap-y-1 text-xs text-muted-foreground",children:[r.start_date&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Yt,{className:"h-3 w-3"}
3952),Be(pt(r.start_date),"MMM d, yyyy"),r.end_date&&r.end_date!==r.start_date&&e.jsxs(e.Fragment,{children:[" â ",Be(pt(r.end_date),"MMM d, yyyy")]})]}),r.location&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Fa,{className:"h-3 w-3"}),r.location]}),r.spots_left!==null&&e.jsxs("span",{className:r.spots_left<=10?"font-medium text-red-600 dark:text-red-400":"",children:[r.spots_left," spot",r.spots_left!==1?"s":""," left"]})]})]}),e.jsxs("div",{className:"shrink-0 text-right",children:[e.jsx("div",{className:"mb-2",children:r.original_price&&r.price<r.original_price?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-sm text-muted-foreground line-through",children:mr(r.original_price)}),e.jsx("span",{className:"ml-1 text-lg font-semibold tracking-tight text-emerald-700 dark:text-emerald-400",children:mr(r.price)})]}):e.jsx("span",{className:"text-lg font-semibold tracking-tight text-foreground",children:r.price===0?"Free":mr(r.price)})}),!r.is_registered&&e.jsx(g,{asChild:!0,size:"sm",className:"bg-blue-600 font-medium text-white hover:bg-blue-700",children:e.jsx(je,{to:t(`/events/${r.id}`),children:"View details"})})]})]})})},r.id))}):e.jsx(L,{className:"min-w-0 overflow-hidden",children:e.jsxs($,{className:"flex flex-col items-center py-12 text-center",children:[e.jsx(Yt,{className:"mb-3 h-10 w-10 text-muted-foreground/60"}),e.jsx("h2",{className:"mb-1 text-base font-semibold tracking-tight text-foreground",children:"No upcoming events"}),e.jsx("p",{className:"max-w-sm text-sm text-muted-foreground",children:"There are no events scheduled at this time. Check back soon for new events and activities."})]})})]})}function pl(t){const{eventIds:s,roleId:a,renewalOptIn:n,autoRenewOptIn:r,claimMembershipOffer:i,enabled:l}=t,{member:m}=ft(),c=m?.id??null,d=n===!0?{auto_renew_opt_in:r!==!1}:null,u=i===!0,h=eb({queries:s.map(N=>({queryKey:["portal","price-preview",c,N,a,n===!0,u],queryFn:()=>Zs.pricePreview({event_id:N,selected_role_type_id:a,renewal:d,claim_membership_offer:u}),enabled:l&&s.length>0,staleTime:3e4}))}),p={};let x=!1,f=!1;return h.forEach((N,j)=>{N.data&&(p[s[j]]=N.data.price),N.isPending&&l&&(x=!0),N.isError&&l&&(f=!0)}),{byId:p,isPending:x,anyError:f,refetchAll:()=>{h.forEach(N=>{N.isError&&N.refetch()})}}}const AP={previewPrice:async(t,s)=>(await Me.post("/portal/checkout/price-preview",{event_id:t,renewal:{auto_renew_opt_in:s}})).data?.renewal??null};function Ud(t){const{eventId:s,autoRenewOptIn:a,enabled:n=!0}=t,{member:r}=ft(),i=r?.id??null,l=re({queryKey:["portal","renewal-preview",i,s,a],queryFn:()=>AP.previewPrice(s,a),enabled:n,staleTime:3e4});return{data:l.data??null,isPending:l.isPending}}function EP({eventId:t,roleTypeId:s,onSkip:a,onLinked:n}){const{societySlug:r}=ft(),{data:i}=Od(r),l=i?.society,m=l?.contact_email,c=re({queryKey:["phase3","match-candidates",t,s],queryFn:()=>vc.matchCandidates(t,s)}),d=c.data?.candidates??[];return c.isLoading||d.length===0?null:e.jsx("div",{className:"rounded-lg border p-4",style:{borderColor:"color-mix(in srgb, var(--portal-primary, #2563eb) 30%, transparent)",background:"color-mix(in srgb, var(--portal-primary, #2563eb) 5%, transparent)"},children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"rounded-md p-2",style:{background:"color-mix(in srgb, var(--portal-primary, #2563eb) 10%, transparent)"},children:e.jsx(Kl,{className:"h-5 w-5",style:{color:"var(--portal-primary, #2563eb)"}})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"text-base font-semibold tracking-tight",children:"Have we met before?"}),e.jsxs("p",{className:"mt-1 text-sm text-muted-foreground",children:["We found a previous ",l?.name??"society"," membership that may be yours. Verify it to merge your accounts and unlock member pricing."]}),e.jsx("ul",{className:"mt-3 space-y-2",children:d.map(u=>e.jsxs("li",{className:"flex items-center justify-between gap-3 rounded-md bg-background p-3",children:[e.jsx("span",{className:"text-sm",children:u.redacted_display}),u.verification_unavailable||!u.challenge_eligible_id?e.jsx("span",{className:"text-xs text-muted-foreground",children:m?e.jsxs(e.Fragment,{children:["Email"," ",e.jsx("a",{href:`mailto:${m}`,className:"underline",children:m})," ","to claim"]}):e.jsx(e.Fragment,{children:"Contact your society to claim this account"})}):e.jsx(TP,{challengeEligibleId:u.challenge_eligible_id,onLinked:n})]},u.challenge_eligible_id??u.redacted_display))}),e.jsx(g,{variant:"ghost",size:"sm",onClick:a,className:"mt-3 min-h-[36px]",children:"Skip â register as a new member"})]})]})})}function TP({challengeEligibleId:t,onLinked:s}){const{applyMergeUpdate:a}=ft(),[n,r]=o.useState("idle"),[i,l]=o.useState(null),[m,c]=o.useState(""),[d,u]=o.useState(""),[h,p]=o.use
3952State(null);async function x(){if(t){p(null),r("sending");try{const b=await vc.startLinkChallenge(t);l(b.challenge_id),c(b.sent_to_redacted),r("code")}catch{p("Could not send code. Please try again."),r("idle")}}}async function f(){if(!(!i||d.length!==6)){r("verifying");try{const b=await vc.verifyLinkChallenge(i,d);if(b.verified){a(b),s();return}p(`Wrong code. ${b.attempts_remaining??0} attempts remaining.`),r("code")}catch{p("Verification failed."),r("code")}}}return n==="idle"||n==="sending"?e.jsx(g,{size:"sm",onClick:x,disabled:n==="sending",className:"min-h-[36px] bg-blue-600 hover:bg-blue-700 text-white",children:n==="sending"?"Sendingâ¦":"Verify"}):e.jsxs("div",{className:"flex flex-col items-end gap-1",children:[e.jsxs("span",{className:"text-xs text-muted-foreground",children:["Code sent to ",m]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{value:d,onChange:b=>u(b.target.value.replace(/\D/g,"").slice(0,6)),inputMode:"numeric",maxLength:6,placeholder:"000000",className:"w-24 rounded-md border px-2 py-1 text-center font-mono"}),e.jsx(g,{size:"sm",onClick:f,disabled:n==="verifying"||d.length!==6,className:"min-h-[36px] bg-blue-600 hover:bg-blue-700 text-white",children:n==="verifying"?"Checkingâ¦":"Submit"})]}),h&&e.jsx("span",{className:"text-xs text-red-600",children:h})]})}function fr(t){return t.toLocaleString("en-US",{style:"currency",currency:"USD"})}function FP(t,s){const a=pt(t),n=pt(s);if(a.getDate()===1){const i=a.getFullYear(),l=n.getFullYear(),m=String(l).slice(-2);return l>i?`${i}â${m}`:String(i)}return"a new year of membership"}function RP(t,s,a,n){if(n&&a!=null&&a>0&&s!=null&&s>0){const i=t+(s??0);return`${fr(t)}/yr with auto-renew (${fr(s??0)} off â was ${fr(i)}/yr)`}return`${fr(t)}/yr`}function MP({eventId:t,societyName:s,renewalOptIn:a,autoRenewOptIn:n,netSavings:r,onChange:i}){const{data:l,isPending:m}=Ud({eventId:t,autoRenewOptIn:n});if(o.useEffect(()=>{l&&l.auto_renew_enabled===!1&&n&&i({renewalOptIn:a,autoRenewOptIn:!1})},[l,n,a,i]),m||!l||!l.eligible)return null;const c=Number(l.price??0),d=l.discount_amount!=null?Number(l.discount_amount):null,u=l.auto_renew_discount_percent??null,h=u!=null&&u>0,p=d!=null&&d>0?d:c*(u??0)/100,x=l.cycle_start&&l.cycle_end?FP(l.cycle_start,l.cycle_end):"upcoming year",f=l.cycle_end?Be(pt(l.cycle_end),"MMM d, yyyy"):null,b=RP(c,d,u,n);return e.jsx("div",{className:"rounded-lg border p-4",style:{borderColor:"color-mix(in srgb, var(--portal-primary, #2563eb) 30%, transparent)",background:"color-mix(in srgb, var(--portal-primary, #2563eb) 5%, transparent)"},children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"rounded-md p-2",style:{background:"color-mix(in srgb, var(--portal-primary, #2563eb) 10%, transparent)"},children:e.jsx(St,{className:"h-5 w-5",style:{color:"var(--portal-primary, #2563eb)"}})}),e.jsx("div",{className:"flex-1",children:e.jsxs("label",{className:"flex cursor-pointer items-start gap-3",children:[e.jsx(ot,{checked:a,onCheckedChange:N=>i({renewalOptIn:N===!0,autoRenewOptIn:n}),className:"mt-0.5"}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"font-semibold tracking-tight",children:["Renew ",s," membership for ",x]}),e.jsxs("div",{className:"mt-1 text-sm text-muted-foreground",children:[b,f&&e.jsxs(e.Fragment,{children:[" · Active today through ",f]})]}),a&&l.auto_renew_enabled===!0&&e.jsxs("label",{className:"mt-3 flex cursor-pointer items-center gap-2 text-sm",children:[e.jsx(ot,{checked:n,onCheckedChange:N=>i({renewalOptIn:a,autoRenewOptIn:N===!0}),onClick:N=>N.stopPropagation()}),e.jsx("span",{children:h?e.jsxs(e.Fragment,{children:["Enable auto-renew (",u,"% off â save"," ",fr(p),"/yr)"]}):e.jsx(e.Fragment,{children:"Auto-renew my membership each cycle â your saved card will be charged automatically before expiry. Turn off anytime from your subscription page."})})]}),r>0?e.jsxs("p",{className:"mt-3 inline-flex items-center gap-1.5 rounded-md px-2.5 py-1 text-sm font-medium",style:{background:"color-mix(in srgb, var(--portal-primary, #2563eb) 12%, transparent)",color:"var(--portal-primary, #2563eb)"},children:["Pay ",fr(r)," less today + get a full year of membership."]}):e.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:"Renewing unlocks the member rate for this event + a full year of membership."})]})]})})]})})}function DP({societyName:t}){const s=J(),{societySlug:a}=ft(),{data:n,isLoading:r}=Od(a),i=n?.non_member_role_options??[],[l,m]=o.useState(""),[c,d]=o.use
3952State(!1),[u,h]=o.useState(null),p=async()=>{if(l){d(!0),h(null);try{await gt.updateProfile({declared_role_type_id:l}),await s.invalidateQueries({queryKey:["portal","profile"]})}catch(x){const b=x?.response?.data?.detail;h(typeof b=="string"?b:"Unable to save your role. Please pick again."),d(!1)}}};return e.jsx("div",{className:"rounded-md border border-border bg-card p-5",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("span",{className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-lg",style:{backgroundColor:"var(--portal-primary-light)",color:"var(--portal-primary)"},children:e.jsx(zp,{className:"h-4 w-4"})}),e.jsxs("div",{className:"flex-1 space-y-3",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-base font-semibold tracking-tight",children:"Before you register"}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"What's your professional role? Pricing varies by role, and we'll save this to your profile so we won't ask again."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(T,{htmlFor:"declare-role-select",className:"text-sm font-medium",children:["Professional role ",e.jsx("span",{className:"text-destructive",children:"*"})]}),r?e.jsx("div",{className:"h-10 animate-pulse rounded-md bg-muted"}):i.length===0?e.jsxs("p",{className:"text-sm text-muted-foreground",children:["No roles available. Please contact ",t," for assistance."]}):e.jsxs(qe,{value:l,onValueChange:m,children:[e.jsx(Le,{id:"declare-role-select",className:"w-full",children:e.jsx(Ie,{placeholder:"Select your role"})}),e.jsx($e,{children:i.map(x=>e.jsx(q,{value:x.id,className:"min-h-[44px]",children:x.name},x.id))})]})]}),u&&e.jsx("p",{className:"rounded-md bg-destructive/10 px-3 py-2 text-sm text-destructive",children:u}),e.jsx("div",{className:"flex justify-end",children:e.jsx(g,{onClick:()=>{p()},disabled:!l||c||r,className:"bg-blue-600 text-white hover:bg-blue-700",children:c?"Savingâ¦":"Save and continue"})})]})]})})}function Gu(t){return t.toLocaleString("en-US",{style:"currency",currency:"USD"})}function Yu(t){if(!t.start_date)return null;const s=Be(pt(t.start_date),"MMM d");return!t.end_date||t.end_date===t.start_date?s:`${s} â ${Be(pt(t.end_date),"MMM d, yyyy")}`}function LP({event:t,selectedChildIds:s,selectedRoleTypeId:a,isActiveMember:n,isOnNonMemberType:r,offerStatusAllowed:i,claimMembershipOffer:l,societyName:m,renewalOptIn:c,autoRenewOptIn:d,declaredRoleTypeId:u,pendingReason:h,errorReason:p,onRetry:x,onChange:f,onNext:b}){const[N,j]=o.useState(!1),[w,v]=o.useState(!1),k=t.children??[],S=u==null&&r,_=!n&&!r,y=t.offer_free_membership_enabled===!0,C=t.offer_role_eligibility,P=a!==null&&C!=null&&C.length>0&&C.includes(a),A=i&&!n&&r&&y&&P,E=t.offer_free_membership_months??12;o.useEffect(()=>{!A&&l&&f({selectedChildIds:s,selectedRoleTypeId:a,claimMembershipOffer:!1,renewalOptIn:c,autoRenewOptIn:d})},[A]),o.useEffect(()=>{const M=s.filter(I=>{const R=k.find(Se=>Se.id===I);return R?!(R.spots_left!==null&&R.spots_left<=0)&&!R.external_registration_url&&!R.member_already_registered&&R.registration_allowed!==!1:!1});M.length!==s.length&&f({selectedChildIds:M,selectedRoleTypeId:a,claimMembershipOffer:l,renewalOptIn:c,autoRenewOptIn:d})},[k]);const Q=o.useMemo(()=>[t.id,...s],[t.id,s]),{byId:U}=pl({eventIds:Q,roleId:a,renewalOptIn:c,autoRenewOptIn:d,claimMembershipOffer:A&&l,enabled:!0}),{byId:D}=pl({eventIds:[t.id],roleId:a,renewalOptIn:!1,autoRenewOptIn:!1,enabled:_}),{byId:K}=pl({eventIds:[t.id],roleId:a,renewalOptIn:!0,autoRenewOptIn:d,enabled:_}),{data:xe}=Ud({eventId:t.id,autoRenewOptIn:d,enabled:_}),z=U[t.id]??t.price,ae=M=>U[M.id]??M.price,ue=!_||!c||K[t.id]!=null,_e=o.useMemo(()=>!c||!xe?.eligible||xe.price==null||!ue?0:Number(xe.price),[c,xe,ue]),ee=o.useMemo(()=>{let M=t.is_registered?0:z;for(const I of s){const R=k.find(X=>X.id===I);R&&!R.member_already_registered&&(M+=ae(R))}return M+_e},[t.is_registered,z,s,k,U,_e]),se=o.useMemo(()=>!_||!xe?.eligible||xe.price==null?0:Number(xe.price),[_,xe]),le=o.useMemo(()=>{if(!_)return 0;const M=D[t.id],I=K[t.id];return M==null||I==null?0:Math.max(0,M-I-se)},[_,D,K,t.id,se]),oe=M=>{s.includes(M)?f({selectedChildIds:s.filter(I=>I!==M),selectedRoleTypeId:a,claimMembershipOffer:l,renewalOptIn:c,autoRenewOptIn:d}):f({selectedChildIds:[...s,M],selectedRoleTypeId:a,claimMembershipOffer:l,renewalOptIn:c,autoRenewOptIn:d})},Pe=!t.is_registered&&t.spots_left!==null&&t.spots_left!==void 0&&t.spots_left<=0;return e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:t.name}),e.jsxs("p",{className:"mt-1 flex flex-wrap items-center gap-3 text-sm text-muted-foreground",children:[t.start_date&&e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(Yt,{className:"h-3.5 w-3.5"}),Yu(t)]}),(t.venue||t.location)&&e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(Fa,{className:"h-3.5 w-3.5"}),t.venue||t.location]})]}),t.description&&e.jsx("p",{className:"mt-3 text-sm text-foreground",children:t.description})]}),S&&e.jsx(DP,{societyName:m}),!S&&e.jsxs(e.Fragment,{children:[A&&e.jsx("div",{className:"rounded-md border border-portal-primary/20 bg-portal-primary/5 p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("span",{className:"grid h-9 w-9 shrink-0 place-items-center rounded-md bg-portal-primary/15 text-portal-primary",children:e.jsx(ci,{className:"h-5 w-5"})}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("p",{className:"font-semibold tracking-tight",children:["Claim your free ",E===12?"1-year":`${E}-month`," ",m," membership"]}),e.jsxs("p",{className:"mt-1 text-sm text-muted-foreground",children:["Pay the member rate today AND get a full year of ",m," membership at no extra cost."]}),e.jsx("ul",{className:"mt-3 space-y-1 text-sm",children:e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx(Kt,{className:"mt-0.5 h-4 w-4 text-emerald-500"}),"Member rate at all ",m," events this year"]})}),e.jsxs("label",{className:"mt-4 flex items-start gap-2",children:[e.jsx(ot,{checked:l,onCheckedChange:M=>f({selectedChildIds:s,selectedRoleTypeId:a,claimMembershipOffer:M===!0,renewalOptIn:c,autoRenewOptIn:d}),className:"mt-0.5"}),e.jsxs("span",{className:"text-sm",children:["Yes, give me 1 year of free ",m," membership.",e.jsx("span",{className:"block text-xs text-muted-foreground",children:"You'll receive a renewal reminder before your year is up. Cancel anytime."})]})]})]})]})}),_&&e.jsx(MP,{eventId:t.id,societyName:m,renewalOptIn:c,autoRenewOptIn:d,netSavings:le,onChange:({renewalOptIn:M,autoRenewOptIn:I})=>f({selectedChildIds:s,selectedRoleTypeId:a,claimMembershipOffer:l,renewalOptIn:M,autoRenewOptIn:I})}),k.length>0&&e.jsxs("div",{children:[e.jsx(T,{className:"text-sm font-semibold tracking-tight",children:"Add-on events (optional)"}),e.jsx("p",{className:"mb-3 mt-1 text-xs text-muted-foreground",children:"Check the add-ons you'd like to attend."}),e.jsx("div",{className:"space-y-2",children:k.map(M=>{const I=s.includes(M.id),R=M.spots_left!==null&&M.spots_left<=0,X=!!M.external_registration_url,Se=M.member_already_registered,ce=M.registration_allowed===!1,ke=R||Se||ce,ve=!X&&!ke;return e.jsxs("div",{role:ve?"button":void 0,tabIndex:ve?0:void 0,onClick:ve?()=>oe(M.id):void 0,onKeyDown:ve?Ne=>{(Ne.key===" "||Ne.key==="Enter")&&(Ne.preventDefault(),oe(M.id))}:void 0,className:`flex min-h-[44px] items-start gap-3 rounded-md border p-3 ${I?"border-blue-500 bg-blue-50/40":"border-border"} ${ke||X?"opacity-60":""} ${ke?"cursor-not-allowed":""}
3952 ${ve?"cursor-pointer hover:bg-blue-50/30":""}`,children:[!X&&!ce&&e.jsx(ot,{checked:I,disabled:ke,onCheckedChange:()=>oe(M.id),onClick:Ne=>Ne.stopPropagation(),className:"mt-0.5"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-semibold tracking-tight",children:M.name}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[Yu(M)??"",!R&&M.spots_left!==null&&M.spots_left>0&&M.spots_left<=10&&e.jsxs(e.Fragment,{children:[" · only ",M.spots_left," spots left"]}),R&&e.jsx(e.Fragment,{children:" · sold out"}),Se&&e.jsx(e.Fragment,{children:" · already registered â"}),ce&&!R&&!Se&&e.jsx(e.Fragment,{children:" · limited to specific members"}),X&&e.jsxs(e.Fragment,{children:[" ","·"," ",e.jsx("a",{href:M.external_registration_url,className:"text-blue-600 underline",target:"_blank",rel:"noopener noreferrer",onClick:Ne=>Ne.stopPropagation(),children:"register externally"})]})]})]}),e.jsx("div",{className:"text-sm font-semibold tabular-nums",children:Gu(ae(M))})]},M.id)})})]}),!N&&!w&&a&&e.jsx(EP,{eventId:t.id,roleTypeId:a,onSkip:()=>j(!0),onLinked:()=>v(!0)}),e.jsxs("div",{className:"flex items-center justify-between rounded-md border bg-emerald-50/60 p-3",children:[e.jsx("span",{className:"text-sm font-semibold tracking-tight text-emerald-900",children:"Running total"}),e.jsx("span",{className:"text-lg font-semibold tabular-nums text-emerald-900",children:Gu(ee)})]}),e.jsxs("div",{className:"flex items-center justify-end",children:[e.jsxs(g,{onClick:b,disabled:Pe||h!=null||p!=null,size:"lg",className:"bg-blue-600 text-white hover:bg-blue-700",children:["Continue",e.jsx(as,{className:"ml-1.5 h-4 w-4"})]}),Pe&&e.jsx("p",{className:"ml-3 text-xs text-destructive self-center",children:"This event is sold out."}),!Pe&&p!=null&&e.jsxs("div",{className:"ml-3 flex items-center gap-2",children:[e.jsx("p",{className:"text-xs text-destructive",children:p}),e.jsxs(g,{variant:"outline",size:"sm",onClick:x,children:[e.jsx(sd,{className:"mr-1.5 h-3 w-3"}),"Retry"]})]}),!Pe&&p==null&&h!=null&&e.jsx("p",{className:"ml-3 text-xs text-muted-foreground self-center",children:h})]})]})]})}const $P={first_name:"first_name",last_name:"last_name",email:"email",phone:"phone",address:"address_line1",city:"city",state:"state",zip_code:"postal_code",country:"country",organization:"organization"},qP=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;function IP({initial:t,onBack:s,onNext:a,requiredOverlapKeys:n}){const{data:r}=ar(),i=pg(),[l,m]=o.useState(t),[c,d]=o.useState(null),[u,h]=o.useState({}),p=o.useRef(!1);o.useEffect(()=>{if(!r||p.current)return;p.current=!0;const _=l,y={..._};let C=!1;for(const P of yr)if(!_[P]){const A=r[P];typeof A=="string"&&A&&(y[P]=A,C=!0)}C&&m(y)},[r]);const x=(_,y)=>{m(C=>({...C,[_]:y})),u[_]&&h(C=>{const P={...C};return delete P[_],P}),c&&d(null)},f=new Set;if(n)for(const _ of n){const y=$P[_];y&&f.add(y)}const b=_=>_==="first_name"||_==="last_name"||_==="email"?!0:f.has(_),N={};l.first_name||(N.first_name="Required"),l.last_name||(N.last_name="Required"),l.email?qP.test(l.email)||(N.email="Enter a valid email"):N.email="Required";for(const _ of f){if(_==="first_name"||_==="last_name"||_==="email")continue;const y=l[_];(!y||typeof y=="string"&&y.trim()==="")&&(N[_]="Required for this event")}const j={...N};for(const[_,y]of Object.entries(u)){const C=_;!j[C]&&y&&(j[C]=y)}const w=Object.keys(N).length>0,v=!w&&!i.isPending,k=_=>{const C=_?.response?.data?.detail,P={};let A=null;if(typeof C=="string")A=C;else if(Array.isArray(C))for(const E of C){const Q=E,U=Q.msg?.replace(/^value error,?\s*/i,"").trim()||"Invalid value";if(Array.isArray(Q.loc)&&Q.loc.length>=2){const D=Q.loc.filter(K=>typeof K=="string").pop();if(D&&yr.includes(D)){P[D]=U;continue}}A=A?`${A}; ${U}`:U}return{fieldErrors:P,topMsg:A}},S=async()=>{if(v){if(d(null),h({}),r){const _={};for(const y of yr){const C=r[y];l[y]!==(typeof C=="string"?C:"")&&(_[y]=l[y])}if(Object.keys(_).length>0)try{await i.mutateAsync(_)}catch(y){const C=y?.response?.status;if(C===422){const{fieldErrors:P,topMsg:A}=k(y);h(P),d(A??"Some of your contact info couldnât be saved to your profile. Please check the highlighted fields.");return}ix(y,{extra:{context:"wizard-profile-sync-failed",diff:_,status:C}})}}a(l)}};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-semibold tracking-tight",children:"Your contact info"}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"Prefilled from your profile. Edit anything that's different for this registration."})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsx(ka,{label:"First name",required:!0,error:j.first_name,children:e.jsx(O,{value:l.first_name,onChange:_=>x("first_name",_.target.value)})}),e.jsx(ka,{label:"Last name",required:!0,error:j.last_name,children:e.jsx(O,{value:l.last_name,onChange:_=>x("last_name",_.target.value)})})]}),e.jsx(ka,{label:"Email",required:!0,error:j.email,children:e.jsx(O,{type:"email",value:l.email,onChange:_=>x("email",_.target.value)})}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsx(ka,{label:"Phone",required:b("phone"),error:j.phone,children:e.jsx(O,{value:l.phone,onChange:_=>x("phone",_.target.value)})}),e.jsx(ka,{label:"Organization",required:b("organization"),error:j.organization,children:e.jsx(O,{value:l.organization,onChange:_=>x("organization",_.target.value)})})]}),e.jsx(ka,{label:"Address line 1",required:b("address_line1"),error:j.address_line1,children:e.jsx(O,{value:l.address_line1,onChange:_=>x("address_line1",_.target.value)})}),e.jsx(ka,{label:"Address line 2",error:j.address_line2,children:e.jsx(O,{value:l.address_line2,onChange:_=>x("address_line2",_.target.value)})}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3",children:[e.jsx(ka,{label:"City",required:b("city"),error:j.city,children:e.jsx(O,{value:l.city,onChange:_=>x("city",_.target.value)})}),e.jsx(ka,{label:"State / Province",required:b("state"),error:j.state,children:e.jsx(O,{value:l.state,onChange:_=>x("state",_.target.value)})}),e.jsx(ka,{label:"Postal code",required:b("postal_code"),error:j.postal_code,children:e.jsx(O,{value:l.postal_code,onChange:_=>x("postal_code",_.target.value)})})]}),e.jsx(ka,{label:"Country",required:b("country"),error:j.country,children:e.jsx(O,{value:l.country,onChange:_=>x("country",_.target.value)})}),c&&e.jsx("div",{role:"alert",className:"rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive",children:c}),e.jsxs("div",{className:"border-t pt-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(g,{variant:"ghost",size:"lg",onClick:s,children:[e.jsx(es,{className:"mr-1.5 h-4 w-4"}),"Back"]}),e.jsxs(g,{onClick:S,disabled:!v,size:"lg",className:"bg-blue-600 text-white hover:bg-blue-700",children:[i.isPending?"Savingâ¦":"Next",!i.isPending&&e.jsx(as,{className:"ml-1.5 h-4 w-4"})]})]}),w&&e.jsxs("p",{className:"mt-2 text-right text-xs text-muted-foreground",children:["Complete the highlighted required field",Object.keys(N).length>
39521?"s":""," above to continue."]})]})]})}const OP="border-amber-300 bg-amber-50 focus-visible:ring-amber-400 dark:border-amber-700/60 dark:bg-amber-950/30";function ka({label:t,required:s,error:a,children:n}){const r=a&&o.isValidElement(n)?o.cloneElement(n,{className:me(n.props.className,OP),"aria-invalid":!0}):n;return e.jsxs("div",{children:[e.jsxs(T,{className:"text-sm font-medium",children:[t,s&&e.jsx("span",{className:"ml-1 text-destructive",children:"*"})]}),e.jsx("div",{className:"mt-1",children:r}),a&&e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:a})]})}function UP({eventName:t,fields:s,sections:a,initial:n,isLastStep:r,onBack:i,onNext:l}){const m=s.filter(c=>!bo.has(c.field_key));return e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight text-foreground",children:t}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"These questions are specific to this event."})]}),e.jsx(kf,{fields:m,sections:a,initial:n,renderActions:({canSubmit:c,missingRequiredCount:d,getValues:u})=>e.jsxs("div",{className:"border-t border-border pt-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(g,{type:"button",variant:"ghost",size:"lg",onClick:i,children:[e.jsx(es,{className:"mr-1.5 h-4 w-4"}),"Back"]}),e.jsx(g,{type:"button",onClick:()=>l(u()),disabled:!c,size:"lg",className:"bg-blue-600 font-medium text-white hover:bg-blue-700",children:r?e.jsxs(e.Fragment,{children:[e.jsx(Qn,{className:"mr-1.5 h-4 w-4"}),"Add to cart & continue"]}):e.jsxs(e.Fragment,{children:["Next",e.jsx(as,{className:"ml-1.5 h-4 w-4"})]})})]}),!c&&d>0&&e.jsxs("p",{className:"mt-2 text-right text-xs text-muted-foreground",children:["Answer the ",d," required question",d===1?"":"s"," highlighted above to continue."]})]})})]})}function zP(t){return re({queryKey:["portal","event-detail",t],queryFn:()=>Zs.getEvent(t),enabled:!!t,staleTime:6e4})}const BP=new Set(["active","grace"]);function KP({event:t}){const s=kt(),a=us(),{items:n,removeItem:r,addItem:i}=_i(),{isAuthenticated:l,member:m}=ft(),{data:c,isError:d,refetch:u}=ar(),[h]=ws(),p=h.get("preselect"),x=(c?.status??"").toLowerCase(),f=BP.has(x)&&!c?.is_non_member,b=c?.is_non_member===!0,N=k4(c?.status),[j,w]=o.useState(()=>p&&t.children?.some(De=>De.id===p)?[p]:[]),[v,k]=o.useState(c?.declared_role_type_id??null),[S,_]=o.useState(j4()),[y,C]=o.useState({}),[P,A]=o.useState(0),[E,Q]=o.useState(!1),[U,D]=o.useState(!1),[K,xe]=o.useState(!0),[z,ae]=o.useState(!1),[ue,_e]=o.useState(m?.id??null);o.useEffect(()=>{const De=m?.id??null;if(De!==ue){k(null),ae(!1),_e(De);return}const he=c?.declared_role_type_id;he!=null&&(k(Xe=>Xe??he),ae(!0))},[c?.declared_role_type_id,m?.id,ue]),o.useEffect(()=>{c&&_(De=>{let he=!1;const Xe={...De};for(const rt of yr)if(!De[rt]){const yt=c[rt];typeof yt=="string"&&yt&&(Xe[rt]=yt,he=!0)}return he?Xe:De})},[c]),o.useEffect(()=>{C(De=>{const he={};let Xe=!1;for(const[rt,yt]of Object.entries(De))rt===t.id||j.includes(rt)?he[rt]=yt:Xe=!0;return Xe?he:De})},[j,t.id]);const{steps:ee}=o.useMemo(()=>w4({parent:t,selectedChildIds:j,memberHasParentRegistration:t.is_registered===!0}),[t,j]);o.useEffect(()=>{P>=ee.length&&A(ee.length-1)},[ee.length,P]);const se=ee[P]??ee[0],le=P===ee.length-1,oe=se.kind==="event-fields"&&se.eventId!==t.id?se.eventId:null,{data:Pe,isLoading:M}=zP(oe),I=o.useMemo(()=>{if(se.kind!=="event-fields")return null;const De=se.eventId===t.id,he=De?t.registration_form_fields?.fields??[]:Pe?.registration_form_fields?.fields??[],Xe=De?t.registration_form_fields?.sections??null:Pe?.registration_form_fields?.sections??null;if(!De&&M)return{fields:he,sections:Xe,initial:{}};const rt=new Map(he.map(be=>[be.field_key,be])),yt=(be,lt)=>{const ht=be.field_type,zt=be.options??null;return ht==="text"||ht==="textarea"||ht==="email"||ht==="phone"||ht==="url"?typeof lt=="string":ht==="number"?typeof lt=="number"||typeof lt=="string"&<.trim()!==""&&!Number.isNaN(Number(lt)):ht==="date"?typeof lt=="string"&&/^\d{4}-\d{2}-\d{2}/.test(lt):ht==="checkbox"?typeof lt=="boolean":ht==="dropdown"?typeof lt=="string"&&(!zt||zt.includes(lt)):ht==="multi_select"?Array.isArray(lt)&&(!zt||lt.every(Tt=>typeof Tt=="string"&&zt.includes(Tt))):!1},dt={},jt=c?.custom_fields??{};for(const be of he){if(be.source!=="custom_field")continue;const lt=jt[be.field_key];lt!=null&&(typeof lt=="string"&<.trim()===""||yt(be,lt)&&(dt[be.field_key]=lt))}for(const[be,lt]of Object.entries(y))if(be!==se.eventId)for(const[ht,zt]of Object.entries(lt)){const Tt=rt.get(ht);Tt&&zt!=null&&(typeof zt=="string"&&zt.trim()===""||dt[ht]===void 0&&yt(Tt,zt)&&(dt[ht]=zt))}const Ot=y[se.eventId]??{};return{fields:he,sections:Xe,initial:{...dt,...Ot}}},[se,t,Pe,M,y,c]),R=o.useMemo(()=>{const De=new Set,he=t.registration_form_fields?.fields??[],Xe=j.map(rt=>t.children?.find(yt=>
3952yt.id===rt)).filter(rt=>rt!=null).flatMap(rt=>rt.id===Pe?.id?Pe.registration_form_fields?.fields??[]:[]);for(const rt of[...he,...Xe])rt.required&&bo.has(rt.field_key)&&De.add(rt.field_key);return De},[t,j,Pe]),X=o.useMemo(()=>[t.id,...j],[t.id,j]),Se=(()=>{if(f||!b||!N||t.offer_free_membership_enabled!==!0)return!1;const De=t.offer_role_eligibility;return v===null||!De||De.length===0?!1:De.includes(v)})(),{byId:ce,anyError:ke,refetchAll:ve}=pl({eventIds:X,roleId:v,renewalOptIn:U,autoRenewOptIn:K,claimMembershipOffer:Se&&E,enabled:!0}),Ne=!l||c!==void 0,Qe=l&&c!==void 0&&(c.declared_role_type_id??null)!==null&&!z,Oe=X.every(De=>ce[De]!==void 0),Ce=l&&d,ze=Ce?"Couldn't load your account details.":ke?"Couldn't calculate pricing.":null,Ze=()=>{Ce&&u(),ke&&ve()},Re=ze?null:!Ne||Qe?"Loading your accountâ¦":Oe?null:"Calculating priceâ¦",{data:de}=Ud({eventId:t.id,autoRenewOptIn:K,enabled:U}),ge=()=>A(De=>Math.max(De-1,0)),mt=De=>{const he=De?.contact??S,Xe=De?.formResponses??y,rt=new Set([t.id,...j]);for(const jt of n)jt.type==="event"&&jt.id&&rt.has(jt.id)&&r(jt.type,jt.id);for(const jt of n)jt.type==="membership_renewal"&&r("membership_renewal",jt.id);const yt=v4(he),dt=t.eligible_non_member_roles?.find(jt=>jt.id===v)?.name??null;if(U&&de?.eligible===!0&&de.price!=null&&i({type:"membership_renewal",id:null,name:"Membership renewal",unitPrice:Number(de.price),quantity:1,autoRenewOptIn:K}),!t.is_registered){const jt={...Xe[t.id]??{},...yt},Ot={type:"event",id:t.id,name:t.name,unitPrice:ce[t.id]??t.price,quantity:1,eventDate:t.start_date??void 0,formResponses:jt,selectedRoleTypeId:v??null,selectedRoleName:dt,claimMembershipOffer:Se&&E};i(Ot)}for(const jt of j){const Ot=t.children?.find(ht=>ht.id===jt);if(!Ot||Ot.member_already_registered)continue;const be={...Xe[jt]??{},...yt},lt={type:"event",id:Ot.id,name:Ot.name,unitPrice:ce[Ot.id]??Ot.price,quantity:1,eventDate:Ot.start_date??void 0,formResponses:be,parentEventId:t.id,selectedRoleTypeId:v??null,selectedRoleName:dt,claimMembershipOffer:Se&&E};i(lt)}s(a("/cart"))},ye=De=>{P>=ee.length-1?mt(De):A(he=>Math.min(he+1,ee.length-1))};let Ke=null;!se||se.kind==="event"?Ke=e.jsx(LP,{event:t,selectedChildIds:j,selectedRoleTypeId:v,isActiveMember:f,isOnNonMemberType:b,offerStatusAllowed:N,claimMembershipOffer:E,societyName:c?.society_name??"the society",renewalOptIn:U,autoRenewOptIn:K,declaredRoleTypeId:c?.declared_role_type_id??null,pendingReason:Re,errorReason:ze,onRetry:Ze,onChange:({selectedChildIds:De,selectedRoleTypeId:he,claimMembershipOffer:Xe,renewalOptIn:rt,autoRenewOptIn:yt})=>{w(De),k(he),Q(Xe),D(rt),xe(yt)},onNext:ye}):se.kind==="contact"?Ke=e.jsx(IP,{initial:S,requiredOverlapKeys:R,onBack:ge,onNext:De=>{_(De),ye({contact:De})}}):se.kind==="event-fields"&&(!(se.eventId===t.id)&&M?Ke=e.jsx(Y,{className:"h-64 w-full"}):I&&(Ke=e.jsx(UP,{eventName:se.eventName,fields:I.fields,sections:I.sections,initial:I.initial,isLastStep:le,onBack:ge,onNext:he=>{const Xe={...y,[se.eventId]:he};C(Xe),ye({formResponses:Xe})}})));const ut=se?se.kind==="event"?t.name:se.kind==="contact"?"Your contact info":se.eventId===t.id?`${t.name} â questions`:`${se.eventName} â questions`:"";return e.jsxs("div",{className:"mx-auto max-w-2xl space-y-4 py-6",children:[e.jsxs("p",{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground/80",children:["Step ",P+1," of ",ee.length,ut&&e.jsxs("span",{className:"ml-2 normal-case tracking-normal text-muted-foreground/60",children:["· ",ut]})]}),Ke]})}function QP(){const{id:t}=Ds(),s=us(),a=kt(),{data:n}=Qa(),{data:r,isLoading:i}=m3(t);return o.useEffect(()=>{r?.parent_event_id&&a(s(`/events/${r.parent_event_id}?preselect=${r.id}`),{replace:!0})},[r?.parent_event_id]),n&&n.feature_modules?.commerce_enabled===!1?e.jsx(_t,{to:s("/dashboard"),replace:!0}):i||!r?e.jsxs("div",{className:"mx-auto max-w-2xl space-y-3 py-6",children:[e.jsx(Y,{className:"h-8 w-2/3"}),e.jsx(Y,{className:"h-4 w-1/2"}),e.jsx(Y,{className:"h-32 w-full"})]}):r.parent_event_id?e.jsxs("div",{className:"mx-auto max-w-2xl space-y-3 py-6",children:[e.jsx(Y,{className:"h-8 w-2/3"}),e.jsx(Y,{className:"h-32 w-full"})]}):r.registration_allowed===!1?e.jsxs("div",{className:"mx-auto max-w-2xl space-y-5 py-6",children:[e.jsxs(g,{variant:"ghost",onClick:()=>a(s("/events")),className:"-ml-2",children:[e.jsx(es,{className:"mr-1.5 h-4 w-4"}),"Back to events"]}),e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:r.name}),r.description&&e.jsx("p",{className:"text-sm text-foreground",children:r.description}),e.jsxs("div",{role:"alert",className:"flex items-start gap-2 rounded-md border border-amber-200 bg-amber-50 p-3 text-sm text-amber-900 dark:border-amber-900/40 dark:bg-amber-950/30 dark:text-amber-200",children:[e.jsx(Bt,{className:"mt-0.5 h-4 w-4 shrink-0"}),"This event is limited to specific members and isnât available for your account."]})]}):r.external_registration_url?e.jsxs("div",{className:"mx-auto max-w-2xl space-y-5 py-6",children:[e.jsxs(g,{variant:"ghost",onClick:()=>a(s("/events")),className:"-ml-2",children:[e.jsx(es,{className:"mr-1.5 h-4 w-4"}),"Back to events"]}),e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:r.name}),r.description&&e.jsx("p",{className:"text-sm text-foreground",children:r.description}),e.jsxs("a",{href:r.external_registration_url,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1.5 rounded-md bg-blue-600 px-4 py-2 text-sm font-semibold text-white hover:bg-blue-700",children:["Register externally",e.jsx(Rs,{className:"h-4 w-4"})]})]}):e.jsx(KP,{event:r})}
3952function Hu(t){return t.toLocaleString("en-US",{style:"currency",currency:"USD"})}function WP(){const t=us(),s=kt(),{data:a}=Qa();if(a&&a.feature_modules?.commerce_enabled===!1)return e.jsx(_t,{to:t("/dashboard"),replace:!0});const{data:n,isLoading:r}=u3(),{addItem:i,items:l}=_i(),[m,c]=o.useState(null),d=p=>l.some(x=>x.type==="product"&&x.id===p),u=p=>{i({type:"product",id:p.id,name:p.name,unitPrice:p.price,quantity:1}),c({name:p.name,price:p.price})},h=()=>e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg",style:{backgroundColor:"var(--portal-primary-light)",color:"var(--portal-primary)"},children:e.jsx(Wn,{className:"h-5 w-5"})}),e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:"Shop"})]});return r?e.jsxs("div",{className:"space-y-6",children:[e.jsx(h,{}),e.jsx("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2",children:[1,2,3,4].map(p=>e.jsx(Y,{className:"h-48 w-full"},p))})]}):e.jsxs("div",{className:"space-y-6",children:[e.jsx(h,{}),n?.length?e.jsx("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2",children:n.map(p=>e.jsxs(L,{className:"min-w-0 overflow-hidden transition-shadow hover:shadow-sm",children:[p.image_url&&e.jsx("div",{className:"aspect-video overflow-hidden bg-muted",children:e.jsx("img",{src:p.image_url,alt:p.name,className:"h-full w-full object-cover"})}),e.jsxs($,{className:"p-4",children:[e.jsxs("div",{className:"mb-2 flex items-start justify-between gap-2",children:[e.jsx("h3",{className:"text-base font-semibold tracking-tight text-foreground",children:p.name}),e.jsx("span",{className:"shrink-0 text-lg font-semibold tracking-tight text-foreground",children:Hu(p.price)})]}),p.description&&e.jsx("p",{className:"mb-3 line-clamp-3 text-sm leading-relaxed text-muted-foreground",children:p.description}),e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:p.inventory_count!==null?p.in_stock?e.jsxs("span",{children:[p.inventory_count," in stock"]}):e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full bg-red-100 px-2.5 py-0.5 text-[11px] font-medium text-red-700 dark:bg-red-900/30 dark:text-red-400",children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-red-500","aria-hidden":"true"}),"Out of stock"]}):null}),p.in_stock?d(p.id)?e.jsxs(g,{variant:"outline",size:"sm",disabled:!0,className:"font-medium",children:[e.jsx(Xt,{className:"mr-1 h-3.5 w-3.5"}),"In cart"]}):e.jsxs(g,{size:"sm",className:"bg-blue-600 font-medium text-white hover:bg-blue-700",onClick:()=>u(p),children:[e.jsx(Qn,{className:"mr-1 h-3.5 w-3.5"}),"Add to cart"]}):e.jsx(g,{disabled:!0,size:"sm",className:"font-medium",children:"Out of stock"})]})]})]},p.id))}):e.jsx(L,{className:"min-w-0 overflow-hidden",children:e.jsxs($,{className:"space-y-3 py-12 text-center",children:[e.jsx(Cr,{className:"mx-auto h-10 w-10 text-muted-foreground/60"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No products available at this time."})]})}),e.jsx(Fe,{open:!!m,onOpenChange:()=>c(null),children:e.jsxs(Te,{className:"sm:max-w-md",children:[e.jsx(Ae,{children:e.jsxs(Ee,{className:"flex items-center gap-2 text-foreground",children:[e.jsx(vn,{className:"h-5 w-5 text-emerald-600 dark:text-emerald-400"}),"Added to cart"]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 rounded-md bg-muted/40 px-3 py-2 text-foreground",children:[e.jsx("span",{className:"font-medium",children:m?.name}),e.jsx("span",{className:"font-semibold",children:m?Hu(m.price):""})]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["You have ",l.length," item",l.length!==1?"s":""," in your cart"]}),e.jsxs("div",{className:"flex gap-3",children:[e.jsx(g,{className:"flex-1 bg-blue-600 font-medium text-white hover:bg-blue-700",onClick:()=>{c(null),s(t("/cart"))},children:"View cart"}),e.jsx(g,{variant:"outline",className:"flex-1 border-border text-muted-foreground",onClick:()=>c(null),children:"Keep shopping"})]})]})]})})]})}
3952function Mn(t){return t.toLocaleString("en-US",{style:"currency",currency:"USD"})}const VP={event:Yt,product:Cr,donation:br};function GP(){const t=us(),{data:s}=Qa();if(s&&s.feature_modules?.commerce_enabled===!1)return e.jsx(_t,{to:t("/dashboard"),replace:!0});const a=kt(),{items:n,removeItem:r,updateQuantity:i,clearCart:l,total:m,itemCount:c}=_i(),[d,u]=o.useState(null),h=f=>{if(f.type!=="event"||!f.id){r(f.type,f.id);return}if(f.autoAddedFor){const b=n.find(N=>N.type==="event"&&N.id===f.autoAddedFor);if(b){u({primary:f,linked:b,label:`Removing ${f.name} will also remove ${b.name}. Continue?`});return}r(f.type,f.id);return}if(f.parentEventId){const b=n.find(N=>N.type==="event"&&N.id===f.parentEventId);if(b&&b.autoAddedFor===f.id){r(f.type,f.id),r(b.type,b.id);return}r(f.type,f.id);return}if(f.type==="event"){const b=n.filter(N=>N.type==="event"&&N.parentEventId===f.id);if(b.length>0){const N=b.map(w=>`⢠${w.name}`).join(` 3953`),j=b.length===1?`Removing "${f.name}" will also remove "${b[0].name}" from your cart. Continue?`:`Removing "${f.name}" will also remove these ${b.length} add-on registrations from your cart: 3954 3955${N} 3956 3957Continue?`;if(!window.confirm(j))return;for(const w of b)r(w.type,w.id);r(f.type,f.id);return}}r(f.type,f.id)},p=()=>{if(!d)return;const{primary:f,linked:b}=d;r(f.type,f.id),r(b.type,b.id),u(null)},x=({count:f})=>e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg",style:{backgroundColor:"var(--portal-primary-light)",color:"var(--portal-primary)"},children:e.jsx(Qn,{className:"h-5 w-5"})}),e.jsxs("h1",{className:"text-2xl font-semibold tracking-tight",children:["Cart",f!==void 0&&f>0&&e.jsxs("span",{className:"ml-2 text-base font-normal text-muted-foreground",children:["(",f," item",f!==1?"s":"",")"]})]})]});return n.length===0?e.jsxs("div",{className:"space-y-6",children:[e.jsx(x,{}),e.jsx(L,{className:"min-w-0 overflow-hidden",children:e.jsxs($,{className:"space-y-4 py-12 text-center",children:[e.jsx(Qn,{className:"mx-auto h-10 w-10 text-muted-foreground/60"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Your cart is empty"}),e.jsxs("div",{className:"flex flex-wrap justify-center gap-3",children:[e.jsx(g,{variant:"outline",onClick:()=>a(t("/events")),children:"Browse events"}),e.jsx(g,{variant:"outline",onClick:()=>a(t("/products")),children:"Browse products"})]})]})})]}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx(x,{count:c}),e.jsx(g,{variant:"ghost",size:"sm",onClick:l,className:"text-muted-foreground",children:"Clear cart"})]}),e.jsx(L,{className:"min-w-0 overflow-hidden",children:e.jsx($,{className:"divide-y p-0",children:n.map((f,b)=>{const N=VP[f.type]||Cr,j=f.autoAddedFor?n.find(k=>k.id===f.autoAddedFor):null,w=f.unitPrice*f.quantity,v=f.type==="product"||f.quantity>1;return e.jsxs("div",{className:"p-4",children:[e.jsxs("div",{className:"flex items-start gap-3 sm:items-center",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg",style:{backgroundColor:"var(--portal-primary-light)",color:"var(--portal-primary)"},children:e.jsx(N,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"font-semibold tracking-tight text-foreground sm:truncate",children:f.name}),f.selectedRoleTypeId&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["as ",f.selectedRoleName??"selected role"," â"," ",f.claimMembershipOffer?"member rate (free membership offer)":"non-member rate"]}),j&&e.jsxs("div",{className:"mt-0.5 text-xs text-muted-foreground",children:["Required for ",j.name]})]}),e.jsxs("div",{className:"hidden shrink-0 items-center gap-3 sm:flex",children:[f.type==="product"?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(O,{type:"number",min:1,max:99,value:f.quantity,onChange:k=>i(f.type,f.id,parseInt(k.target.value)||1),className:"h-8 w-16 text-center"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Ã"}),e.jsx("span",{className:"text-sm",children:Mn(f.unitPrice)})]}):v?e.jsxs("span",{className:"text-sm text-muted-foreground",children:[f.quantity," à ",Mn(f.unitPrice)]}):null,e.jsx("span",{className:"w-20 text-right font-semibold tracking-tight text-foreground",children:Mn(w)})]}),e.jsx("button",{onClick:()=>h(f),className:"shrink-0 rounded-md p-1.5 text-muted-foreground transition-colors hover:bg-red-50 hover:text-red-600 dark:hover:bg-red-950/30","aria-label":"Remove item",children:e.jsx(Ft,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"mt-2 flex items-center justify-between pl-[52px] sm:hidden",children:[f.type==="product"?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(O,{type:"number",min:1,max:99,value:f.quantity,onChange:k=>i(f.type,f.id,parseInt(k.target.value)||1),className:"h-8 w-16 text-center"}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:["à ",Mn(f.unitPrice)]})]}):v?e.jsxs("span",{className:"text-sm text-muted-foreground",children:[f.quantity," à ",Mn(f.unitPrice)]}):e.jsx("span",{}),e.jsx("span",{className:"font-semibold tracking-tight text-foreground",children:Mn(w)})]})]},`${f.type}-${f.id}-${b}`)})})}),e.jsx(L,{className:"min-w-0 overflow-hidden",children:e.jsxs($,{className:"p-5",children:[e.jsxs("div",{className:"mb-4 flex items-center justify-between gap-3",children:[e.jsx("span",{className:"text-base font-semibold tracking-tight text-foreground",children:"Total"}),e.jsx("span",{className:"text-2xl font-semibold tracking-tight text-foreground",children:Mn(m)})]}),e.jsxs(g,{className:"w-full bg-blue-600 font-medium text-white hover:bg-blue-700",size:"lg",onClick:()=>a(t("/checkout")),children:["Proceed to checkout",e.jsx(as,{className:"ml-2 h-4 w-4"})]})]})}),e.jsx(Fe,{open:!!d,onOpenChange:f=>{f||u(null)},children:e.jsxs(Te,{className:"sm:max-w-md",children:[e.jsxs(Ae,{children:[e.jsxs(Ee,{className:"flex items-center gap-2",children:[e.jsx(Bt,{className:"h-5 w-5 text-amber-500"}),"Remove linked events"]}),e.jsx(tt,{children:d?.label})]}),e.jsxs(Ge,{className:"pt-2",children:[e.jsx(g,{type:"button",variant:"outline",onClick:()=>u(null),children:"Cancel"}),e.jsx(g,{type:"button",variant:"destructive",onClick:p,children:"Remove both"})]})]})})]})}
3957function sl(t){return t.toLocaleString("en-US",{style:"currency",currency:"USD"})}function YP({onSuccess:t}){const s=mn(),a=un(),[n,r]=o.useState(!1),[i,l]=o.useState(null),[m,c]=o.useState(!1),[d,u]=o.useState(!1);o.useEffect(()=>{if(m)return;const p=window.setTimeout(()=>u(!0),12e3);return()=>window.clearTimeout(p)},[m]);const h=async p=>{if(p.preventDefault(),!s||!a||!m)return;r(!0),l(null);const x=await s.confirmPayment({elements:a,confirmParams:{return_url:window.location.href},redirect:"if_required"});x.error?(l(x.error.message||"Payment failed"),r(!1)):x.paymentIntent?.status==="succeeded"?t(x.paymentIntent.id):(l("Unexpected payment status"),r(!1))};return e.jsxs("form",{onSubmit:h,className:"space-y-4",children:[e.jsx(hn,{onReady:()=>c(!0),onLoadError:p=>{ix(new Error(`payment element load: ${p.error?.code??p.error?.type??"unknown"}`),{tags:{surface:"portal-checkout",failure:"payment-element-load"},extra:{stripeError:p.error}}),l("The secure payment form could not load. Some workplace networks block payment pages â please try a different network or device.")}}),!m&&d&&!i&&e.jsxs("div",{className:"flex items-center gap-2 text-sm text-amber-700 dark:text-amber-400",children:[e.jsx(Dt,{className:"h-4 w-4 shrink-0"}),"Still loading the secure payment form⦠If this never finishes, your network may be blocking it â try a different network or device."]}),i&&e.jsxs("div",{className:"flex items-center gap-2 text-sm text-red-600",children:[e.jsx(Dt,{className:"h-4 w-4 shrink-0"}),i]}),e.jsx(g,{type:"submit",disabled:!s||!m||n,className:"w-full bg-blue-600 font-medium text-white hover:bg-blue-700",size:"lg",children:n?e.jsxs(e.Fragment,{children:[e.jsx(He,{className:"mr-2 h-4 w-4 animate-spin"}),"Processingâ¦"]}):e.jsxs(e.Fragment,{children:[e.jsx(Ys,{className:"mr-2 h-4 w-4"}),"Pay now"]})})]})}function HP({savedCard:t,onUseSavedCard:s,onUseNewCard:a,isProcessing:n,error:r}){const i={visa:"Visa",mastercard:"Mastercard",amex:"American Express",discover:"Discover"};return e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"rounded-lg border bg-muted/30 p-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex h-10 w-14 shrink-0 items-center justify-center rounded border bg-background",children:e.jsx(Qt,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("p",{className:"truncate font-semibold tracking-tight text-foreground",children:[i[t.brand.toLowerCase()]||t.brand," â¢â¢â¢â¢"," ",t.last4]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Expires ",t.exp_month.toString().padStart(2,"0"),"/",t.exp_year]})]}),e.jsx(Xt,{className:"h-5 w-5 shrink-0 text-emerald-600 dark:text-emerald-400"})]})}),r&&e.jsxs("div",{className:"flex items-center gap-2 text-sm text-red-600 dark:text-red-400",children:[e.jsx(Dt,{className:"h-4 w-4 shrink-0"}),r]}),e.jsx(g,{onClick:s,disabled:n,className:"w-full bg-blue-600 font-medium text-white hover:bg-blue-700",size:"lg",children:n?e.jsxs(e.Fragment,{children:[e.jsx(He,{className:"mr-2 h-4 w-4 animate-spin"}),"Processingâ¦"]}):e.jsxs(e.Fragment,{children:[e.jsx(Ys,{className:"mr-2 h-4 w-4"}),"Pay with saved card"]})}),e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute inset-0 flex items-center",children:e.jsx("span",{className:"w-full border-t"})}),e.jsx("div",{className:"relative flex justify-center text-[10px] font-semibold uppercase tracking-wider",children:e.jsx("span",{className:"bg-card px-2 text-muted-foreground",children:"or"})})]}),e.jsx("button",{type:"button",onClick:a,className:"w-full py-2 text-sm text-muted-foreground transition-colors hover:text-foreground",children:"Use a different payment method"})]})}function JP({onApplied:t,onRemoved:s,appliedCode:a,appliedDiscount:n}){const[r,i]=o.useState(""),[l,m]=o.useState(null),[c,d]=o.useState(!!a),u=x3(),h=()=>{r.trim()&&(m(null),u.mutate({code:r.trim(),scope:"all"},{onSuccess:p=>{p.valid?(t(p),m(null)):m(p.message||"Invalid code")},onError:()=>m("Failed to validate code")}))};return a&&n?e.jsxs("div",{className:"flex items-center justify-between gap-2 rounded-lg border border-emerald-200 bg-emerald-50 px-4 py-3 dark:border-emerald-900/60 dark:bg-emerald-950/30",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx(xa,{
3957className:"h-4 w-4 shrink-0 text-emerald-600 dark:text-emerald-400"}),e.jsx("span",{className:"text-sm font-semibold text-emerald-800 dark:text-emerald-300",children:a}),e.jsxs("span",{className:"truncate text-xs text-emerald-700/85 dark:text-emerald-400/85",children:["â ",n.message]})]}),e.jsx("button",{onClick:s,className:"shrink-0 rounded-md p-1 text-emerald-700 transition-colors hover:bg-emerald-100 dark:text-emerald-400 dark:hover:bg-emerald-900/40",children:e.jsx(ms,{className:"h-4 w-4"})})]}):c?e.jsxs("div",{className:"space-y-2 rounded-lg border bg-card p-4",children:[e.jsxs("p",{className:"flex items-center gap-2 text-sm font-medium",children:[e.jsx(xa,{className:"h-4 w-4 text-blue-600 dark:text-blue-400"}),"Promo code"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(O,{value:r,onChange:p=>i(p.target.value.toUpperCase()),placeholder:"Enter code",autoFocus:!0,className:"font-mono uppercase text-foreground",onKeyDown:p=>p.key==="Enter"&&(p.preventDefault(),h())}),e.jsx(g,{type:"button",variant:"outline",onClick:h,disabled:u.isPending||!r.trim(),className:"shrink-0",children:u.isPending?"Checkingâ¦":"Apply"})]}),l&&e.jsx("p",{className:"text-sm text-red-600 dark:text-red-400",children:l})]}):e.jsxs("button",{type:"button",onClick:()=>d(!0),className:"flex w-full items-center justify-between gap-2 rounded-lg border border-dashed border-blue-300 bg-blue-50/60 px-4 py-3 text-left transition-colors hover:border-blue-400 hover:bg-blue-50 dark:border-blue-800 dark:bg-blue-950/20 dark:hover:border-blue-700 dark:hover:bg-blue-950/40",children:[e.jsxs("span",{className:"flex items-center gap-2 text-sm font-medium text-blue-700 dark:text-blue-300",children:[e.jsx(xa,{className:"h-4 w-4"}),"Have a promo code?"]}),e.jsx("span",{className:"text-sm font-semibold text-blue-600 dark:text-blue-400",children:"Add"})]})}function ZP(){const t=us(),{data:s}=Qa(),a=kt(),{items:n,clearCart:r}=_i(),i=Xf(),l=ey(),m=ty(),[c,d]=o.useState(null),[u,h]=o.useState(null),[p,x]=o.useState(null),[f,b]=o.useState(!1),[N,j]=o.useState(!0),[w,v]=o.useState(null),[k,S]=o.useState(!1),[_,y]=o.useState(null),[C,P]=o.useState(null),A=z=>{const ae=n.map(ue=>({type:ue.type,id:ue.id,name:ue.name,unit_price:ue.unitPrice,quantity:ue.quantity,campaign_id:ue.campaignId,form_responses:ue.formResponses||void 0,selected_role_type_id:ue.selectedRoleTypeId??null,claim_membership_offer:ue.claimMembershipOffer??!1,auto_renew_opt_in:ue.type==="membership_renewal"?ue.autoRenewOptIn??!0:void 0}));h(null),d(null),x(null),i.mutate({items:ae,promoCode:z||void 0},{onSuccess:ue=>{if(ue.free_order||ue.already_paid){r(),a(t(`/checkout/success?order_id=${ue.order_id}`));return}h(ue),ue.publishable_key&&d(rd(ue.publishable_key)),j(!!ue.saved_payment_method)},onError:ue=>{const _e=ue?.response;x(_e?.data?.detail||"Failed to create checkout session")}})};o.useEffect(()=>{if(n.length===0){a(t("/cart"));return}let z=!1;return queueMicrotask(()=>{z||A()}),()=>{z=!0}},[]);const E=z=>{y(z.code||null),P(z),A(z.code||void 0)},Q=()=>{y(null),P(null),A()},U=async z=>{if(u){b(!0);try{const ae=await l.mutateAsync({orderId:u.order_id,paymentIntentId:z});try{sessionStorage.setItem(`ams_confirm_${u.order_id}`,JSON.stringify(ae))}catch{}r(),a(t(`/checkout/success?order_id=${u.order_id}`))}catch(ae){const ue=ae?.response;x(ue?.data?.detail||"Payment confirmed but order processing failed"),b(!1)}}},D=async()=>{if(u){S(!0),v(null);try{const z=await m.mutateAsync(u.order_id);try{sessionStorage.setItem(`ams_confirm_${u.order_id}`,JSON.stringify(z))}catch{}r(),a(t(`/checkout/success?order_id=${u.order_id}`))}catch(z){const ae=z?.response;v(ae?.data?.detail||"Payment failed. Please try again or use a different card."),S(!1)}}};if(s&&s.feature_modules?.commerce_enabled===!1)return e.jsx(_t,{to:t("/dashboard"),replace:!0});const K=()=>e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg",style:{backgroundColor:"var(--portal-primary-light)",color:"var(--portal-primary)"},children:e.jsx(Ys,{className:"h-5 w-5"})}),e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:"Checkout"})]});if(p)return e.jsxs("div",{className:"space-y-6",children:[e.jsx(K,{}),e.jsx(L,{className:"min-w-0 overflow-hidden",children:e.jsxs($,{className:"space-y-3 py-12 text-center",children:[e.jsx(Dt,{className:"mx-auto h-10 w-10 text-red-500/80"}),e.jsx("p",{className:"text-sm text-red-600 dark:text-red-400",children:p}),e.jsx(g,{className:"bg-blue-600 font-medium text-white hover:bg-blue-700",onClick:()=>A(_??void 0),children:"Try again"}),e.jsxs(g,{variant:"outline",onClick:()=>a(t("/cart")),children:[e.jsx(es,{className:"mr-2 h-4 w-4"}),"Back to cart"]})]})})]});if(!u||!c)return e.jsxs("div",{className:"space-y-6",children:[e.jsx(K,{}),e.jsx(L,{className:"min-w-0 overflow-hidden",children:e.jsx($,{className:"flex justify-center py-12",children:e.jsx(He,{className:"h-8 w-8 animate-spin text-muted-foreground"})})})]});if(f)return e.jsxs("div",{className:"space-y-6",children:[e.jsx(K,{}),e.jsx(L,{className:"min-w-0 overflow-hidden",children:e.jsxs($,{className:"space-y-3 py-12 text-center",children:[e.jsx(He,{className:"mx-auto h-8 w-8 animate-spin text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Confirming your orderâ¦"})]})})]});const xe=!!u.saved_payment_method;return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("button",{onClick:()=>a(t("/cart")),className:"inline-flex items-center gap-1.5 text-sm font-medium text-muted-foreground transition-colors hover:text-foreground",children:[e.jsx(es,{className:"h-4 w-4"}),"Back to cart"]}),e.jsx(K,{}),e.jsxs("div",{className:"grid gap-4 lg:grid-cols-3",children:[e.jsx("div",{className:"lg:col-span-2",children:e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex items-center gap-2.5",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg",style:{backgroundColor:"var(--portal-primary-light)",color:"var(--portal-primary)"},children:e.jsx(Qt,{className:"h-4 w-4"})}),"Payment"]})}),e.jsx($,{children:xe&&N?e.jsx(HP,{savedCard:u.saved_payment_method,onUseSavedCard:D,onUseNewCard:()=>j(!1),isProcessing:k,error:w}):e.jsxs("div",{className:"space-y-4",children:[xe&&e.jsxs("button",{type:"button",onClick:()=>j(!0),className:"mb-2 inline-flex w-full items-center justify-center gap-1 py-2 text-sm font-medium text-blue-600 hover:text-blue-700 dark:text-blue-400 dark:hover:text-blue-300",children:["â Use saved card (",u.saved_payment_method.brand," â¢â¢â¢â¢"," ",u.saved_payment_method.last4,")"]}),e.jsx(dn,{stripe:c,options:{clientSecret:u.client_secret,appearance:{theme:"stripe"}},children:e.jsx(YP,{orderId:u.order_id,onSuccess:U})})]})})]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex items-center gap-2.5",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg",style:{backgroundColor:"var(--portal-primary-light)",color:"var(--portal-primary)"},children:e.jsx(ii,{className:"h-4 w-4"})}),"Order summary"]})}),e.jsxs($,{className:"space-y-3",children:[u.line_items.map(z=>e.jsxs("div",{className:"flex justify-between gap-2 text-sm",children:[e.jsxs("span",{className:"min-w-0 truncate text-muted-foreground",children:[z.item_name,z.quantity>1&&` à ${z.quantity}`]}),e.jsx("span",{className:"shrink-0 font-medium",children:sl(z.total_price)})]},z.id)),u.discount_amount>0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex justify-between border-t pt-3 text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Subtotal"}),e.jsx("span",{children:sl(u.subtotal_cents/100)})]}),e.jsxs("div",{className:"flex justify-between text-sm text-emerald-700 dark:text-emerald-400",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(xa,{
3957className:"h-3.5 w-3.5"}),u.promo_code]}),e.jsxs("span",{children:["â",sl(u.discount_amount)]})]})]}),e.jsxs("div",{className:"flex justify-between border-t pt-3",children:[e.jsx("span",{className:"font-semibold tracking-tight",children:"Total"}),e.jsx("span",{className:"text-lg font-semibold tracking-tight",children:sl(u.total_cents/100)})]})]})]}),e.jsx(JP,{onApplied:E,onRemoved:Q,appliedCode:_,appliedDiscount:C})]})]})]})}const XP={event:"Event",product:"Product",donation:"Donation"};function sc(t){return t.toLocaleString("en-US",{style:"currency",currency:"USD"})}function eA(){const t=us(),[s]=ws(),a=s.get("order_id"),{data:n,isLoading:r}=f3(a||void 0),{data:i}=ar(),l=o.useMemo(()=>{if(!a)return null;try{const b=sessionStorage.getItem(`ams_confirm_${a}`);return b?JSON.parse(b):null}catch{return null}},[a]),m=o.useMemo(()=>(l?.registrations??[]).filter(b=>b.grant_action==="upgraded"),[l]),c=m.length>0,d=i?.society_name??"the society",u=l?.renewal??null,h=o.useMemo(()=>{const b=m.map(N=>N.offer_months_granted).filter(N=>typeof N=="number");return b.length>0?Math.max(...b):null},[m]),p=h==null?"free":h===12?"1-year":`${h}-month`,x=h==null||h===12?"You'll receive a renewal reminder before your year is up.":`You'll receive a renewal reminder before your ${h}-month term is up.`,f=async()=>{if(a)try{const b=await Zs.downloadOrderReceipt(a),N=window.URL.createObjectURL(b),j=document.createElement("a");j.href=N,j.download=`receipt-${n?.order_id_short||a.slice(0,8)}.pdf`,j.click(),window.URL.revokeObjectURL(N)}catch{}};return e.jsxs("div",{className:"mx-auto mt-8 max-w-lg space-y-4",children:[c&&e.jsxs("div",{role:"status",className:"flex items-start gap-3 rounded-md border border-portal-primary/20 bg-portal-primary/5 p-4",children:[e.jsx("span",{className:"grid h-9 w-9 shrink-0 place-items-center rounded-md bg-portal-primary/15 text-portal-primary",children:e.jsx(ci,{className:"h-5 w-5"})}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("p",{className:"font-semibold tracking-tight",children:["Welcome to ",d," â your ",p," membership is active."]}),e.jsxs("p",{className:"mt-1 text-sm text-muted-foreground",children:["A welcome email is on its way. ",x]})]})]}),u&&u.action==="applied"&&e.jsxs("div",{role:"status",className:"flex items-start gap-3 rounded-md border border-portal-primary/20 bg-portal-primary/5 p-4",children:[e.jsx("span",{className:"grid h-9 w-9 shrink-0 place-items-center rounded-md bg-portal-primary/15 text-portal-primary",children:e.jsx(St,{className:"h-5 w-5"})}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("p",{className:"font-semibold tracking-tight",children:["Welcome back! Your ",u.membership_type_name," membership is active",u.new_membership_end_date&&e.jsxs(e.Fragment,{children:[" ","through ",Be(pt(u.new_membership_end_date),"MMM d, yyyy")]}),"."]}),u.auto_renew?e.jsxs("p",{className:"mt-1 text-sm text-muted-foreground",children:["Auto-renew is enabled â we'll charge"," ",u.amount_charged>0?`$${Number(u.amount_charged).toFixed(2)}`:"your dues","/yr automatically each year. You can turn it off anytime."]}):e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"Auto-renew is disabled. You'll receive a renewal reminder before your membership expires."})]})]}),u&&u.action==="skipped"&&u.auto_refunded&&e.jsxs("div",{role:"status",className:"flex items-start gap-3 rounded-md border border-amber-200 bg-amber-50/60 p-4 dark:border-amber-700/40 dark:bg-amber-900/20",children:[e.jsx("span",{className:"grid h-9 w-9 shrink-0 place-items-center rounded-md bg-amber-100 text-amber-700 dark:bg-amber-800/40 dark:text-amber-400",children:e.jsx(St,{className:"h-5 w-5"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"font-semibold tracking-tight",children:"Renewal refunded"}),e.jsxs("p",{className:"mt-1 text-sm text-muted-foreground",children:["We refunded your $",Number(u.amount_charged).toFixed(2)," renewal â your existing ",u.membership_type_name," membership already covers this period",u.new_membership_end_date&&e.jsxs(e.Fragment,{children:[" ","through ",Be(pt(u.new_membership_end_date),"MMM d, yyyy")]}),"."]})]})]}),e.jsx(L,{className:"min-w-0 overflow-hidden",children:e.jsxs($,{className:"space-y-5 py-10",children:[e.jsxs("div",{className:"space-y-3 text-center",children:[e.jsx("div",{className:"mx-auto flex h-16 w-16 items-center justify-center rounded-full bg-emerald-100 dark:bg-emerald-900/30",children:e.jsx(vn,{className:"h-10 w-10 text-emerald-600 dark:text-emerald-400"})}),e.jsx("h1",{className:"text-2xl font-semibold tracking-tight text-foreground",children:"Payment successful"}),e.jsx("p",{className:"text-sm leading-relaxed text-muted-foreground",children:"Your order has been confirmed. You will receive a receipt via email."})]}),a&&(r?e.jsxs("div",{className:"space-y-2 pt-2",children:[e.jsx(Y,{className:"h-8 w-full"}),e.jsx(Y,{className:"h-8 w-full"})]}
3957):n?e.jsxs("div",{className:"space-y-3 pt-2",children:[e.jsxs("div",{className:"text-center text-[11px] font-semibold uppercase tracking-wider text-muted-foreground",children:["Order #",n.order_id_short]}),e.jsx("div",{className:"divide-y rounded-md border bg-muted/20",children:n.line_items.map((b,N)=>e.jsxs("div",{className:"flex items-center justify-between gap-3 p-3 text-sm",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate font-medium text-foreground",children:b.item_name}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[XP[b.item_type]||b.item_type,b.quantity>1&&` à ${b.quantity}`]})]}),e.jsx("span",{className:"shrink-0 font-semibold text-foreground",children:sc(b.total_price)})]},N))}),n.discount_amount>0&&e.jsxs("div",{className:"text-right text-sm text-emerald-700 dark:text-emerald-400",children:["Discount",n.promo_code?` (${n.promo_code})`:"",": â",sc(n.discount_amount)]}),e.jsxs("div",{className:"text-right text-base font-semibold tracking-tight text-foreground",children:["Total: ",sc(n.total)]})]}):e.jsxs("p",{className:"text-center text-xs text-muted-foreground",children:["Order ID: ",a]})),e.jsxs("div",{className:"flex flex-col justify-center gap-2 pt-2 sm:flex-row",children:[n?.has_receipt&&e.jsxs(g,{className:"bg-blue-600 font-medium text-white hover:bg-blue-700",onClick:f,children:[e.jsx(vs,{className:"mr-1.5 h-4 w-4"}),"Download receipt"]}),e.jsx(g,{asChild:!0,variant:"outline",className:"font-medium",children:e.jsx(je,{to:t("/orders"),children:"View order history"})}),e.jsx(g,{asChild:!0,variant:"outline",className:"font-medium",children:e.jsx(je,{to:t("/dashboard"),children:"Go to dashboard"})})]})]})})]})}function Ju(){const t=qs(),s=us(),[a,n]=o.useState(""),[r,i]=o.useState(!1),[l,m]=o.useState(!1),[c,d]=o.useState("");if(!t)return e.jsxs(Oa,{children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight text-foreground",children:"Invalid portal link"}),e.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"Please check your URL and try again."})]});const u=async h=>{h.preventDefault(),d(""),i(!0);try{await Me.post("/portal/forgot-password",{email:a,society_slug:t}),m(!0)}catch{d("Something went wrong. Please try again.")}finally{i(!1)}};return e.jsx(Oa,{children:l?e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"mx-auto mb-5 flex size-12 items-center justify-center rounded-full bg-emerald-50 dark:bg-emerald-500/15",children:e.jsx(Kt,{className:"size-6 text-emerald-500 dark:text-emerald-400"})}),e.jsx("h1",{className:"text-2xl font-semibold tracking-tight text-foreground",children:"Check your email"}),e.jsx("p",{className:"mt-3 text-sm leading-relaxed text-muted-foreground",children:"If an account with that email exists, we've emailed a link to get you back into your account. Please check your inbox (and spam folder)."}),e.jsx(je,{to:s("/login"),className:"mt-6 inline-block text-sm font-medium hover:underline",style:{color:"var(--portal-primary)"},children:"Back to login"})]}):e.jsxs(e.Fragment,{children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight text-foreground",children:"Reset your password"}),e.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"Enter your email and we'll send you a link to reset your password â or a sign-in link if your account doesn't use one."}),c&&e.jsx("div",{className:"mt-6 rounded-lg border border-destructive/30 bg-destructive/5 px-4 py-3",children:e.jsx("p",{className:"text-sm text-destructive",children:c})}),e.jsxs("form",{onSubmit:u,className:"mt-8 space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"email",className:"text-sm font-medium",children:"Email"}),e.jsxs("div",{className:"relative",children:[e.jsx($t,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(O,{id:"email",type:"email",placeholder:"[email protected]",value:a,onChange:h=>n(h.target.value),required:!0,autoComplete:"email",className:"h-11 pl-10"})]})]}),e.jsx(g,{type:"submit",variant:"ghost",className:"h-11 w-full font-medium transition-all hover:opacity-90",disabled:r,style:{backgroundColor:"var(--portal-primary)",color:"var(--portal-primary-fg)"},children:r?"Sendingâ¦":"Send reset link"})]}),e.jsxs("p",{className:"mt-8 text-center text-sm text-muted-foreground",children:["Remember your password?"," ",e.jsx(je,{to:s("/login"),
3957className:"font-medium transition-colors hover:underline",style:{color:"var(--portal-primary)"},children:"Sign in"})]})]})})}function Zu(){const t=qs(),s=us(),a=kt(),[n]=ws(),r=n.get("token"),[i,l]=o.useState(""),[m,c]=o.useState(""),[d,u]=o.useState(!1),[h,p]=o.useState("");if(!t)return e.jsxs(Oa,{children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight text-foreground",children:"Invalid portal link"}),e.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"Please check your URL and try again."})]});if(!r)return e.jsxs(Oa,{children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight text-foreground",children:"Invalid link"}),e.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"This password reset link is invalid or has expired."}),e.jsx(je,{to:s("/forgot-password"),className:"mt-6 inline-block text-sm font-medium hover:underline",style:{color:"var(--portal-primary)"},children:"Request a new reset link"})]});const x=async f=>{if(f.preventDefault(),p(""),i!==m){p("Passwords do not match");return}if(i.length<8){p("Password must be at least 8 characters");return}u(!0);try{await Me.post("/portal/reset-password",{token:r,new_password:i}),a(s("/login?reset=success"),{replace:!0})}catch(b){const N=b?.response;N?.data?.detail?p(N.data.detail):p("Failed to reset password. The link may have expired.")}finally{u(!1)}};return e.jsxs(Oa,{children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight text-foreground",children:"Choose a new password"}),e.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"Pick something at least 8 characters long."}),h&&e.jsx("div",{className:"mt-6 rounded-lg border border-destructive/30 bg-destructive/5 px-4 py-3",children:e.jsx("p",{className:"text-sm text-destructive",children:h})}),e.jsxs("form",{onSubmit:x,className:"mt-8 space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"new_password",className:"text-sm font-medium",children:"New password"}),e.jsxs("div",{className:"relative",children:[e.jsx(Ys,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(O,{id:"new_password",type:"password",value:i,onChange:f=>l(f.target.value),required:!0,minLength:8,autoComplete:"new-password",className:"h-11 pl-10"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"confirm_password",className:"text-sm font-medium",children:"Confirm password"}),e.jsxs("div",{className:"relative",children:[e.jsx(Ys,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(O,{id:"confirm_password",type:"password",value:m,onChange:f=>c(f.target.value),required:!0,minLength:8,autoComplete:"new-password",className:"h-11 pl-10"})]})]}),e.jsx(g,{type:"submit",variant:"ghost",className:"h-11 w-full font-medium transition-all hover:opacity-90",disabled:d,style:{backgroundColor:"var(--portal-primary)",color:"var(--portal-primary-fg)"},children:d?"Resettingâ¦":"Reset password"})]})]})}function Xu(){const t=qs(),s=us(),[a]=ws(),n=a.get("token"),{data:r}=ma(t||void 0),i=Si(r?.society?.primary_color);Ra(r?.society?.favicon_url);const[l,m]=o.useState("loading"),[c,d]=o.useState("");return o.useEffect(()=>{if(!n){m("error"),d("Invalid verification link. No token provided.");return}(async()=>{try{const h=await Me.post("/portal/verify-email-change",{token:n});m("success"),d(h.data.message||"Email address updated successfully.")}catch(h){m("error"),d(h?.response?.data?.detail||"Failed to verify email change. The link may have expired.")}})()},[n]),e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background px-4",style:i,children:e.jsxs(L,{className:"w-full max-w-md",children:[e.jsxs(ne,{className:"space-y-1 text-center",children:[e.jsxs(ie,{className:"flex items-center justify-center gap-2.5 text-2xl font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg",style:{backgroundColor:"var(--portal-primary-light)",color:"var(--portal-primary)"},children:e.jsx($t,{className:"h-4 w-4"})}),"Email verification"]}),e.jsxs(Ci,{children:[l==="loading"&&"Verifying your new email addressâ¦",l==="success"&&"Your email has been updated",l==="error"&&"Verification failed"]})]}),e.jsxs($,{children:[l==="loading"&&e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-b-2 border-foreground"})}),l==="success"&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"rounded-md border border-emerald-200 bg-emerald-50 p-3 text-sm text-emerald-800 dark:border-emerald-900/60 dark:bg-emerald-950/30 dark:text-emerald-300",children:c}),e.jsx("p",{className:"text-center text-sm text-muted-foreground",children:e.jsx(je,{to:s("/login"),
3957className:"font-medium hover:underline",style:{color:"var(--portal-primary)"},children:"Go to login"})})]}),l==="error"&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"rounded-md bg-destructive/10 p-3 text-sm text-destructive",children:c}),e.jsx("p",{className:"text-center text-sm text-muted-foreground",children:e.jsx(je,{to:s("/profile"),className:"font-medium hover:underline",style:{color:"var(--portal-primary)"},children:"Back to profile"})})]})]})]})})}function eh(){const t=qs(),{isResolving:s,isCustomDomain:a}=da(),n=us(),r=kt(),[i]=ws(),l=i.get("token"),m=i.get("redirect"),{loginWithMember:c}=ft(),[d,u]=o.useState("verifying"),[h,p]=o.useState(""),x=o.useRef(null),[f,b]=o.useState(""),[N,j]=o.useState("idle"),[w,v]=o.useState(""),k=async S=>{if(S.preventDefault(),!(!t||!f.trim()||N==="sending")){j("sending"),v("");try{await Me.post("/portal/magic-link",{email:f.trim(),society_slug:t}),j("sent")}catch(_){const y=_?.response?.status;j("idle"),v(y===429?"Too many requests â please wait a minute and try again.":"We couldn't send the link right now. Please try again.")}}};return o.useEffect(()=>{if(a&&s)return;if(!l||!t){u("error"),p("Invalid or expired link");return}const S=`${t}:${l}`;if(x.current===S)return;x.current=S,u("verifying"),p(""),(async()=>{try{const y=await Me.post("/portal/verify-magic-link",{token:l,society_slug:t}),{member:C,csrf_token:P}=y.data;c(C,t,P),u("success");const A=C.has_password===!1,E=m&&m.startsWith("/")?m:null,Q=A?`${n("/set-password")}${E?`?redirect=${encodeURIComponent(E)}`:""}`:n(E||"/dashboard");setTimeout(()=>{r(Q,{replace:!0})},1500)}catch(y){const C=px(y);if(C){r(n("/complete-payment"),{replace:!0,state:{resumeToken:C}});return}u("error");const P=y?.response?.data?.detail;p(typeof P=="string"?P:"This link is invalid or has expired.")}})()},[l,t,r,c,a,s,n,m]),t?e.jsxs(Oa,{children:[d==="verifying"&&e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"mx-auto mb-6 flex h-16 w-16 items-center justify-center rounded-full",style:{backgroundColor:"var(--portal-primary-light)"},children:e.jsx(He,{className:"h-8 w-8 animate-spin",style:{color:"var(--portal-primary)"}})}),e.jsx("h1",{className:"text-2xl font-semibold tracking-tight text-foreground",children:"Verifying your linkâ¦"}),e.jsx("p",{className:"mt-3 text-sm text-muted-foreground",children:"Please wait while we sign you in."})]}),d==="success"&&e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"mx-auto mb-6 flex h-16 w-16 items-center justify-center rounded-full bg-emerald-50 dark:bg-emerald-500/15",children:e.jsx(Kt,{className:"h-8 w-8 text-emerald-500 dark:text-emerald-400"})}),e.jsx("h1",{className:"text-2xl font-semibold tracking-tight text-foreground",children:"Welcome back"}),e.jsx("p",{className:"mt-3 text-sm text-muted-foreground",children:"Signing you inâ¦"})]}),d==="error"&&e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"mx-auto mb-6 flex h-16 w-16 items-center justify-center rounded-full bg-destructive/10",children:e.jsx(Ca,{className:"h-8 w-8 text-destructive"})}),e.jsx("h1",{className:"text-2xl font-semibold tracking-tight text-foreground",children:"Link invali
3957d"}),e.jsx("p",{className:"mt-3 text-sm leading-relaxed text-muted-foreground",children:h}),N==="sent"?e.jsx("p",{className:"mt-6 text-sm leading-relaxed text-muted-foreground",children:"If an account with that email exists, a new sign-in link is on its way. It stays valid for 4 hours."}):e.jsxs("form",{onSubmit:S=>{k(S)},className:"mt-6 space-y-3 text-left",children:[e.jsx("label",{htmlFor:"rerequest-email",className:"block text-sm font-medium text-foreground",children:"Get a new sign-in link"}),e.jsx("input",{id:"rerequest-email",type:"email",required:!0,value:f,onChange:S=>b(S.target.value),placeholder:"[email protected]",className:"w-full rounded-lg border border-input bg-background px-3 py-2.5 text-sm text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring"}),w&&e.jsx("p",{className:"text-sm text-destructive",children:w}),e.jsx("button",{type:"submit",disabled:N==="sending",className:"inline-flex w-full items-center justify-center rounded-lg px-6 py-2.5 text-sm font-medium transition-colors disabled:opacity-60",style:{backgroundColor:"var(--portal-primary)",color:"var(--portal-primary-fg)"},children:N==="sending"?"Sendingâ¦":"Email me a new link"})]}),e.jsx(je,{to:n("/login"),className:"mt-4 inline-block text-sm font-medium text-muted-foreground underline-offset-4 hover:underline",children:"Back to login"})]})]}):e.jsxs(Oa,{children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight text-foreground",children:"Invalid portal link"}),e.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"Please check your URL and try again."})]})}function th(){const t=us(),s=kt(),[a]=ws(),n=a.get("redirect"),{member:r,markPasswordSet:i}=ft(),[l,m]=o.useState(""),[c,d]=o.useState(""),[u,h]=o.useState(""),[p,x]=o.useState(!1),f=async b=>{if(b.preventDefault(),h(""),l.length<8){h("Password must be at least 8 characters.");return}if(!/[A-Z]/.test(l)){h("Password must contain at least one uppercase letter.");return}if(!/[a-z]/.test(l)){h("Password must contain at least one lowercase letter.");return}if(!/\d/.test(l)){h("Password must contain at least one digit.");return}if(l!==c){h("Passwords do not match.");return}x(!0);try{await gt.setPassword(l),i();const N=n&&n.startsWith("/")?t(n):t("/dashboard");s(N,{replace:!0})}catch(N){const j=N?.response;h(j?.data?.detail||"Failed to set password. Please try again.")}finally{x(!1)}};return e.jsxs(Oa,{children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight text-foreground",children:"Create your password"}),e.jsxs("p",{className:"mt-2 text-sm text-muted-foreground",children:[r?.first_name?`Welcome, ${r.first_name}. `:"","Set a password so you can sign in anytime."]}),u&&e.jsx("div",{className:"mt-6 rounded-lg border border-destructive/30 bg-destructive/5 px-4 py-3",children:e.jsx("p",{className:"text-sm text-destructive",children:u})}),e.jsxs("form",{onSubmit:f,className:"mt-8 space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"new-password",className:"text-sm font-medium",children:"Password"}),e.jsxs("div",{className:"relative",children:[e.jsx(Ys,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(O,{id:"new-password",type:"password",value:l,onChange:b=>m(b.target.value),required:!0,minLength:8,autoComplete:"new-password",autoFocus:!0,placeholder:"At least 8 characters",className:"h-11 pl-10"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"confirm-password",className:"text-sm font-medium",children:"Confirm password"}),e.jsxs("div",{className:"relative",children:[e.jsx(Ys,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(O,{id:"confirm-password",type:"password",value:c,onChange:b=>d(b.target.value),required:!0,minLength:8,autoComplete:"new-password",placeholder:"Re-enter your password",className:"h-11 pl-10"})]})]}),e.jsx("p",{className:"text-xs leading-relaxed text-muted-foreground",children:"Must be 8+ characters with at least one uppercase letter, one lowercase letter, and one number."}),e.jsx(g,{type:"submit",variant:"ghost",className:"h-11 w-full font-medium transition-all hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-50",disabled:p,style:{backgroundColor:"var(--portal-primary)",color:"var(--portal-primary-fg)"},children:p?e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(He,{className:"h-4 w-4 animate-spin"}),"Creatingâ¦"]}):"Create password and continue"})]})]})}const ti={chair:"Chair",vice_chair:"Vice Chair",secretary:"Secretary",treasurer:"Treasurer",member:"Member"},ur={chair:"bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400",vice_chair:"bg-indigo-100 text-indigo-700 dark:bg-indigo-900/30 dark:text-indigo-400",secretary:"bg-purple-100 text-purple-700 dark:bg-purple-900/30 dark:text-purple-400",treasurer:"bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400",member:"bg-muted text-muted-foreground"},sh={pending:"bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400",accepted:"bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400",rejected:"bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400",withdrawn:"bg-muted text-muted-foreground"};function tA(){const t=us(),{data:s}=Qa();if(s&&s.feature_modules?.committees_enabled===!1)return e.jsx(_t,{to:t("/dashboard"),replace:!0});const{data:a,isLoading:n}=N3(),{data:r,isLoading:i}=sy(),{data:l,isLoading:m}=ay(),{data:c}
3957=S3(),d=k3(),u=_3(),[h,p]=o.useState(null),[x,f]=o.useState(""),[b,N]=o.useState(null),j=new Set(r?.map(y=>y.id)||[]),w=new Map(r?.map(y=>[y.id,y])||[]),v=l?.find(y=>y.id===h),k=async()=>{if(h)try{await d.mutateAsync({opening_id:h,message:x||null}),p(null),f("")}catch{}},S=async y=>{try{await u.mutateAsync(y)}catch{}},_=async y=>{try{const C=await Me.get(`/portal/committees/${y}/meeting.ics`,{responseType:"blob"}),P=window.URL.createObjectURL(C.data),A=document.createElement("a");A.href=P,A.download="meeting.ics",A.click(),window.URL.revokeObjectURL(P)}catch{}};return n||i||m?e.jsxs("div",{className:"space-y-4",children:[e.jsx(Y,{className:"h-8 w-48"}),e.jsx("div",{className:"grid gap-4 sm:grid-cols-2",children:[1,2,3,4].map(y=>e.jsx(Y,{className:"h-28"},y))})]}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg",style:{backgroundColor:"var(--portal-primary-light)",color:"var(--portal-primary)"},children:e.jsx(Kn,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:"Committees"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Active committees in your society"})]})]}),l&&l.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("h2",{className:"flex min-w-0 items-center gap-2.5 text-lg font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg",style:{backgroundColor:"var(--portal-primary-light)",color:"var(--portal-primary)"},children:e.jsx(Gl,{className:"h-4 w-4"})}),"Open Positions"]}),e.jsx("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-2",children:l.map(y=>e.jsx(L,{className:"min-w-0 overflow-hidden transition-shadow hover:shadow-sm",children:e.jsx($,{className:"p-4",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("h3",{className:"truncate text-sm font-semibold tracking-tight text-foreground",children:y.title}),e.jsx("p",{className:"mt-0.5 truncate text-xs text-muted-foreground",children:y.committee_name}),y.description&&e.jsx("p",{className:"mt-1.5 line-clamp-2 text-xs leading-relaxed text-muted-foreground",children:y.description}),e.jsx("div",{className:"mt-2.5",children:e.jsx("span",{className:`inline-flex items-center rounded-full px-2 py-0.5 text-[11px] font-medium ${ur[y.role]||ur.member}`,children:ti[y.role]||y.role})})]}),e.jsx("div",{className:"shrink-0",children:y.has_applied?e.jsx("span",{className:"inline-flex items-center rounded-full bg-amber-100 px-2.5 py-1 text-[11px] font-medium text-amber-700 dark:bg-amber-900/30 dark:text-amber-400",children:"Applied"}):e.jsx(g,{size:"sm",className:"bg-blue-600 font-medium text-white hover:bg-blue-700",onClick:()=>{p(y.id),f("")},children:"Apply"})})]})})},y.id))})]}),c&&c.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("h2",{className:"text-lg font-semibold tracking-tight",children:"My applications"}),e.jsx("div",{className:"space-y-2",children:c.map(y=>e.jsx(L,{className:"min-w-0 overflow-hidden",children:e.jsx($,{className:"p-4",children:e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"truncate text-sm font-semibold tracking-tight text-foreground",children:y.title}),e.jsxs("p",{className:"truncate text-xs text-muted-foreground",children:[y.committee_name," · ",ti[y.role]||y.role]})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[e.jsx("span",{className:`inline-flex items-center rounded-full px-2.5 py-0.5 text-[11px] font-medium capitalize ${sh[y.status]||sh.pending}`,children:y.status}),y.status==="pending"&&e.jsx(g,{size:"sm",variant:"outline",className:"h-7 text-xs text-muted-foreground",onClick:()=>S(y.id),disabled:u.isPending,children:"Withdraw"})]})]})})},y.id))})]}),!a||a.length===0?e.jsx(L,{className:"min-w-0 overflow-hidden",children:e.jsxs($,{className:"p-8 text-center",children:[e.jsx(Kn,{className:"mx-auto mb-3 h-10 w-10 text-muted-foreground
3957/60"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No active committees at this time."})]})}):e.jsxs("div",{children:[e.jsx("h2",{className:"mb-3 text-lg font-semibold tracking-tight",children:"All committees"}),e.jsx("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2",children:a.map(y=>{const C=j.has(y.id),P=w.get(y.id)?.role,A=b===y.id,E=y.next_meeting_date?new Date(y.next_meeting_date+"T00:00:00"):null;return e.jsx(L,{className:`min-w-0 overflow-hidden transition-shadow hover:shadow-sm ${C?"ring-2 ring-offset-2":""}`,style:C?{borderColor:"color-mix(in oklab, var(--portal-primary) 30%, transparent)",backgroundColor:"color-mix(in oklab, var(--portal-primary-light) 50%, transparent)","--tw-ring-color":"color-mix(in oklab, var(--portal-primary) 35%, transparent)","--tw-ring-offset-color":"var(--background)"}:void 0,children:e.jsxs($,{className:"p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("h3",{className:"truncate text-sm font-semibold tracking-tight text-foreground",children:y.name}),y.description&&e.jsx("p",{className:"mt-1 line-clamp-2 text-xs leading-relaxed text-muted-foreground",children:y.description}),e.jsxs("button",{type:"button",className:"mt-2 flex items-center gap-1 text-xs text-muted-foreground transition-colors hover:text-foreground",onClick:()=>N(A?null:y.id),children:[y.member_count," member",y.member_count!==1?"s":"",A?e.jsx(Gn,{className:"h-3 w-3"}):e.jsx(ps,{className:"h-3 w-3"})]})]}),e.jsxs("div",{className:"flex shrink-0 flex-col items-end gap-1.5",children:[C&&P&&e.jsx("span",{className:`inline-flex items-center rounded-full px-2.5 py-0.5 text-[11px] font-medium ${ur[P]||ur.member}`,children:ti[P]||P}),C&&y.chat_link&&e.jsxs("a",{href:y.chat_link,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 rounded-full bg-emerald-100 px-2.5 py-0.5 text-[11px] font-medium text-emerald-700 transition-colors hover:bg-emerald-200 dark:bg-emerald-900/30 dark:text-emerald-400 dark:hover:bg-emerald-900/50",children:[e.jsx(Gc,{className:"h-3 w-3"}),"Group chat"]})]})]}),E&&e.jsxs("div",{className:"mt-3 border-t border-border pt-3",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-sm text-muted-foreground",children:[e.jsx(Yt,{className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsxs("span",{children:["Next meeting:"," ",E.toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"}),y.next_meeting_time&&` at ${y.next_meeting_time}`]})]}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[e.jsxs(g,{type:"button",size:"sm",variant:"outline",className:"h-7 text-xs",onClick:()=>_(y.id),children:[e.jsx(Yt,{className:"mr-1 h-3 w-3"}),"Add to calendar"]}),y.meeting_link&&e.jsxs("a",{href:y.meeting_link,target:"_blank",rel:"noopener noreferrer",className:"inline-flex h-7 items-center gap-1 rounded-md border border-border px-2.5 text-xs font-medium text-foreground transition-colors hover:bg-muted",children:[e.jsx(Kp,{className:"h-3 w-3"}),"Join meeting"]})]})]}),A&&y.members&&y.members.length>0&&e.jsxs("div",{className:"mt-3 border-t border-border pt-3",children:[e.jsx("p",{className:"mb-2 text-[10px] font-semibold uppercase tracking-wider text-muted-foreground",children:"Members"}),e.jsx("div",{className:"space-y-1.5",children:y.members.map((Q,U)=>e.jsxs("div",{className:"flex items-center justify-between gap-2 text-sm",children:[e.jsx("span",{className:"truncate text-foreground",children:Q.name}),e.jsx("span",{className:`inline-flex shrink-0 items-center rounded-full px-2 py-0.5 text-[11px] font-medium ${ur[Q.role]||ur.member}`,children:ti[Q.role]||Q.role})]},U))})]}),A&&(!y.members||y.members.length===0)&&e.jsx("div",{className:"mt-3 border-t border-border pt-3",children:e.jsx("p",{className:"text-xs italic text-muted-foreground",children:"No members listed"})})]})},y.id)})})]}),e.jsx(Fe,{open:!!h,onOpenChange:y=>{y||p(null)},children:e.jsxs(Te,{className:"sm:max-w-md",children:[e.jsx(Ae,{children:e.jsx(Ee,{children:"Apply for position"})}),e.jsxs("div",{className:"space-y-3 py-2",children:[v&&e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-semibold tracking-tight text-foreground",children:v.title}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[v.committee_name," ·"," ",ti[v.role]||v.role]})]}),e.jsxs("div",{children:[e.jsx(T,{className:"text-muted-foreground",children:"Message (optional)"}),e.jsx(It,{value:x,onChange:y=>f(y.target.value),placeholder:"Tell the committee why you're interestedâ¦",rows:3,maxLength:500,className:"text-foreground"}),e.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:[x.length,"/500"]})]})]}),e.jsxs(Ge,{children:[e.jsx(g,{variant:"outline",onClick:()=>p(null),children:"Cancel"}),e.jsx(g,{className:"bg-blue-600 font-medium text-white hover:bg-blue-700",onClick:k,disabled:d.isPending,children:d.isPending?"Submittingâ¦":"Submit application"})]})]})})]})}function dy(t){return Object.entries(t.custom_fields||{}).filter(([,s])=>s!==null&&s!==""&&!(Array.isArray(s)&&s.length===0))}function my(t){return!!t.email||!!t.phone||dy(t).length>0}function sA(){const t=us(),{data:s}=Qa(),[a,n]=o.useState(1),[r,i]=o.useState(""),[l,m]=o.useState(""),[c,d]=o.use
3957State(""),[u,h]=o.useState(""),[p,x]=o.useState("grid"),[f,b]=o.useState(null),[N,j]=o.useState({});o.useEffect(()=>{const A=setTimeout(()=>{m(r),n(1)},300);return()=>clearTimeout(A)},[r]);const{data:w}=bg(),{data:v,isLoading:k,isFetching:S}=sN(a,20,l,{membership_type_id:c||void 0,state:u||void 0,customFieldFilters:Object.keys(N).length>0?N:void 0});if(s&&s.feature_modules?.directory_enabled===!1)return e.jsx(_t,{to:t("/dashboard"),replace:!0});const _=w?.custom_field_labels||{},y=Object.values(N).some(Boolean),C=!!l||!!c||!!u||y,P=()=>{i(""),m(""),d(""),h(""),j({}),n(1)};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg",style:{backgroundColor:"var(--portal-primary-light)",color:"var(--portal-primary)"},children:e.jsx(Lt,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:"Member directory"}),v&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:[v.total.toLocaleString()," member",v.total!==1?"s":""]})]})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-0.5 rounded-lg border border-border bg-card p-0.5",children:[e.jsx("button",{onClick:()=>x("grid"),className:`rounded p-1.5 transition-colors ${p==="grid"?"bg-muted text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,title:"Grid view",children:e.jsx(sj,{className:"h-4 w-4"})}),e.jsx("button",{onClick:()=>x("list"),className:`rounded p-1.5 transition-colors ${p==="list"?"bg-muted text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,title:"List view",children:e.jsx(td,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(ya,{className:"pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(O,{placeholder:"Search by name, city, or organizationâ¦",value:r,onChange:A=>i(A.target.value),className:"h-11 border-border bg-background pl-9 text-base text-foreground"})]}),w?.membership_types?.length||w?.states?.length||w?.custom_field_filters?.length?e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[w.membership_types.length>0&&e.jsxs(qe,{value:c,onValueChange:A=>{d(A==="all"?"":A),n(1)},children:[e.jsx(Le,{className:"w-full border-border bg-background text-foreground sm:w-[200px]",children:e.jsx(Ie,{placeholder:"Membership Type"})}),e.jsxs($e,{children:[e.jsx(q,{value:"all",children:"All Types"}),w.membership_types.map(A=>e.jsx(q,{value:A.id,children:A.name},A.id))]})]}),w.states.length>0&&e.jsxs(qe,{value:u,onValueChange:A=>{h(A==="all"?"":A),n(1)},children:[e.jsx(Le,{className:"w-full border-border bg-background text-foreground sm:w-[140px]",children:e.jsx(Ie,{placeholder:"State"})}),e.jsxs($e,{children:[e.jsx(q,{value:"all",children:"All States"}),w.states.map(A=>e.jsx(q,{value:A,children:A},A))]})]}),w.custom_field_filters?.map(A=>e.jsxs(qe,{value:N[A.key]||"",onValueChange:E=>{j(Q=>{const U={...Q};return E==="all"?delete U[A.key]:U[A.key]=E,U}),n(1)},children:[e.jsx(Le,{className:"w-full border-border bg-background text-foreground sm:w-[180px]",children:e.jsx(Ie,{placeholder:A.label})}),e.jsxs($e,{children:[e.jsxs(q,{value:"all",children:["All ",A.label]}),A.options.map(E=>e.jsx(q,{value:E,children:E},E))]})]}
3957,A.key)),C&&e.jsxs(g,{variant:"outline",size:"sm",onClick:P,className:"h-10 border-border text-muted-foreground hover:text-foreground",children:[e.jsx(ms,{className:"mr-1 h-4 w-4"}),"Clear"]})]}):null,k?e.jsx("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-3",children:[1,2,3,4,5,6].map(A=>e.jsx(Y,{className:"h-36 w-full rounded-lg"},A))}):v?.items.length?p==="grid"?e.jsx("div",{className:`grid gap-3 sm:grid-cols-2 lg:grid-cols-3 ${S?"opacity-70":""}`,children:v.items.map(A=>e.jsx(aA,{member:A,expanded:f===A.id,onToggle:()=>b(f===A.id?null:A.id),customFieldLabelMap:_},A.id))}):e.jsx("div",{className:`overflow-hidden rounded-lg border border-border bg-card ${S?"opacity-70":""}`,children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-muted/30",children:e.jsxs("tr",{className:"border-b border-border text-left",children:[e.jsx("th",{className:"h-10 px-4 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Name"}),e.jsx("th",{className:"hidden h-10 px-4 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80 sm:table-cell",children:"Organization"}),e.jsx("th",{className:"hidden h-10 px-4 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80 md:table-cell",children:"Location"}),e.jsx("th",{className:"hidden h-10 px-4 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80 lg:table-cell",children:"Type"})]})}),e.jsx("tbody",{className:"divide-y divide-border",children:v.items.map(A=>{const E=my(A);return e.jsxs("tr",{className:`transition-colors ${E?"cursor-pointer hover:bg-brand-navy/[0.04] dark:hover:bg-brand-navy/10":""}`,onClick:E?()=>b(f===A.id?null:A.id):void 0,children:[e.jsxs("td",{className:"px-4 py-3",children:[e.jsxs("div",{className:"font-semibold tracking-tight text-foreground",children:[A.first_name," ",A.last_name]}),A.committees&&A.committees.length>0&&e.jsx("div",{className:"mt-1 flex flex-wrap gap-1",children:A.committees.map((Q,U)=>e.jsx("span",{className:"inline-flex items-center rounded-full bg-blue-100 px-2 py-0.5 text-[11px] font-medium text-blue-700 dark:bg-blue-900/30 dark:text-blue-300",children:Q.name},U))}),E&&f===A.id&&e.jsx(uy,{member:A,customFieldLabelMap:_})]}),e.jsx("td",{className:"hidden px-4 py-3 text-muted-foreground sm:table-cell",children:A.organization||"â"}),e.jsx("td",{className:"hidden px-4 py-3 text-muted-foreground md:table-cell",children:[A.city,A.state].filter(Boolean).join(", ")||"â"}),e.jsx("td",{className:"hidden px-4 py-3 lg:table-cell",children:A.membership_type_name?e.jsx("span",{className:"inline-flex items-center rounded-full px-2 py-0.5 text-[11px] font-medium",style:{backgroundColor:"var(--portal-primary-light)",color:"var(--portal-primary)"},children:A.membership_type_name}):"â"})]},A.id)})})]})}):e.jsx(L,{className:"min-w-0 overflow-hidden",children:e.jsxs($,{className:"py-12 text-center",children:[e.jsx(Lt,{className:"mx-auto mb-3 h-10 w-10 text-muted-foreground/60"}),e.jsx("p",{className:"text-sm font-medium text-muted-foreground",children:"No members found"}),C&&e.jsx(g,{variant:"outline",size:"sm",onClick:P,className:"mt-3 border-border text-muted-foreground hover:text-foreground",children:"Clear filters"})]})}),v&&v.pages>1&&e.jsxs("div",{className:"flex items-center justify-between pt-2",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Page ",v.page," of ",v.pages]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(g,{variant:"outline",size:"sm",onClick:()=>n(A=>Math.max(1,A-1)),disabled:a<=1,className:"border-border text-muted-foreground",children:[e.jsx(Gs,{className:"mr-1 h-4 w-4"}),"Previous"]}),e.jsxs(g,{variant:"outline",size:"sm",onClick:()=>n(A=>A+1),disabled:a>=(v?.pages??1),className:"border-border text-muted-foreground",children:["Next",e.jsx(ts,{className:"ml-1 h-4 w-4"})]})]})]})]})}function aA({member:t,expanded:s,onToggle:a,customFieldLabelMap:n}){const r=[t.city,t.state].filter(Boolean).join(", "),i=my(t);return e.jsx(L,{className:`min-w-0 overflow-hidden border-border transition-shadow ${i?"cursor-pointer hover:shadow-md":""}`,onClick:i?a:void 0,children:e.jsxs($,{className:"p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("h3",{className:"truncate text-base font-semibold tracking-tight text-foreground",children:[t.first_name," ",t.last_name]}),t.membership_type_name&&e.jsx("span",{className:"mt-1.5 inline-flex items-center rounded-full px-2 py-0.5 text-[11px] font-medium",style:{backgroundColor:"var(--portal-primary-light)",color:"var(--portal-primary)"},children:t.membership_type_name})]}),t.headshot_url?e.jsx("img",{src:`${ds}${t.headshot_url}`,alt:"",className:"h-10 w-10 shrink-0 rounded-full object-cover ring-1 ring-border"}):e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-full ring-1 ring-border",style:{backgroundColor:"var(--portal-primary-light)",color:"var(--portal-primary)"},children:e.jsxs("span",{className:"text-xs font-semibold tracking-tight",children:[t.first_name[0],t.last_name[0]]})})]}),e.jsxs("div",{className:"mt-3 space-y-1",children:[r&&e.jsxs("div",{className:"flex items-center gap-1.5 text-sm text-muted-foreground",children:[e.jsx(Fa,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{className:"truncate",children:r})]}),t.organization&&e.jsxs("div",{className:"flex items-center gap-1.5 text-sm text-muted-foreground",children:[e.jsx(ga,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{className:"truncate",children:t.organization})]})]}),t.committees&&t.committees.length>0&&e.jsx("div",{className:"mt-2 flex flex-wrap gap-1",children:t.committees.map((l,m)=>e.jsx("span",{className:"inline-flex items-center rounded-full bg-blue-100 px-2 py-0.5 text-[11px] font-medium text-blue-700 dark:bg-blue-900/30 dark:text-blue-300",children:l.name},m))}),i&&s&&e.jsx(uy,{member:t,customFieldLabelMap:n})]})})}const nA=uo;function rA(t){return Array.isArray(t)?t.join(", "):String(t)}function uy({member:t,customFieldLabelMap:s}){const a=dy(t);return e.jsx("div",{className:"mt-3 border-t border-border pt-3",onClick:n=>n.stopPropagation(),children:e.jsxs("dl",{className:"space-y-2 text-sm",children:[t.email&&e.jsxs("div",{children:[e.jsx("dt",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted-foreground",children:"Email"}),e.jsx("dd",{className:"mt-0.5 text-muted-foreground",children:e.jsx("a",{href:`mailto:${t.email}`,className:"hover:underline",children:t.email})})]}),t.phone&&e.jsxs("div",{children:[e.jsx("dt",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted-foreground",children:"Phone"}),e.jsx("dd",{className:"mt-0.5 text-muted-foreground",children:t.phone})]}),a.map(([n,r])=>e.jsxs("div",{children:[e.jsx("dt",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted-foreground",children:s[n]||nA(n)}),e.jsx("dd",{className:"mt-0.5 text-muted-foreground",children:rA(r)})]},n))]})})}const iA={event:"Event",product:"Product",donation:"Donation"};
3957function hr(t){return t.toLocaleString("en-US",{style:"currency",currency:"USD"})}function lA({order:t}){const[s,a]=o.useState(!1),n=async i=>{i.stopPropagation();try{const l=await Zs.downloadOrderReceipt(t.id),m=window.URL.createObjectURL(l),c=document.createElement("a");c.href=m,c.download=`receipt-${t.order_id_short}.pdf`,c.click(),window.URL.revokeObjectURL(m)}catch{}},r=t.line_items.length===1?t.line_items[0].item_name:`${t.line_items.length} items`;return e.jsx(L,{className:"min-w-0 overflow-hidden transition-shadow hover:shadow-sm",children:e.jsxs($,{className:"p-0",children:[e.jsxs("button",{className:"flex w-full items-center gap-3 p-4 text-left transition-colors hover:bg-brand-navy/[0.04] dark:hover:bg-brand-navy/10",onClick:()=>a(!s),children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("span",{className:"text-sm font-semibold tracking-tight text-foreground",children:["#",t.order_id_short]}),e.jsxs("span",{className:"inline-flex items-center gap-1.5 whitespace-nowrap capitalize",children:[e.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-emerald-500"}),e.jsx("span",{className:"text-xs font-medium",children:t.status})]})]}),e.jsxs("div",{className:"mt-1 truncate text-xs text-muted-foreground",children:[Be(pt(t.created_at),"MMM d, yyyy")," â ",r]})]}),e.jsx("div",{className:"shrink-0 text-right",children:e.jsx("div",{className:"text-sm font-semibold tracking-tight text-foreground",children:hr(t.total)})}),e.jsx("div",{className:"shrink-0 text-muted-foreground",children:s?e.jsx(Gn,{className:"h-4 w-4"}):e.jsx(ps,{className:"h-4 w-4"})})]}),s&&e.jsxs("div",{className:"space-y-3 border-t bg-muted/20 px-4 pb-4 pt-3",children:[e.jsx("div",{className:"divide-y rounded-md border bg-background",children:t.line_items.map((i,l)=>e.jsxs("div",{className:"flex items-center justify-between gap-3 p-3 text-sm",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate font-medium text-foreground",children:i.item_name}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[iA[i.item_type]||i.item_type,i.quantity>1&&` Ã ${i.quantity} @ ${hr(i.unit_price)}`]})]}),e.jsx("span",{className:"shrink-0 font-semibold text-foreground",children:hr(i.total_price)})]},l))}),e.jsxs("div",{className:"space-y-1 text-right text-sm",children:[t.discount_amount>0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"text-muted-foreground",children:["Subtotal: ",hr(t.subtotal)]}),e.jsxs("div",{className:"text-emerald-700 dark:text-emerald-400",children:["Discount",t.promo_code?` (${t.promo_code})`:"",": â",hr(t.discount_amount)]})]}),e.jsxs("div",{className:"font-semibold tracking-tight text-foreground",children:["Total: ",hr(t.total)]})]}),t.has_receipt&&e.jsxs(g,{className:"bg-blue-600 font-medium text-white hover:bg-blue-700",size:"sm",onClick:n,children:[e.jsx(vs,{className:"mr-1.5 h-4 w-4"}),"Download receipt"]})]})]})})}function oA(){const[t,s]=o.useState(1),{data:a,isLoading:n}=g3(t);return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg",style:{backgroundColor:"var(--portal-primary-light)",color:"var(--portal-primary)"},children:e.jsx(Wn,{className:"h-5 w-5"})}),e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:"Order history"})]}),n?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(r=>e.jsx(Y,{className:"h-20 w-full"},r))}):a?.items.length?e.jsx("div",{className:"space-y-2",children:a.items.map(r=>e.jsx(lA,{order:r},r.id))}):e.jsx(L,{className:"min-w-0 overflow-hidden",children:e.jsxs($,{className:"space-y-3 py-12 text-center",children:[e.jsx(Wn,{className:"mx-auto h-10 w-10 text-muted-foreground/60"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No orders yet."})]})}),a&&a.pages>1&&e.jsxs("div",{className:"flex items-center justify-between pt-2",children:[e.jsx(g,{variant:"outline",className:"min-h-[44px]",disabled:t<=1,onClick:()=>s(r=>r-1),children:"Previous"}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:["Page ",t," of ",a.pages]}),e.jsx(g,{variant:"outline",className:"min-h-[44px]",disabled:t>=a.pages,onClick:()=>s(r=>r+1),children:"Next"})]})]})}function ah(){const t=qs(),s=us(),{data:a,isLoading:n}=ma(t||void 0);Ra(a?.society?.favicon_url);const r=a?.society?.name||"Organization",i=a?.society?.logo_url?`${ds}${a.society.logo_url}`:null,l=a?.society?.primary_color||"#2563eb";return n?e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-slate-50",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-slate-200 border-t-blue-600"})}):e.jsx("div",{className:"min-h-screen bg-slate-50",children:e.jsxs("div",{className:"mx-auto max-w-3xl px-4 py-12 sm:px-6",children:[e.jsxs("div",{className:"mb-8 text-center",children:[i&&e.jsx("img",{src:i,alt:r,className:"mx-auto mb-4 h-14 object-contain"}),e.jsx("h1",{className:"text-2xl font-semibold tracking-tight text-slate-900",children:"Terms of service"}),e.jsx("p",{className:"mt-1 text-sm text-slate-500",children:"Last updated: February 2026"})]}),e.jsx("div",{className:"rounded-xl border border-slate-200 bg-white p-6 shadow-sm sm:p-10",children:e.jsxs("div",{className:"prose prose-slate prose-headings:text-slate-900 prose-p:text-slate-600 prose-li:text-slate-600 max-w-none",children:[e.jsx("h2",{children:"1. Acceptance of Terms"}),e.jsxs("p",{children:["By creating an account or using the membership portal operated by ",r,' ("we," "us," or "our"), you agree to be bound by these Terms of Service. If you do not agree, please do not use our services.']}),e.jsx("h2",{children:"2. Membership"}),e.jsxs("p",{children:["Membership is subject to approval by ",r,". We reserve the right to accept or decline any membership application at our discretion. Membership benefits, dues, and terms are as de
3957scribed on our signup page and may be updated from time to time."]}),e.jsx("h2",{children:"3. Account responsibilities"}),e.jsx("p",{children:"You are responsible for maintaining the confidentiality of your account credentials and for all activities that occur under your account. You agree to provide accurate and complete information when creating your account and to keep your information up to date."}),e.jsx("h2",{children:"4. Payments and Refunds"}),e.jsxs("p",{children:["Membership dues and other fees are as stated at the time of purchase. Payments are processed securely through our payment provider. Refund policies are determined by"," ",r," and may vary. Contact us directly for refund requests."]}),e.jsx("h2",{children:"5. Acceptable use"}),e.jsx("p",{children:"You agree not to:"}),e.jsxs("ul",{children:[e.jsx("li",{children:"Use the portal for any unlawful purpose"}),e.jsx("li",{children:"Share your account credentials with others"}),e.jsx("li",{children:"Attempt to gain unauthorized access to any part of the system"}),e.jsx("li",{children:"Upload harmful content or interfere with the portal's operation"})]}),e.jsx("h2",{children:"6. Intellectual property"}),e.jsxs("p",{children:["All content, logos, and materials on this portal are the property of ",r," or its licensors and are protected by applicable intellectual property laws."]}),e.jsx("h2",{children:"7. Termination"}),e.jsxs("p",{children:["We may suspend or terminate your account if you violate these terms. You may cancel your membership at any time by contacting ",r," directly."]}),e.jsx("h2",{children:"8. Limitation of Liability"}),e.jsxs("p",{children:["To the fullest extent permitted by law, ",r," shall not be liable for any indirect, incidental, or consequential damages arising from your use of the portal."]}),e.jsx("h2",{children:"9. Changes to Terms"}),e.jsx("p",{children:"We may update these terms from time to time. Continued use of the portal after changes constitutes acceptance of the updated terms."}),e.jsx("h2",{children:"10. Contact"}),e.jsxs("p",{children:["If you have questions about these terms, please contact ",r," through our website",a?.society?.website_url&&e.jsxs(e.Fragment,{children:[" ","at"," ",e.jsx("a",{href:a.society.website_url,target:"_blank",rel:"noopener noreferrer",children:a.society.website_url})]}),"."]})]})}),e.jsx("div",{className:"mt-6 text-center",children:e.jsxs(je,{to:s("/signup"),className:"inline-flex items-center gap-1.5 text-sm font-medium transition-colors hover:opacity-80",style:{color:l},children:[e.jsx(es,{className:"h-3.5 w-3.5"}),"Back to signup"]})})]})})}function nh(){const t=qs(),s=us(),{data:a,isLoading:n}=ma(t||void 0);Ra(a?.society?.favicon_url);const r=a?.society?.name||"Organization",i=a?.society?.logo_url?`${ds}${a.society.logo_url}`:null,l=a?.society?.primary_color||"#2563eb";return n?e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-slate-50",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-slate-200 border-t-blue-600"})}):e.jsx("div",{className:"min-h-screen bg-slate-50",children:e.jsxs("div",{className:"mx-auto max-w-3xl px-4 py-12 sm:px-6",children:[e.jsxs("div",{className:"mb-8 text-center",children:[i&&e.jsx("img",{src:i,alt:r,className:"mx-auto mb-4 h-14 object-contain"}),e.jsx("h1",{className:"text-2xl font-semibold tracking-tight text-slate-900",children:"Privacy policy"}),e.jsx("p",{className:"mt-1 text-sm text-slate-500",children:"Last updated: February 2026"})]}),e.jsx("div",{className:"rounded-xl border border-slate-200 bg-white p-6 shadow-sm sm:p-10",children:e.jsxs("div",{className:"prose prose-slate prose-headings:text-slate-900 prose-p:text-slate-600 prose-li:text-slate-600 max-w-none",children:[e.jsx("h2",{children:"1. Information we collect"}),e.jsx("p",{children:"When you create an account or use our membership portal, we may collect:"}),e.jsxs("ul",{children:[e.jsxs("li",{children:[e.jsx("strong",{children:"Personal information:"})," Name, email address, phone number, mailing address, and organization"]}),e.jsxs("li",{children:[e.jsx("strong",{children:"Account information:"})," Login credentials (passwords are encrypted and never stored in plain text)"]}),e.jsxs("li",{children:[e.jsx("strong",{children:"Payment information:"})," Payment details are processed securely by our third-party payment processor (Stripe) and are not stored on our servers"]}
3957),e.jsxs("li",{children:[e.jsx("strong",{children:"Usage information:"})," How you interact with the portal, including pages visited and actions taken"]})]}),e.jsx("h2",{children:"2. How we use your information"}),e.jsx("p",{children:"We use the information we collect to:"}),e.jsxs("ul",{children:[e.jsx("li",{children:"Manage your membership and provide member benefits"}),e.jsx("li",{children:"Process payments and send receipts"}),e.jsx("li",{children:"Communicate with you about your membership, events, and organization news"}),e.jsx("li",{children:"Maintain and improve our portal and services"}),e.jsx("li",{children:"Comply with legal obligations"})]}),e.jsx("h2",{children:"3. Information sharing"}),e.jsx("p",{children:"We do not sell your personal information. We may share your information with:"}),e.jsxs("ul",{children:[e.jsxs("li",{children:[e.jsx("strong",{children:"Service providers:"})," Third parties that help us operate the portal (e.g., payment processing, email delivery)"]}),e.jsxs("li",{children:[e.jsx("strong",{children:"Member directory:"})," If you opt in, your name and professional details may be visible to other members in the member directory"]}),e.jsxs("li",{children:[e.jsx("strong",{children:"Legal requirements:"})," When required by law or to protect our rights"]})]}),e.jsx("h2",{children:"4. Data security"}),e.jsx("p",{children:"We implement appropriate technical and organizational measures to protect your personal information, including encryption of sensitive data, secure HTTPS connections, and regular security reviews."}),e.jsx("h2",{children:"5. Your rights"}),e.jsx("p",{children:"You have the right to:"}),e.jsxs("ul",{children:[e.jsx("li",{children:"Access and update your personal information through your profile settings"}),e.jsx("li",{children:"Request deletion of your account and associated data"}),e.jsx("li",{children:"Opt out of marketing communications at any time"}),e.jsx("li",{children:"Request a copy of the data we hold about you"})]}),e.jsx("h2",{children:"6. Cookies"}),e.jsx("p",{children:"We use essential cookies to keep you logged in and maintain your session. We do not use tracking or advertising cookies."}),e.jsx("h2",{children:"7. Data retention"}),e.jsx("p",{children:"We retain your personal information for as long as your membership is active and for a reasonable period afterward for record-keeping and legal compliance purposes."}),e.jsx("h2",{children:"8. Children's Privacy"}),e.jsx("p",{children:"Our portal is not intended for use by individuals under the age of 13. We do not knowingly collect personal information from children."}),e.jsx("h2",{children:"9. Changes to this policy"}),e.jsx("p",{children:"We may update this privacy policy from time to time. We will notify members of significant changes via email or a notice on the portal."}),e.jsx("h2",{children:"10. Contact"}),e.jsxs("p",{children:["If you have questions about this privacy policy or your personal data, please contact"," ",r,a?.society?.website_url&&e.jsxs(e.Fragment,{children:[" ","through our website at"," ",e.jsx("a",{href:a.society.website_url,target:"_blank",rel:"noopener noreferrer",children:a.society.website_url})]}),"."]})]})}),e.jsx("div",{className:"mt-6 text-center",children:e.jsxs(je,{to:s("/signup"),className:"inline-flex items-center gap-1.5 text-sm font-medium transition-colors hover:opacity-80",style:{color:l},children:[e.jsx(es,{className:"h-3.5 w-3.5"}),"Back to signup"]})})]})})}function Ll(){const t=qs(),s=us(),{data:a}=ma(t||void 0),n=Si(a?.society?.primary_color),{isAuthenticated:r}=ft(),i=kt();Ra(a?.society?.favicon_url);const l=a?.society?.name||t?.toUpperCase()||"Member Portal",m=a?.society?.logo_url,c=m?`${ds}${m}`:null;return e.jsx("div",{className:"flex min-h-screen flex-col items-center justify-center bg-background px-4",style:n,children:e.jsxs("div",{className:"w-full max-w-md text-center",children:[e.jsx("div",{className:"mb-8",children:c?e.jsx("img",{src:c,alt:l,className:"mx-auto mb-4 h-16 w-auto object-contain"}):e.jsx("h2",{className:"mb-4 text-xl font-semibold tracking-tight text-foreground",children:l})}),e.jsx("div",{className:"mx-auto mb-5 flex h-16 w-16 items-center justify-center rounded-full",style:{backgroundColor:"var(--portal-primary-light)",color:"var(--portal-primary)"},children:e.jsx(aj,{className:"h-8 w-8"})}),e.jsx("h1",{className:"mb-2 text-2xl font-semibold tracking-tight text-foreground",children:"Page not found"}),e.jsx("p",{className:"mb-8 text-sm leading-relaxed text-muted-foreground",children:"The page you're looking for doesn't exist or has been moved."}),e.jsxs("div",{className:"flex flex-col justify-center gap-3 sm:flex-row",children:[r&&e.jsx("button",{onClick:()=>i(s("/dashboard")),className:"inline-flex min-h-[40px] items-center justify-center rounded-md bg-blue-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-blue-700",children:"Back to dashboard"}),e.jsx("button",{onClick:()=>i(s("/login")),className:`inline-flex min-h-[40px] items-center justify-center rounded-md px-4 py-2 text-sm font-medium transition-colors ${r?"border border-border bg-card text-foreground hover:bg-muted":"bg-blue-600 text-white hover:bg-blue-700"}`,children:"Back to login"})]})]})})}function cA(t){const s=[];if(t.due_at){const a=_d(t.due_at);s.push(Ct(t.due_at).getTime()<Date.now()?`Overdue (was due ${a} UTC)`:`Due ${a} UTC`)}return t.since&&s.push(`Since ${Yn(t.since)}`),t.evidence_at&&s.push(`Recorded ${Yn(t.evidence_at)}`),s.length===0&&s.push("No time recorded"),s.join(" · ")}function dA({societyId:t}){const s=Ms(re({queryKey:["platform","attention",t??"all"],queryFn:()=>bi.getAttention(t),staleTime:0,refetchOnMount:"always"}),t??"all"),a=s.readyData,n=a?.sources.filter(r=>!r.ok)??[];return e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex items-center gap-2.5 text-base font-semibold tracking-tight",children:[e.jsx(pa,{icon:Yc}),"Needs attention"]})}),e.jsx($,{className:"space-y-3",children:s.state==="loading"?e.jsx(Y,{className:"h-32 w-full"}):s.state==="offline"&&!a?e.jsx(Wa,{title:"What needs attention canât be checked right now."}):a?e.jsxs(e.Fragment,{children:[e.jsx(Ma,{view:s,what:"what needs attention"}),n.length>0&&e.jsxs("p",{role:"alert",className:"flex items-start gap-2 rounded-lg border border-amber-500/40 bg-amber-50 px-3 py-2 text-sm text-amber-900 dark:bg-amber-950/30 dark:text-amber-200",children:[e.jsx(Dt,{className:"mt-0.5 h-4 w-4 shrink-0","aria-hidden":"true"}),e.jsxs("span",{children:["Couldnât check ",n.map(r=>r.label.toLowerCase()).join(", "),", so any problems there arenât listed."," ",e.jsx("button",{type:"button",onClick:s.retry,className:"font-medium underline underline-offset-2",children:"Try again"})]})]}),a.items.length===0?e.jsxs("p",{role:"status",className:"flex items-start gap-2 text-sm",children:[e.jsx(Kt,{className:"mt-0.5 h-4 w-4 shrink-0 text-emerald-600","aria-hidden":"true"}
3957),e.jsx("span",{children:a.societies_checked===0?"No active societies to check.":n.length>0?`No problems found in the checks that ran (${a.societies_checked} active ${a.societies_checked===1?"society":"societies"}).`:`No known issues across ${a.societies_checked} active ${a.societies_checked===1?"society":"societies"}.`})]}):e.jsxs("p",{role:"status",className:"text-sm text-muted-foreground",children:[a.items.length," ",a.items.length===1?"item":"items"," across"," ",new Set(a.items.map(r=>r.society_id)).size," of ",a.societies_checked," ","active societies, most urgent first."]}),a.items.length>0&&e.jsx("ul",{className:"divide-y rounded-md border",children:a.items.map(r=>e.jsxs("li",{className:"flex flex-col gap-2 px-3 py-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"min-w-0 space-y-0.5",children:[e.jsxs("p",{className:"flex items-center gap-2 text-sm font-medium",children:[e.jsx("span",{className:me("h-2 w-2 shrink-0 rounded-full",r.severity==="high"?"bg-red-500":"bg-amber-500"),"aria-hidden":"true"}),e.jsx("span",{className:"sr-only",children:r.severity==="high"?"Urgent: ":"Needs attention: "}),r.title]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[e.jsx(je,{to:`/platform/societies/${r.society_id}`,className:"font-medium text-foreground hover:underline",children:r.society_n
3957ame})," ","· ",r.detail]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:cA(r)})]}),e.jsx(g,{variant:"outline",size:"sm",asChild:!0,className:"shrink-0",children:e.jsxs(je,{to:r.resolve_url,"aria-label":`${r.resolve_label}: ${r.society_name}`,children:[r.resolve_label,e.jsx(as,{className:"ml-1.5 h-4 w-4","aria-hidden":"true"})]})})]},r.id))}),e.jsxs("details",{className:"text-xs text-muted-foreground",children:[e.jsx("summary",{className:"cursor-pointer",children:"Whatâs checked"}),e.jsxs("ul",{className:"mt-2 list-disc space-y-0.5 pl-5",children:[a.sources.map(r=>e.jsxs("li",{children:[r.label,r.ok?"":" (couldnât be checked)"]},r.key)),e.jsx("li",{children:"Not checked here: failed renewal charges, order recovery and scheduled jobs. See each societyâs workspace."}),a.inactive_societies>0&&e.jsxs("li",{children:[a.inactive_societies," inactive"," ",a.inactive_societies===1?"society is":"societies are"," left out."]})]})]})]}):e.jsx(ja,{title:"What needs attention couldnât be checked.",error:s.error,onRetry:s.retry,isRetrying:s.retrying})})]})}function Br(t,s="/dashboard"){const[a,n=""]=s.split("?"),r=new URLSearchParams(n);return r.set("society",t),`${a}?${r.toString()}`}const Ec={needs_attention:"Needs attention",verified:"Verified",configured:"Configured",unknown:"No health signal",not_configured:"Not set up",not_enabled:"Off"},hy={needs_attention:"amber",verified:"emerald",configured:"sky",unknown:"neutral",not_configured:"muted",not_enabled:"muted"};function py(t){return t?`Based on activity ${Yn(t)}.`:"No activity recorded."}const mA={amber:"bg-amber-500",emerald:"bg-emerald-500",sky:"bg-sky-500",neutral:"border border-muted-foreground/60",muted:"bg-muted-foreground/40"},rh={needs_attention:0,verified:1,configured:2,unknown:3,not_configured:4,not_enabled:5};function xy({societyId:t,integrations:s}){const a=s.filter(i=>i.required||i.state!=="not_configured"&&i.state!=="not_enabled").sort((i,l)=>rh[i.state]-rh[l.state]),n=s.length-a.length,r=a.filter(i=>i.state==="needs_attention").length;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Integrations"}),r>0&&e.jsxs(je,{to:`/platform/societies/${t}/settings?tab=integrations`,className:"text-xs font-medium text-amber-700 underline-offset-2 hover:underline dark:text-amber-400",children:["Review ",r," issue",r===1?"":"s"]})]}),a.length===0?e.jsx("p",{className:"text-xs text-muted-foreground",children:"None set up."}):e.jsx("ul",{className:"flex flex-wrap gap-x-3 gap-y-1.5",children:a.map(i=>e.jsx("li",{children:e.jsxs(fs,{children:[e.jsx(ys,{asChild:!0,children:e.jsxs("span",{tabIndex:0,className:"inline-flex cursor-default items-center gap-1.5 whitespace-nowrap rounded focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[e.jsx("span",{className:me("h-1.5 w-1.5 shrink-0 rounded-full",mA[hy[i.state]]),"aria-hidden":"true"}),e.jsx("span",{className:"text-xs font-medium",children:i.label}),e.jsxs("span",{className:"sr-only",children:[": ",Ec[i.state]]})]})}),e.jsxs(hs,{className:"max-w-xs",children:[e.jsxs("p",{className:"font-medium",children:[i.label," · ",Ec[i.state]]}),e.jsx("p",{className:"mt-0.5",children:i.detail}),e.jsx("p",{className:"mt-0.5 opacity-80",children:py(i.checked_at)})]})]})},i.key))}),n>0&&e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:[n," optional integration",n===1?"":"s"," off or not set up"]})]})}function uA(){const t=Ms(zv()),s=t.readyData,{user:a}=V(),n=kt(),r=o.useCallback(()=>Xa.listCredentials(),[]),[i,l]=ws(),m=_r.test(i.get("society")??"")?i.get("society"):void 0,c=qr().data??[],d=s?s.societies.filter(u=>!m||u.id===m):[];return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-brand-navy
3957/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(Ul,{className:"h-5 w-5","aria-hidden":"true"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:"Platform overview"}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"What needs attention across your societies, and where to fix it"})]})]}),e.jsxs("div",{className:"w-full sm:w-64",children:[e.jsx(T,{htmlFor:"overview-society",className:"sr-only",children:"Society"}),e.jsxs(qe,{value:m??ac,onValueChange:u=>l(u===ac?{}:{society:u},{replace:!0}),children:[e.jsx(Le,{id:"overview-society","aria-label":"Show society",children:e.jsx(Ie,{placeholder:"All societies"})}),e.jsxs($e,{children:[e.jsx(q,{value:ac,children:"All societies"}),c.map(u=>e.jsx(q,{value:u.id,children:u.name},u.id))]})]})]})]}),a&&e.jsx(Ad,{subjectId:a.id,variant:"admin",settingsPath:"/platform/account",checkCredentials:r}),e.jsx(dA,{societyId:m}),t.state==="loading"?e.jsx(pA,{}):s?e.jsxs(e.Fragment,{children:[e.jsx(Ma,{view:t,what:"society totals"}),m&&e.jsx("p",{className:"-mb-4 text-xs text-muted-foreground",children:"Totals for all societies"}),e.jsxs("dl",{className:"grid gap-4 rounded-lg border bg-card p-4 text-sm sm:grid-cols-3",children:[e.jsxs("div",{children:[e.jsx("dt",{className:"text-muted-foreground",children:"Societies"}),e.jsxs("dd",{className:"text-xl font-semibold",children:[s.total_societies,e.jsxs("span",{className:"ml-2 text-xs font-normal text-muted-foreground",children:[s.active_societies," active, ",s.inactive_societies," inactive"]})]})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-muted-foreground",children:"Member records"}),e.jsx("dd",{className:"text-xl font-semibold",children:s.total_members.toLocaleString()})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-muted-foreground",children:"Active members"}),e.jsx("dd",{className:"text-xl font-semibold",children:s.total_active_members.toLocaleString()})]})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"mb-4 flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("h2",{className:"text-lg font-semibold tracking-tight text-foreground",children:"Societies"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Integration status comes from recorded activity:"," ",e.jsx("span",{className:"font-medium text-foreground",children:"verified"})," worked recently,"," ",e.jsx("span",{className:"font-medium text-foreground",children:"configured"})," is set up but unconfirmed, ",e.jsx("span",{className:"font-medium text-foreground",children:"needs attention"})," ","has a recorded problem."]})]}),e.jsx(g,{variant:"outline",onClick:()=>n("/platform/societies"),children:"View all societies"})]}),d.length===0?e.jsx("p",{className:"rounded-lg border px-4 py-8 text-center text-sm text-muted-foreground",children:s.societies.length===0?"No societies yet.":"This society isnât listed."}):e.jsx("div",{className:"grid gap-4 md:grid-cols-2 xl:grid-cols-3",children:d.map(u=>e.jsx(hA,{society:u},u.id))})]})]}):e.jsx("div",{className:"rounded-lg border",children:t.state==="offline"?e.jsx(Wa,{title:"Society totals canât be loaded right now."}):e.jsx(ja,{title:"Society totals couldnât be loaded.",error:t.error,onRetry:t.retry,isRetrying:t.retrying})})]})}const ac="__all__";function hA({society:t}){const s=kt();return e.jsxs(L,{className:"relative min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs(ie,{className:"flex items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(ga,{className:"h-4 w-4"})}),e.jsx(je,{to:`/platform/societies/${t.id}`,className:"hover:underline focus-visible:underline focus-visible:outline-none",children:t.name})]}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:t.slug})]}),e.jsxs(fs,{children:[e.jsx(ys,{asChild:!0,children:t.is_active?e.jsxs("span",{className:"inline-flex cursor-default items-center gap-1.5 rounded-full bg-emerald-100 px-2.5 py-0.5 text-[11px] font-medium text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400",children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-emerald-500","aria-hidden":"true"}),"Active"]}):e.jsxs("span",{className:"inline-flex cursor-default items-center gap-1.5 rounded-full bg-muted px-2.5 py-0.5 text-[11px] font-medium text-muted-foreground",children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-muted-foreground
3957/60","aria-hidden":"true"}),"Inactive"]})}),e.jsx(hs,{children:t.is_active?"Society is operational and accepting members":"Society is disabled and not visible to members"})]})]})}),e.jsxs($,{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-2 text-sm",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Member records:"}),e.jsx("span",{className:"ml-1 font-medium",children:t.total_members})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Active:"}),e.jsx("span",{className:"ml-1 font-medium text-emerald-600 dark:text-emerald-400",children:t.active_members})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Pending:"}),e.jsx("span",{className:"ml-1 font-medium text-amber-600 dark:text-amber-400",children:t.pending_members})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Expired:"}),e.jsx("span",{className:"ml-1 font-medium text-red-600 dark:text-red-400",children:t.expired_members})]})]}),t.expiring_soon>0&&e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-amber-50 px-2 py-1 text-sm text-amber-700 dark:bg-amber-950/20 dark:text-amber-400",children:[e.jsx(Bt,{className:"h-4 w-4 shrink-0"}),e.jsxs("span",{children:[t.expiring_soon," expiring soon (excl. auto-renew)"]})]}),e.jsx(xy,{societyId:t.id,integrations:t.integration_health}),e.jsxs("div",{className:"flex items-center gap-2 pt-2",children:[e.jsx(g,{variant:"outline",size:"sm",className:"flex-1",onClick:()=>s(`/platform/societies/${t.id}/settings`),children:"Settings"}),e.jsx(g,{variant:"default",size:"sm",className:"flex-1",asChild:!0,children:e.jsx(je,{to:Br(t.id),"aria-label":`Open ${t.name} workspace`,children:"Open workspace"})})]})]})]})}function pA(){return e.jsxs("div",{className:"space-y-6",children:[e.jsx(Y,{className:"h-20 w-full"}),e.jsx("div",{className:"grid gap-4 md:grid-cols-2 xl:grid-cols-3",children:[1,2,3].map(t=>e.jsx(Y,{className:"h-48 w-full"},t))})]})}function xA({societies:t,onDelete:s,emptyState:a}){const n=kt();return e.jsx("div",{className:"rounded-md border",children:e.jsxs(Pt,{children:[e.jsx(At,{className:"bg-muted/30",children:e.jsxs(Ue,{className:"hover:bg-transparent",children:[e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Name"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Slug"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Status"}),e.jsx(H,{className:"h-10 text-right text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Actions"})]})}),e.jsx(Et,{children:t.length===0?e.jsx(Ue,{children:e.jsx(G,{colSpan:4,className:"p-0 text-center text-muted-foreground",children:a??e.jsx("p",{className:"py-8",children:"No societies found"})})}):t.map(r=>e.jsxs(Ue,{className:"hover:bg-brand-navy/[0.04] dark:hover:bg-brand-navy/10",children:[e.jsx(G,{className:"font-medium",children:e.jsx(je,{to:`/platform/societies/${r.id}`,className:"hover:underline focus-visible:underline focus-visible:outline-none",children:r.name})}),e.jsx(G,{className:"text-muted-foreground",children:r.slug}),e.jsx(G,{children:e.jsxs(fs,{children:[e.jsx(ys,{asChild:!0,children:e.jsxs("span",{className:"inline-flex cursor-default items-center gap-1.5 whitespace-nowrap",children:[e.jsx("span",{className:`h-1.5 w-1.5 shrink-0 rounded-full ${r.is_active?"bg-emerald-500":"bg-muted-foreground/60"}`}),e.jsx("span",{className:"text-xs font-medium",children:r.is_active?"Active":"Inactive"})]})}),e.jsx(hs,{children:r.is_active?"Society is operational and accepting members":"Society is disabled and not visible to members"})]})}),e.jsx(G,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[e.jsx(g,{variant:"outline",size:"sm",asChild:!0,children:e.jsx(je,{to:Br(r.id),"aria-label":`Open ${r.name} workspace`,children:"Open workspace"})}),e.jsxs(Ws,{children:[e.jsx(Vs,{asChild:!0,children:e.jsxs(g,{variant:"ghost",size:"icon",className:"h-11 w-11 lg:h-10 lg:w-10",children:[e.jsx(Pn,{className:"h-4 w-4","aria-hidden":"true"}),e.jsxs("span",{className:"sr-only",children:["Actions for ",r.name]})]})}),e.jsxs($s,{align:"end",children:[e.jsxs(wt,{onClick:()=>n(`/platform/societies/${r.id}
3957/settings`),children:[e.jsx(Hs,{className:"mr-2 h-4 w-4","aria-hidden":"true"}),"Settings"]}),e.jsxs(wt,{onClick:()=>n(`/platform/societies/${r.id}/settings?tab=customization`),children:[e.jsx(Yc,{className:"mr-2 h-4 w-4"}),"Manage custom fields"]}),e.jsxs(wt,{className:"text-destructive",onClick:()=>s(r),children:[e.jsx(Ft,{className:"mr-2 h-4 w-4"}),"Delete"]})]})]})]})})]},r.id))})]})})}function gA({society:t,open:s,onOpenChange:a,onConfirm:n,isDeleting:r,error:i,onAlreadyDeleted:l}){const[m,c]=o.useState(t);return t&&t!==m&&c(t),e.jsx(Fe,{open:s,onOpenChange:d=>!r&&a(d),children:e.jsx(Te,{className:"max-h-[90vh] overflow-y-auto sm:max-w-lg",children:m&&e.jsx(fA,{society:m,onCancel:()=>a(!1),onConfirm:n,isDeleting:r,error:i,onAlreadyDeleted:l},m.id)})})}function fA({society:t,onCancel:s,onConfirm:a,isDeleting:n,error:r,onAlreadyDeleted:i}){const l=Kv(t.id),[m,c]=o.useState(""),d=m.trim()===t.slug,u=l.isSuccess&&!l.isFetching,h=l.isError&&!l.isFetching,p=on(l.error)===404,x=p||on(l.error)===422,f=l.data?fy(l.data):!1,b=d&&!f&&(u||h&&!x)&&!n&&!gy(r),N=o.useRef(!1);return o.useEffect(()=>{!p||N.current||(N.current=!0,i?.())},[p,i]),e.jsxs(e.Fragment,{children:[e.jsxs(Ae,{children:[e.jsxs(Ee,{children:["Delete ",t.name,"?"]}),e.jsxs(tt,{children:[t.name," (",t.slug,") will be archived: its records are kept, and everything else stops. Thereâs no way to restore it from Korevera."]})]}),e.jsxs("div",{className:"space-y-4 text-sm",children:[l.isError?e.jsx("div",{className:"rounded-md border",children:e.jsx(ja,{title:"What this affects couldnât be loaded.",error:l.error,onRetry:()=>{l.refetch()},isRetrying:l.isFetching,notFound:`${t.name} has already been deleted. Close this to see the current list.`,children:!x&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"You can still delete it without this summary."})})}):l.data?e.jsxs(e.Fragment,{children:[e.jsx(bA,{society:t,impact:l.data}),l.isFetching&&e.jsx("p",{role:"status",className:"text-xs text-muted-foreground",children:"Checking the current numbersâ¦"})]}):e.jsxs("div",{className:"space-y-2","aria-busy":"true","aria-label":"Loading what this affects",children:[e.jsx(Y,{className:"h-4 w-3/4"}),e.jsx(Y,{className:"h-4 w-2/3"}),e.jsx(Y,{className:"h-4 w-1/2"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(T,{htmlFor:"delete-society-confirm",children:["Type ",e.jsx("span",{className:"font-mono font-semibold",children:t.slug})," to confirm"]}),e.jsx(O,{id:"delete-society-confirm",value:m,onChange:j=>c(j.target.value),autoComplete:"off",spellCheck:!1,disabled:n})]}),r!=null&&e.jsx(yA,{error:r})]}),e.jsxs(Ge,{children:[e.jsx(g,{type:"button",variant:"outline",onClick:s,disabled:n,children:"Cancel"}),e.jsx(g,{type:"button",variant:"destructive",onClick:a,disabled:!b,children:n?"Deletingâ¦":"Delete society"})]})]})}function gy(t){return t!=null&&!wi(t)}function yA({error:t}){if(gy(t)){const s=on(t);return e.jsxs("p",{role:"alert",className:"text-destructive",children:[s===void 0?"No answer came back":`The server returned an error (${s})`,", so it isnât known whether the society was deleted; it may still be finishing. Close this and check the list again in a moment before trying again."]})}return e.jsxs("p",{role:"alert",className:"text-destructive",children:[Xn(t,"The society couldnât be deleted.")," Nothing was changed; you can try again."]})}function ha(t,s,a=`${s}s`){return`${t.toLocaleString()} ${t===1?s:a}`}function fy(t){return t.refunds_owed+t.open_disputes+t.checkouts_in_progress>0}function bA({society:t,impact:s}){if(fy(s)){const r=s.checkouts_in_progress;return e.jsxs("p",{role:"alert",className:"rounded-md border border-destructive/40 bg-destructive/5 p-3 text-destructive",children:["Members still have money in flight through ",t.name,"âs Stripe account:"," ",[s.refunds_owed>0&&ha(s.refunds_owed,"refund")+" to send",s.open_disputes>0&&ha(s.open_disputes,"dispute")+" open",r>0&&ha(r,"checkout")+" in progress"].filter(i=>!!i).reduce((i,l,m,c)=>m===0?l:`${i}${m===c.length-1?" and ":", "}${l}`,""),". Settle them first: archiving disconnects Stripe.",r>0&&" An abandoned checkout is cancelled within about an hour; one still pending after that needs looking at in Stripe."]})}const a=s.stale_checkouts??0,n=[a>0&&`${ha(a,"checkout")} pending for over a day never settled; check ${a===1?"it":"them"} in Stripe (archiving doesnât wait for ${a===1?"it":"them"}).`,s.satellite_revokes_pending>0&&`${ha(s.satellite_revokes_pending,"access removal")} still queued for the event app or video library ${s.satellite_revokes_pending===1?"is":"are"} dropped;
3957 check those apps if it matters.`,s.stripe_subscriptions>0&&`Stripe subscriptions from the old checkout arenât cancelled. ${ha(s.stripe_subscriptions,"member")} ${s.stripe_subscriptions===1?"has":"have"} one on record; cancel them in the societyâs Stripe account first.`,"Its slug stays reserved and canât be reused."].filter(Boolean);return e.jsxs(e.Fragment,{children:[e.jsxs("section",{"aria-labelledby":"delete-happens",children:[e.jsx("h3",{id:"delete-happens",className:"font-medium text-foreground",children:"What happens"}),e.jsxs("ul",{className:"mt-1 list-disc space-y-1 pl-5 text-muted-foreground",children:[e.jsx("li",{children:"It disappears from the societies list and the platform dashboard."}),e.jsxs("li",{children:["Everyone is signed out."," ",s.admin_users>0&&`${ha(s.admin_users,"admin or staff account")} ${s.admin_users===1?"is":"are"} deactivated. `,"Members are signed out and canât sign in or sign up",s.is_active?"":" (they already canât, because the society is inactive)","."]}),s.is_active&&e.jsxs("li",{children:["Its public pages",s.custom_domain?` and ${s.custom_domain}`:""," stop working",s.custom_domain?"; the domain is released":"","."]}),e.jsxs("li",{children:["All automations stop: renewal and campaign emails, email-list syncs, and event app and video library updates.",s.auto_renew_charging_enabled&&` Korevera stops charging renewals (${ha(s.auto_renewing_members,"member")} ${s.auto_renewing_members===1?"is":"are"} set up to renew automatically).`]}),s.connections.length>0&&e.jsxs("li",{children:["Disconnected: ",s.connections.join(", "),". Bringing the society back would mean connecting each one again."]}),s.is_active&&s.upcoming_events>0&&e.jsxs("li",{children:[ha(s.upcoming_events,"event")," listed on its public pages (",ha(s.upcoming_registrations,"registration"),")"," ",s.upcoming_events===1?"comes":"come"," down."]})]})]}),e.jsxs("section",{"aria-labelledby":"delete-kept",children:[e.jsx("h3",{id:"delete-kept",className:"font-medium text-foreground",children:"Whatâs kept"}),e.jsxs("p",{className:"mt-1 text-muted-foreground",children:["All of ",t.name,"âs records: ",ha(s.member_records,"member record")," (",s.active_members.toLocaleString()," active)",s.other_records>0&&` and ${ha(s.other_records,"other contact record")}`,", payments, events and emails."]})]}),e.jsxs("section",{"aria-labelledby":"delete-unchanged",className:"rounded-md border border-amber-300 bg-amber-50 p-3 dark:border-amber-900/60 dark:bg-amber-950/20",children:[e.jsxs("h3",{id:"delete-unchanged",className:"flex items-center gap-1.5 font-medium text-amber-800 dark:text-amber-300",children:[e.jsx(Bt,{className:"h-4 w-4 shrink-0","aria-hidden":"true"}),"Not changed by archiving"]}),e.jsx("ul",{className:"mt-1 list-disc space-y-1 pl-5 text-amber-900 dark:text-amber-200",children:n.map(r=>e.jsx("li",{children:r},r))})]})]})}const ih={access_denied:{title:"QuickBooks connection cancelled",body:"The authorization was declined in QuickBooks. No changes were made â connect again when ready."},state_invalid:{title:"QuickBooks connection failed",body:"The authorization link expired or was already used. Start the connect again from this page."},auth_required:{title:"QuickBooks connection failed",body:"Your admin session expired during the QuickBooks authorization. Sign in and connect again."},exchange_failed:{title:"QuickBooks connection failed",body:"QuickBooks rejected the authorization exchange. Connect again; if this repeats, check the Intuit app credentials."},exchange_unavailable:{title:"QuickBooks connection failed",body:"Intuit could not be reached to complete the connection. Connect again in a few minutes."},sync_in_progress:{title:"QuickBooks connection failed",body:"A sync was running for this society while the authorization completed. Wait for it to finish, then connect again â retrying the same authorization will not work."},realm_change_blocked:{title:"QuickBooks company mismatch",body:"This society already has synced records tied to a different QuickBooks company, so connecting a new company is blocked. Reconnect to the original company, or contact support."},internal_error:{title:"QuickBooks connection failed",body:"Something went wrong on our side completing the connection. The error was reported; connect again to retry."}};function jA(t){return t&&Object.hasOwn(ih,t)?{...ih[t],showCode:!1}:{title:"QuickBooks connection failed",body:t?"QuickBooks returned an unrecognized error. Connect again; share the code below with support if it repeats.":"QuickBooks returned an error. Connect again; contact support if it repeats.",showCode:!!t}}function yy(){const[t,s]=ws(),[a,n]=o.useState(null);o.useEffect(()=>{if(a!==null)return;const m=t.get("qbo"),c=t.get("code");n({qbo:m,code:c}),m!==null&&s(d=>{const u=new URLSearchParams(d);return u.delete("qbo"),u.delete("code"),u.has("tab")||u.set("tab","integrations"),u},{replace:!0})},[a]);const[r,i]=o.useState(!1);if(a===null||r||a.qbo===null)return null;if(a.qbo==="connected")return e.jsxs("div",{className:"relative flex items-start gap-3 rounded-lg border border-emerald-200 bg-emerald-50 p-4 dark:border-emerald-900/40 dark:bg-emerald-950/20",children:[e.jsx(Kt,{className:"mt-0.5 h-5 w-5 shrink-0 text-emerald-600 dark:text-emerald-400"}),e.jsxs("div",{className:"min-w-0 flex-1 pr-6",children:[e.jsx("p",{className:"text-sm font-semibold text-emerald-900 dark:text-emerald-100",children:"Qu
3957ickBooks connected"}),e.jsx("p",{className:"mt-1 text-sm text-emerald-700 dark:text-emerald-300",children:"Configure accounts and mappings below, then enable sync."})]}),e.jsx("button",{type:"button","aria-label":"Dismiss",className:"absolute right-3 top-3 flex h-7 w-7 items-center justify-center rounded-md text-emerald-700 transition-colors hover:bg-emerald-100 dark:text-emerald-300 dark:hover:bg-emerald-900/40",onClick:()=>i(!0),children:e.jsx(ms,{className:"h-4 w-4"})})]});const l=jA(a.code);return e.jsxs("div",{className:"relative flex items-start gap-3 rounded-lg border border-destructive/30 bg-destructive/10 p-4",children:[e.jsx(Ca,{className:"mt-0.5 h-5 w-5 shrink-0 text-destructive"}),e.jsxs("div",{className:"min-w-0 flex-1 pr-6",children:[e.jsx("p",{className:"text-sm font-semibold text-destructive",children:l.title}),e.jsx("p",{className:"mt-1 text-sm text-destructive",children:l.body}),l.showCode&&e.jsxs("p",{className:"mt-1 font-mono text-xs",children:["Code: ",a.code]})]}),e.jsx("button",{type:"button","aria-label":"Dismiss",className:"absolute right-3 top-3 flex h-7 w-7 items-center justify-center rounded-md text-destructive transition-colors hover:bg-destructive/10",onClick:()=>i(!0),children:e.jsx(ms,{className:"h-4 w-4"})})]})}function vA(){const t=o.useId(),s=o.useId(),a=kt(),n=Ms(qr()),r=n.readyData,i=Qv(),l=J(),[m,c]=o.useState(""),[d,u]=o.useState("all"),[h,p]=o.useState(null),x=o.useMemo(()=>r?r.filter(k=>{const S=sg(k,m),_=d==="all"||d==="active"&&k.is_active||d==="inactive"&&!k.is_active;return S&&_}):[],[r,m,d]),f=k=>{i.reset(),p(k)},b=()=>vd(l),N=()=>{i.reset(),p(null)},j=()=>{const k=h;k&&i.mutate(k.id,{onSuccess:S=>{const _=S.member_records;p(null),Ut.success(`${k.name} was deleted.`,{description:`Its records are kept, including ${_.toLocaleString()} member ${_===1?"record":"records"}.`}),S.warnings?.length&&Ut.warning("Some things outside Korevera need a look",{description:S.warnings.join(". ")+".",duration:1/0})},onError:S=>{on(S)===404&&(p(null),i.reset(),Ut.info(`${k.name} had already been deleted.`))}})},w=m.trim()!==""||d!=="all",v=()=>{c(""),u("all")};return e.jsxs("div",{className:"space-y-6",children:[e.jsx(yy,{}),e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(ga,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:"Societies"}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"Manage all societies on the platform"})]})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:e.jsxs(g,{onClick:()=>a("/platform/societies/new"),children:[e.jsx(Rt,{className:"mr-2 h-4 w-4"}),"New society"]})})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-4",children:[e.jsxs("div",{className:"relative max-w-sm flex-1",children:[e.jsx(ya,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground","aria-hidden":"true"}),e.jsx(O,{placeholder:"Search by name or slugâ¦","aria-label":"Search societies by name or slug",value:m,onChange:k=>c(k.target.value),className:"pl-9"})]}),e.jsx("span",{id:t,className:"sr-only",children:"Status"}),e.jsxs(qe,{value:d,onValueChange:k=>u(k),children:[e.jsx(Le,{id:s,"aria-labelledby":`${t} ${s}`,className:"w-40",children:e.jsx(Ie,{placeholder:"Status"})}),e.jsxs($e,{children:[e.jsx(q,{value:"all",children:"All statuses"}),e.jsx(q,{value:"active",children:"Active"}),e.jsx(q,{value:"inactive",children:"Inactive"})]})]}),r&&e.jsx("p",{role:"status",className:"text-sm text-muted-foreground",children:w?`${x.length} of ${r.length} societies`:`${r.length} ${r.length===1?"society":"societies"}`})]}),e.jsx(Ma,{view:n,what:"societies"}),n.state==="offline"?e.jsx("div",{className:"rounded-md border",children:e.jsx(Wa,{title:"Societies canât be loaded right now."})}):n.state==="failed"?e.jsx("div",{className:"rounded-md border",children:e.jsx(ja,{title:"Societies couldnât be loaded.",error:n.error,onRetry:n.retry,isRetrying:n.retrying})}):r?e.jsx(xA,{societies:x,onDelete:f,emptyState:r&&r.length>0&&w?e.jsx(tn,{title:"No societies match your search.",action:e.jsx(g,{variant:"outline",onClick:v,children:"Clear filters"})}):e.jsx(tn,{title:"No societies yet.",description:"Create a society to start onboarding its members.",action:e.jsxs(g,{onClick:()=>a("/platform/societies/new"),children:[e.jsx(Rt,{className:"mr-2 h-4 w-4"}),"Create the first society"]})})}):e.jsxs("div",{className:"space-y-4",children:[e.jsx(Y,{className:"h-12 w-full"}),e.jsx(Y,{className:"h-12 w-full"}),e.jsx(Y,{className:"h-12 w-full"})]}),e.jsx(gA,{society:h,open:!!h,onOpenChange:k=>!k&&N(),onConfirm:j,isDeleting:i.isPending,error:i.error,onAlreadyDeleted:b})]})}function wA(t){const s=o.useRef(!1),a=ta();o.useEffect(()=>{s.current=!1},[a.key]);const n=o.useCallback(({currentLocation:l,nextLocation:m})=>t&&!s.current&&l.pathname!==m.pathname,[t]),r=Uy(n);zy(o.useCallback(l=>{t&&(l.preventDefault(),l.returnValue="")},[t]));const i=o.useCallback(()=>{s.current=!0},[]);return{blocker:r,allowNextNavigation:i}}function Ri({children:t}){return e.jsxs("p",{className:"mt-1.5 flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(Ar,{className:"h-3.5 w-3.5 shrink-0","aria-hidden":"true"}),e.jsx("span",{children:t})]})}function NA({societyId:t}
3957){const[s,a]=o.useState(""),[n,r]=o.useState(0),[i,l]=o.useState(!1),{data:m,isLoading:c,refetch:d,isFetching:u}=h0(t),h=p0(),p=x0(),x=J(),f=async()=>{const y=s.trim().toLowerCase();if(y)try{await h.mutateAsync({societyId:t,data:{domain:y}}),a("")}catch{}},b=async()=>{try{await p.mutateAsync(t),l(!1)}catch{}},N=()=>{x.invalidateQueries({queryKey:["domain-status",t]}),d()},j=o.useRef(void 0);o.useEffect(()=>()=>clearTimeout(j.current),[]);const w=async y=>{if(y){try{await navigator.clipboard.writeText(y)}catch{Ut.error("Couldnât copy. Select the target and copy it instead.");return}clearTimeout(j.current),r(C=>C+1),j.current=setTimeout(()=>r(0),2e3)}};if(c)return e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(bl,{className:"h-4 w-4"})}),"Custom domain"]})}),e.jsx($,{children:e.jsx("div",{className:"h-20 animate-pulse rounded bg-muted"})})]});const v=m?.configured,k=m?.status==="active"&&m?.ssl_status==="active",S=v&&!k&&m?.status!=="deleted",_=(m?.verification_errors?.length??0)>0||(m?.ssl_validation_errors?.length??0)>0;return e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsxs(ne,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(ie,{className:"flex items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(bl,{className:"h-4 w-4"})}),"Custom domain"]}),v&&k&&e.jsxs("span",{className:"inline-flex items-center gap-1.5 whitespace-nowrap",children:[e.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-emerald-500"}),e.jsx("span",{className:"text-xs font-medium",children:"Active"})]}),S&&e.jsxs("span",{className:"inline-flex items-center gap-1.5 whitespace-nowrap",children:[e.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-amber-500"}),e.jsx("span",{className:"text-xs font-medium",children:"Pending"})]})]}),e.jsx(Ri,{children:"Domain changes apply as soon as you confirm them."})]}),e.jsxs($,{className:"space-y-4",children:[!v&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"custom-domain-input",children:"Domain"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(O,{id:"custom-domain-input",value:s,onChange:y=>a(y.target.value),placeholder:"ams.flgastro.org",onKeyDown:y=>{y.key==="Enter"&&(y.preventDefault(),f())}}),e.jsx(g,{type:"button",onClick:f,disabled:!s.trim()||h.isPending,children:h.isPending?"Configuringâ¦":"Configure"})]}),h.isError&&e.jsx("p",{className:"text-sm text-destructive",children:Ni(h.error)??(h.error?.message||"Failed to configure domain")})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Configure a custom domain so members can access the portal at"," ",e.jsx("span",{className:"font-mono",children:"https://your-domain.org/portal"})," instead of the default korevera.com URL. After configuring, you'll need to add a CNAME record at your DNS provider."]})]}),v&&k&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between rounded-lg border border-emerald-200 bg-emerald-50 p-3 dark:border-emerald-900/40 dark:bg-emerald-950/20",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-mono text-sm font-medium text-emerald-900 dark:text-emerald-100",children:m.domain}),e.jsx("p",{className:"text-xs text-emerald-700 dark:text-emerald-300",children:"SSL active â portal accessible via custom domain"})]}),e.jsxs("a",{href:`https://${m.domain}/portal`,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1 text-sm text-emerald-700 hover:text-emerald-900 dark:text-emerald-300 dark:hover:text-emerald-100",children:["Visit ",e.jsx(Rs,{className:"h-3.5 w-3.5"})]})]}),e.jsx("div",{className:"flex gap-2",children:i?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Remove this domain?"}),e.jsx(g,{type:"button",variant:"destructive",size:"sm",onClick:b,disabled:p.isPending,children:p.isPending?"Removingâ¦":"Confirm"}),e.jsx(g,{type:"button",variant:"ghost",size:"sm",onClick:()=>l(!1),children:"Cancel"})]}):e.jsxs(g,{type:"button",variant:"outline",size:"sm",className:"text-destructive hover:text-destructive",onClick:()=>l(!0),children:[e.jsx(Ft,{className:"mr-1.5 h-3.5 w-3.5"}),"Remove"]})})]}),S&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"rounded-lg border border-amber-200 bg-amber-50 p-3 dark:border-amber-900/40 dark:bg-amber-950/20",children:[e.jsx("p",{className:"font-mono text-sm font-medium text-amber-900 dark:text-amber-100",children:m?.domain}),e.jsx("p",{className:"mt-1 text-xs text-amber-700 dark:text-amber-300",children:"Waiting for DNS verification. Add the CNAME record below, then check status."})]}),e.jsxs("div",{className:"space-y-3 rounded-lg border bg-muted/50 p-4",children:[e.jsx("p",{className:"text-sm font-medium",children:"Add this CNAME record at your DNS provider:"}),e.jsxs("div",{className:"grid gap-2 text-sm sm:grid-cols-[auto_1fr]",children:[e.jsx("span",{className:"font-medium text-muted-foreground",children:"Name:"}),e.jsx("code",{className:"rounded bg-background px-2 py-1 font-mono text-xs",children:m?.domain}),e.jsx("span",{className:"font-medium text-muted-foreground",children:"Target:"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("code",{className:"flex-1 rounded bg-background px-2 py-1 font-mono text-xs",children:m?.cname_target}),e.jsx(g,{type:"button",variant:"ghost",size:"sm",className:"h-11 w-11 shrink-0 p-0 lg:h-7 lg:w-7",onClick:()=>{w(m?.cname_target||"")},"aria-label":"Copy CNAME target",children:n?e.jsx(Xt,{className:"h-3.5 w-3.5 text-emerald-600","aria-hidden":"true"}):e.jsx(za,{className:"h-3.5 w-3.5","aria-hidden":"true"})}),e.jsx("span",{role:"status",className:"sr-only",children:n===0?"":n===1?"CNAME target copied":`CNAME target copied (${n} times)`})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"SSL will be provisioned automatically once the CNAME is detected by Cloudflare. DNS propagation can take up to 24 hours."})]}),_&&e.jsxs("div",{className:"space-y-1 rounded-lg border border-red-200 bg-red-50 p-3 dark:border-red-900/40 dark:bg-red-950/20",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-sm font-medium text-red-800 dark:text-red-200",children:[e.jsx(Dt,{className:"h-4 w-4"}),"Verification issues"]}),e.jsxs("ul",{className:"list-disc space-y-0.5 pl-5 text-xs text-red-700 dark:text-red-300",children:[m?.verification_errors?.map((y,C)=>e.jsx("li",{children:y},C)),m?.ssl_validation_errors?.map((y,C)=>e.jsx("li",{children:y},`ssl-${C}`))]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(g,{type:"button",variant:"outline",size:"sm",onClick:N,disabled:u,children:[e.jsx(St,{className:`mr-1.5 h-3.5 w-3.5 ${u?"animate-spin":""}`}),u?"Checkingâ¦":"Check status"]}),i?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Remove?"}),e.jsx(g,{type:"button",variant:"destructive",size:"sm",onClick:b,disabled:p.isPending,children:p.isPending?"Removingâ¦":"Confirm"}),e.jsx(g,{type:"button",variant:"ghost",size:"sm",onClick:()=>l(!1),children:"Cancel"})]}):e.jsxs(g,{type:"button",variant:"outline",size:"sm",className:"text-destructive hover:text-destructive",onClick:()=>l(!0),children:[e.jsx(Ft,{className:"mr-1.5 h-3.5 w-3.5"}),"Remove"]})]})]})]})]})}const zd=o.createContext(null),kA=zd.Provider;function _A(){return o.useContext(zd)}function Bd(){const t=o.useContext(zd);return o.useCallback((s,a)=>(n,r)=>t&&Object.is(n,t[s])?!0:a(n,r),[t])}
3957const by=o.createContext(()=>{}),SA=by.Provider;function CA(){return o.useContext(by)}function jo({disabled:t,className:s="space-y-6",children:a}){const n=CA();return e.jsxs("form",{noValidate:!0,onSubmit:r=>{r.preventDefault(),n()},children:[e.jsx("fieldset",{disabled:t,className:`m-0 min-w-0 border-0 p-0 ${s}`,children:a}),e.jsx("button",{type:"submit",className:"sr-only",tabIndex:-1,"aria-hidden":"true"})]})}function PA(t){try{const s=new URL(t.trim());return s.protocol==="https:"||s.protocol==="http:"}catch{return!1}}function AA({isEditing:t,societyId:s,disabled:a,active:n=!0}){const{register:r,watch:i,setValue:l,formState:{errors:m}}=Rr(),c=Bd();return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(jo,{disabled:a,children:[e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(ga,{className:"h-4 w-4"})}),"Basic information"]})}),e.jsxs($,{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"name",children:"Society name *"}),e.jsx(O,{id:"name",...r("name",{validate:c("name",d=>!!d.trim()||"Name is required")}),placeholder:"Florida Gastroenterologic Society"}),m.name&&e.jsx("p",{className:"text-sm text-destructive",children:m.name.message})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"slug",children:"Slug *"}),e.jsx(O,{id:"slug",...r("slug",t?{}:{required:"Slug is required",pattern:{value:/^[a-z0-9-]+$/,message:"Slug must contain only lowercase letters, numbers, and hyphens"}}),placeholder:"fgs",disabled:t}),m.slug&&e.jsx("p",{className:"text-sm text-destructive",children:m.slug.message}),t&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Slug cannot be changed after creation"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"description",children:"Description"}),e.jsx(It,{id:"description",...r("description"),placeholder:"A brief description of the societyâ¦",rows:3,"aria-invalid":!!m.description}),m.description&&e.jsx("p",{className:"text-sm text-destructive",children:m.description.message})]})]})]}),e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx($t,{className:"h-4 w-4"})}),"Contact information"]})}),e.jsxs($,{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"contact_email",children:"Contact email *"}),e.jsx(O,{id:"contact_email",type:"email",...r("contact_email",{validate:c("contact_email",d=>d.trim()?/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(d)||"Invalid email address":"Email is required")}),placeholder:"[email protected]"}),m.contact_email&&e.jsx("p",{className:"text-sm text-destructive",children:m.contact_email.message})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"contact_phone",children:"Contact phone"}),e.jsx(O,{id:"contact_phone",...r("contact_phone"),placeholder:"(555) 123-4567","aria-invalid":!!m.contact_phone}),m.contact_phone&&e.jsx("p",{className:"text-sm text-destructive",children:m.contact_phone.message})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"website_url",children:"Website URL"}),e.jsx(O,{id:"website_url",type:"url",...r("website_url",{validate:c("website_url",d=>!d.trim()||PA(d)?!0:"Enter a full web address (https://â¦)")}),placeholder:"https://society.org"}),m.website_url&&e.jsx("p",{className:"text-sm text-destructive",children:m.website_url.message})]})]})]}),t&&e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy
3957/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(Cp,{className:"h-4 w-4"})}),"Status"]})}),e.jsx($,{children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"society-is-active",children:"Active status"}),e.jsxs(qe,{name:"is_active",disabled:a,value:i("is_active")?"true":"false",onValueChange:d=>l("is_active",d==="true",{shouldDirty:!0}),children:[e.jsx(Le,{className:"w-48",children:e.jsx(Ie,{})}),e.jsxs($e,{children:[e.jsx(q,{value:"true",children:"Active"}),e.jsx(q,{value:"false",children:"Inactive"})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Inactive societies will not be accessible to society admins"})]})})]})]}),t&&s&&n&&e.jsx(NA,{societyId:s})]})}function EA({societyId:t,logoUrl:s,faviconUrl:a,disabled:n,active:r=!0}){const{control:i}=Rr(),l=Bd();return e.jsxs("div",{className:"space-y-6",children:[r&&e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsxs(ne,{className:"pb-3",children:[e.jsxs(ie,{className:"flex items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx(pa,{icon:Wl}),"Logo and favicon"]}),e.jsx(Ri,{children:"Uploading or removing an image saves immediately."})]}),e.jsxs($,{className:"space-y-6",children:[e.jsx(Pl,{societyId:t,kind:"logo",url:s}),e.jsxs("div",{className:"border-t pt-4",children:[e.jsx("p",{className:"mb-3 text-sm font-medium",children:"Favicon (browser and home-screen icon)"}),e.jsx(Pl,{societyId:t,kind:"favicon",url:a})]})]})]}),e.jsx(jo,{disabled:n,className:"",children:e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx(pa,{icon:Vl}),"Brand color"]})}),e.jsx($,{children:e.jsx(qa,{name:"primary_color",control:i,rules:{validate:l("primary_color",m=>Al.test(m)||"Must be a valid hex color (e.g. #1a365d)")},render:({field:m,fieldState:c})=>e.jsx(lf,{inputRef:m.ref,value:m.value,onChange:m.onChange,onBlur:m.onBlur,error:c.error?.message,disabled:n})})})]})})]})}const vo=[{key:"commerce_enabled",defaultOn:!0,label:"Commerce",description:"Events, Products, Donations, Orders"},{key:"committees_enabled",defaultOn:!0,label:"Committees",description:"Committee management and applications"},{key:"mailchimp_enabled",defaultOn:!0,label:"Mailchimp integration",description:"Audience sync with Mailchimp"},{key:"mailerlite_enabled",defaultOn:!0,label:"MailerLite integration",description:"Group sync with MailerLite"},{key:"member_directory_enabled",defaultOn:!0,label:"Member directory",description:"Searchable member directory in the portal"},{key:"phase3_link_merge_enabled",defaultOn:!1,label:"Account matching for returning members",description:"When enabled, new attendees who match a lapsed member record are prompted to verify their identity (via a one-time code) and merge accounts at event registration."},{key:"phase4_paid_renewal_enabled",defaultOn:!1,label:"Renewal at event checkout",description:"When enabled, lapsed or expired members are prompted to renew their dues at event checkout â paying for renewal + event in one transaction and unlocking the member event rate."},{key:"template_event_1to1_enabled",defaultOn:!1,label:"Synced event registration forms",description:"Edit a registration form template once and see your changes on every event using it. If you later delete a template, each event keeps its own copy so existing registrations stay intact."}],Kd=vo.map(t=>t.key),TA=["January","February","March","April","May","June","July","August","September","October","November","December"];function FA({disabled:t}){const{register:s,watch:a,control:n,setValue:r,clearErrors:i,formState:{errors:l}}=Rr(),m=Bd(),c=_A();return e.jsx(jo,{disabled:t,children:e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy
3957/40 dark:text-sky-300",children:e.jsx(Yt,{className:"h-4 w-4"})}),"Dues cycle settings"]})}),e.jsxs($,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{children:"Cycle type"}),e.jsx(qa,{name:"dues_cycle_type",control:n,render:({field:d})=>e.jsxs("div",{className:"flex gap-4",children:[e.jsxs("label",{className:`flex cursor-pointer items-center gap-2 rounded-lg border px-4 py-2 transition-colors ${d.value==="calendar"?"border-primary bg-primary/5":"border-muted"}`,children:[e.jsx("input",{type:"radio",name:"dues_cycle_type",value:"calendar",checked:d.value==="calendar",onChange:()=>d.onChange("calendar"),className:"accent-primary"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium",children:"Calendar year"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"All members expire on the same date"})]})]}),e.jsxs("label",{className:`flex cursor-pointer items-center gap-2 rounded-lg border px-4 py-2 transition-colors ${d.value==="anniversary"?"border-primary bg-primary/5":"border-muted"}`,children:[e.jsx("input",{type:"radio",name:"dues_cycle_type",value:"anniversary",checked:d.value==="anniversary",onChange:()=>{d.onChange("anniversary"),c&&(r("dues_cycle_start_month",c.dues_cycle_start_month),r("dues_cycle_start_day",c.dues_cycle_start_day)),i(["dues_cycle_start_month","dues_cycle_start_day"])},className:"accent-primary"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium",children:"Anniversary"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Each member expires 1 year from join/renewal"})]})]})]})})]}),a("dues_cycle_type")==="calendar"&&e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"dues-cycle-start-month",children:"Dues cycle start month"}),e.jsx(qa,{name:"dues_cycle_start_month",control:n,render:({field:d})=>e.jsxs(qe,{name:"dues_cycle_start_month",disabled:t,value:String(d.value),onValueChange:u=>d.onChange(parseInt(u)),children:[e.jsx(Le,{children:e.jsx(Ie,{placeholder:"Select month"})}),e.jsx($e,{children:TA.map((u,h)=>e.jsx(q,{value:String(h+1),children:u},u))})]})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"dues_cycle_start_day",children:"Start day"}),e.jsx(O,{id:"dues_cycle_start_day",type:"number",min:1,max:31,...s("dues_cycle_start_day",{valueAsNumber:!0,validate:m("dues_cycle_start_day",d=>Number.isInteger(d)?d>=1&&d<=31||"Day must be between 1 and 31":"Enter a whole-number start day")})}),l.dues_cycle_start_day&&e.jsx("p",{className:"text-sm text-destructive",children:l.dues_cycle_start_day.message})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"grace_period_days",children:"Grace period (days)"}),e.jsx(O,{id:"grace_period_days",type:"number",min:0,...s("grace_period_days",{valueAsNumber:!0,validate:m("grace_period_days",d=>Number.isInteger(d)?d>=0||"Grace period cannot be negative":"Enter a whole number of days")})}),l.grace_period_days&&e.jsx("p",{className:"text-sm text-destructive",children:l.grace_period_days.message})]})]})]})})}function RA({societyId:t}){return e.jsx(L,{className:"min-w-0 overflow-hidden",children:e.jsxs($,{className:"flex flex-wrap items-center justify-between gap-3 p-4 text-sm",children:[e.jsx("p",{className:"text-muted-foreground",children:"Membership types, prices and auto-renewal are managed in the society workspace. Feature switches (Commerce, Committeesâ¦) are on the Features tab."}),e.jsx(g,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs(je,{to:Br(t,"/membership-types"),children:[e.jsx(gi,{className:"mr-2 h-4 w-4","aria-hidden":"true"}),"Membership types"]})})]})})}const lh="We typically reply within a few hours.";function MA({societyId:t}){const s=J(),{data:a}=re({queryKey:["platform","support-chat",t],queryFn:async()=>(await F.get(`/societies/${t}/support-chat`)).data}),[n,r]=o.useState(void 0),[i,l]=o.useState(void 0),m=n??a?.support_chat_enabled??!1,c=i??a?.support_chat_response_time_text??lh,d=W({mutationFn:()=>F.patch(`/societies/${t}/support-chat`,{enabled:m,response_time_text:c}),onSuccess:()=>{r(void 0),l(void 0),s.invalidateQueries({queryKey:["platform","support-chat",t]})}});return e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsxs(ne,{className:"pb-3",children:[e.jsxs(ie,{className:"flex items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx(pa,{icon:Gc}
3957),"Support chat"]}),e.jsx(Ri,{children:"Saved with its own button, not with the changes above."})]}),e.jsxs($,{className:"space-y-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Allow portal members to open a live chat that relays to a central Slack channel. Replies flow back to the member in real time and by email when they're away."}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-4",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(T,{htmlFor:"support-chat-enabled",children:"Enabled"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Show the chat widget on the portal"})]}),e.jsx(ss,{id:"support-chat-enabled",checked:m,onCheckedChange:r})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"support-response-time",children:"Response-time text"}),e.jsx(O,{id:"support-response-time",value:c,onChange:u=>l(u.target.value),placeholder:lh,maxLength:200}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Shown to members in the welcome message when they open a new conversation."})]}),e.jsx(g,{type:"button",size:"sm",onClick:()=>d.mutate(),disabled:d.isPending,children:d.isPending?"Savingâ¦":"Save support chat"}),d.isSuccess&&e.jsx("p",{role:"status",className:"text-xs text-emerald-700 dark:text-emerald-400",children:"Support chat saved."}),d.isError&&e.jsx("p",{role:"alert",className:"text-xs text-destructive",children:"Support chat wasnât saved. Please try again."})]})]})}const oh={stripe:"Stripe",mailchimp:"Mailchimp (with an audience chosen)",mailerlite:"MailerLite (with a group chosen)",email:"the email sender (a From address)"},DA={commerce_enabled:{connections:["stripe"]},mailchimp_enabled:{connections:["mailchimp"],optional:!0},mailerlite_enabled:{connections:["mailerlite"],optional:!0},phase3_link_merge_enabled:{features:["commerce_enabled"],connections:["email"]},phase4_paid_renewal_enabled:{features:["commerce_enabled"],connections:["stripe"]},template_event_1to1_enabled:{features:["commerce_enabled"]}}
3957,LA={mailchimp:"an audience",mailerlite:"a group"},ch=Object.fromEntries(vo.map(t=>[t.key,t.label]));function $A({societyId:t,disabled:s,onOpenTab:a,active:n=!0}){const{control:r,watch:i}=Rr(),l=i("modules"),m=n?t:void 0,c=to(m).data,d=tr(m).data,u=sr(m).data,h=Or(m).data,p=Wx(m).data,x={mailchimp:d?.mailchimp_connected,mailerlite:u?.mailerlite_connected},f={mailchimp:!!d?.list_id,mailerlite:!!u?.group_id},b={stripe:c?.stripe_connected,mailchimp:d&&x.mailchimp&&f.mailchimp,mailerlite:u&&x.mailerlite&&f.mailerlite,email:h&&!!h.from_address};return e.jsxs("div",{className:"space-y-6",children:[e.jsx(jo,{disabled:s,children:e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsxs(ne,{className:"pb-3",children:[e.jsxs(ie,{className:"flex items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx(pa,{icon:gi}),"Features"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"What this society uses. Changes are saved with the rest of your changes; what a feature needs is set up on the tab it names."})]}),e.jsx($,{className:"space-y-4",children:vo.map(N=>{const j=`module-${N.key}`,w=DA[N.key],v=l?.[N.key]===!0,k=(w?.features??[]).filter(C=>l?.[C]!==!0),S=(w?.connections??[]).filter(C=>b[C]===!1),_=S.find(C=>x[C]&&!f[C]),y=v&&k.length===0&&(w?.connections??[]).every(C=>b[C]===!0);return e.jsxs("div",{className:"space-y-3 rounded-lg border p-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(T,{htmlFor:j,children:N.label}),e.jsx("p",{className:"text-sm text-muted-foreground",children:N.description})]}),e.jsx(qa,{name:`modules.${N.key}`,control:r,render:({field:C})=>e.jsx(ss,{id:j,disabled:s,checked:C.value,onCheckedChange:C.onChange,"aria-describedby":w?`${j}-needs`:void 0})})]}),w&&e.jsx("div",{id:`${j}-needs`,className:"text-sm",children:v&&w.optional&&S.length>0?e.jsxs("p",{className:"text-muted-foreground",children:[_?`Connected; choose ${LA[_]} to sync with.`:"Not connected yet."," ",e.jsx(g,{type:"button",variant:"link",className:"h-auto p-0 text-sm",onClick:()=>a("integrations"),children:_?"Choose in Integrations":"Connect in Integrations"})]}):v&&(k.length>0||S.length>0)?e.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 text-amber-800 dark:text-amber-300",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(Dt,{className:"h-4 w-4 shrink-0","aria-hidden":"true"}),"Needs"," ",[...k.map(C=>`${ch[C]} turned on`),...S.map(C=>`${oh[C]} set up`)].join(" and "),"."]}),S.length>0&&e.jsx(g,{type:"button",variant:"link",className:"h-auto p-0 text-sm",onClick:()=>a("integrations"),children:"Set up in Integrations"})]}):y?e.jsxs("p",{className:"inline-flex items-center gap-1.5 text-muted-foreground",children:[e.jsx(Kt,{className:"h-4 w-4 shrink-0 text-emerald-600","aria-hidden":"true"}),"Everything it needs is set up."]}):!v&&e.jsxs("p",{className:"text-muted-foreground",children:["Needs"," ",[...(w.features??[]).map(C=>ch[C]),...(w.connections??[]).map(C=>oh[C])].join(" and "),"."]})})]},N.key)})})]})}),e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx(pa,{icon:nj}),"Video library"]})}),e.jsxs($,{className:"flex flex-wrap items-center justify-between gap-3 text-sm",children:[e.jsx("p",{className:"text-muted-foreground",children:p===void 0?"Checkingâ¦":p.configured&&p.enabled?"On. Members reach it from the portal.":"Off. It turns on when the library is provisioned under Integrations."}),e.jsx(g,{type:"button",variant:"outline",size:"sm",onClick:()=>a("integrations"),children:"Open Integrations"})]})]}),n&&e.jsx(MA,{societyId:t})]})}function qA(t,s){return`/qbo/records/${t}/${s}`}function al(t,s){return`/qbo/tieout-flags/${t}/${s}`}function Mi(t){if(!t)return null;const s=Ct(t);return Number.isNaN(s.getTime())?null:s}function IA(t,s){const a=window.URL.createObjectURL(t),n=document.createElement("a");n.href=a,n.download=s,document.body.appendChild(n),n.click(),window.URL.revokeObjectURL(a),document.body.removeChild(n)}function OA(t,s){if(typeof t=="string"){const a=/filename="?([^"]+)"?/.exec(t);if(a?.[1])return a[1]}return s}const As={getConnectUrl:async t=>(await F.get("/qbo/connect-url",{params:{society_id:t}})).data,disconnect:async(t,s)=>(await F.post("/qbo/disconnect",{society_id:t,force:s})).data,getConfig:async t=>(await F.get("/qbo/config",{params:{society_id:t}})).data,updateConfig:async(t,s)=>(await F.put("/qbo/config",s,{params:{society_id:t}})).data,listAccounts:async t=>(await F.get("/qbo/accounts",{params:{society_id:t}})).data,listItems:async t=>(await F.get("/qbo/items",{params:{society_id:t}})).data,listClasses:async t=>(await F.get("/qbo/classes",{params:{society_id:t}})).data,createClass:async(t,s,a)=>(await F.post("/qbo/classes",{society_id:t,name:s,expected_realm_id:a})).data,listCategories:async t=>(await F.get("/qbo/categories",{params:{society_id:t}})).data,getSyncStatus:async t=>(await F.get("/qbo/sync-status",{params:{society_id:t}})).data,getActivity:async t=>(await F.get("/qbo/activity",{params:{society_id:t}})).data,exportRecordsCsv:async t=>{const s=await F.get("/qbo/records.csv",{params:{society_id:t},responseType:"blob"}),a=OA(s.headers["content-disposition"],"quickbooks_ledger.csv");IA(s.data,a)},retryNow:async t=>(await F.post("/qbo/retry-now",{society_id:t})).data,recoverRecord:async(t,s,a,n,r,i)=>(await F.post(qA(s,t),{society_id:a,note:n,qbo_id:r??null,qbo_doc_number:i??null})).data,getTieoutFlags:async t=>(await F.get("/qbo/tieout-flags",{params:{society_id:t}})).data,tieOutNow:async(t,s)=>(await F.post("/qbo/tie-out-now",{society_id:t,period:s??null})).data,acknowledgeTieoutFlag:async(t,s,a)=>(await F.post(al(t,"acknowledge"),{society_id:s,note:a})).data,retargetTieoutFlag:async(t,s,a,{qboId:n,qboDocNumber:r}={})=>(await F.post(al(t,"retarget"),{society_id:s,note:a,qbo_id:n??null,qbo_doc_number:r??null})).data,convertTieoutFlagExternal:async(t,s,a)=>(await F.post(al(t,"convert-external"),{society_id:s,note:a})).data,resolveTieoutFlagSlots:async(t,s,a,n)=>(await F.post(al(t,"resolve-slots"),{society_id:s,note:a,dispositions:n})).data};function Qd(t){return re({queryKey:["qbo-config",t],queryFn:()=>As.getConfig(t),enabled:!!t})}function UA(t){return re({queryKey:["qbo-sync-status",t],queryFn:()=>As.getSyncStatus(t),enabled:!!t})}function zA(t){return re({queryKey:["qbo-activity",t],queryFn:()=>As.getActivity(t),enabled:!!t})}function BA(t,s){return re({queryKey:["qbo-accounts",t],queryFn:()=>As.listAccounts(t),enabled:!!t&&s})}function KA(t,s){return re({queryKey:["qbo-items",t],queryFn:()=>As.listItems(t),enabled:!!t&&s})}function QA(t,s){return re({queryKey:["qbo-classes",t],queryFn:()=>As.listClasses(t),enabled:!!t&&s})}function WA(t){return re({queryKey:["qbo-categories",t],queryFn:()=>As.listCategories(t),enabled:!!t})}function VA(){return W({mutationFn:({societyId:t})=>As.getConnectUrl(t),onSuccess:({url:t})=>{window.location.href=t}})}function nl(){const t=J();return W({mutationFn:({societyId:s,data:a})=>As.updateConfig(s,a),meta:{suppressErrorToast:!0},onSettled:(s,a,{societyId:n})=>{t.invalidateQueries({queryKey:["qbo-config",n]})}})}function GA(){const t=J();return W({mutationFn:({societyId:s,force:a})=>As.disconnect(s,a),meta:{suppressErrorToast:!0},onSettled:(s,a,{societyId:n})=>{t.invalidateQueries({queryKey:["qbo-config",n]})}})}
3957function YA(){const t=J();return W({mutationFn:({societyId:s,name:a,expectedRealmId:n})=>As.createClass(s,a,n),meta:{suppressErrorToast:!0},onSuccess:(s,{societyId:a})=>{t.invalidateQueries({queryKey:["qbo-classes",a]})},onSettled:(s,a,{societyId:n})=>{t.invalidateQueries({queryKey:["qbo-config",n]})}})}function HA(){const t=J();return W({mutationFn:({societyId:s})=>As.retryNow(s),meta:{suppressErrorToast:!0},onSettled:(s,a,{societyId:n})=>{t.invalidateQueries({queryKey:["qbo-sync-status",n]}),t.invalidateQueries({queryKey:["qbo-config",n]}),t.invalidateQueries({queryKey:["qbo-activity",n]})}})}function JA(){const t=J();return W({mutationFn:({kind:s,recordId:a,societyId:n,note:r,qboId:i,qboDocNumber:l})=>As.recoverRecord(s,a,n,r,i,l),meta:{suppressErrorToast:!0},onSettled:(s,a,{societyId:n})=>{t.invalidateQueries({queryKey:["qbo-sync-status",n]}),t.invalidateQueries({queryKey:["qbo-config",n]}),t.invalidateQueries({queryKey:["qbo-activity",n]})}})}function jy(t){return re({queryKey:["qbo-tieout-flags",t],queryFn:()=>As.getTieoutFlags(t),enabled:!!t})}function ZA(){const t=J();return W({mutationFn:({societyId:s,period:a})=>As.tieOutNow(s,a),meta:{suppressErrorToast:!0},onSettled:(s,a,{societyId:n})=>{t.invalidateQueries({queryKey:["qbo-tieout-flags",n]}),t.invalidateQueries({queryKey:["qbo-sync-status",n]}),t.invalidateQueries({queryKey:["qbo-config",n]}),t.invalidateQueries({queryKey:["qbo-activity",n]})}})}function XA(){const t=J();return W({mutationFn:({action:s,flagId:a,societyId:n,note:r,qboId:i,qboDocNumber:l,dispositions:m})=>{switch(s){case"acknowledge":return As.acknowledgeTieoutFlag(a,n,r);case"retarget":return As.retargetTieoutFlag(a,n,r,{qboId:i,qboDocNumber:l});case"convert-external":return As.convertTieoutFlagExternal(a,n,r);case"resolve-slots":return As.resolveTieoutFlagSlots(a,n,r,m??[])}},meta:{suppressErrorToast:!0},onSettled:(s,a,{societyId:n})=>{t.invalidateQueries({queryKey:["qbo-tieout-flags",n]}),t.invalidateQueries({queryKey:["qbo-sync-status",n]}),t.invalidateQueries({queryKey:["qbo-config",n]}),t.invalidateQueries({queryKey:["qbo-activity",n]})}})}const eE=[{key:"stripe",name:"Stripe",description:"Accept payments for memberships, events, and merchandise.",fields:[{name:"stripe_publishable_key",label:"Publishable key",type:"text",placeholder:"pk_live_...",required:!0},{name:"stripe_secret_key",label:"Secret key",type:"password",placeholder:"sk_live_...",required:!0},{name:"stripe_webhook_secret",label:"Webhook secret",type:"password",placeholder:"whsec_...",required:!1}]},{key:"mailchimp",name:"Mailchimp",description:"Sync members to Mailchimp audiences for email campaigns.",fields:[{name:"mailchimp_api_key",label:"API key",type:"password",placeholder:"xxxxxxxxxxxxxxxx-us14",required:!0},{name:"mailchimp_server_prefix",label:"Server prefix",type:"text",placeholder:"us14",required:!0,hint:"Found after the dash in your API key (e.g., us14)"}]},{key:"mailerLite",name:"MailerLite",description:"Sync members to MailerLite groups for email campaigns.",fields:[{name:"mailerlite_api_key",label:"API key",type:"password",placeholder:"Enter MailerLite API key",required:!0,hint:"Found in MailerLite â Integrations â API"}]},{key:"eventApp",name:"Event App",description:"Import events, push attendees, and support Event App to AMS services.",fields:[{name:"base_url",label:"Base URL",type:"text",placeholder:"https://events.example.org/events",required:!0},{name:"import_key",label:"Import API key",type:"password",placeholder:"Enter import API key",required:!0},{name:"api_key",label:"AMS API key",type:"password",placeholder:"Optional: key Event App uses to call AMS",required:!1,hint:"Needed for Event App -> AMS features like delegated email sending."}]},{key:"email",name:"Email sender",description:"Configure how this society sends transactional emails.",fields:[]},{key:"memberClicks",name:"MemberClicks",description:"Import members from a MemberClicks account.",fields:[{name:"org_id",label:"Organization ID",type:"text",placeholder:"your-org",required:!0,hint:'The subdomain from your MemberClicks URL (e.g. "your-org" from your-org.memberclicks.net)'},{name:"client_id",label:"Client ID",type:"password",placeholder:"Enter OAuth client ID",required:!0},{name:"client_secret",label:"Client secret",type:"password",placeholder:"Enter OAuth client secret",required:!0}]},{key:"videoLibrary",name:"Video Library",description:"Connect a video library instance for member SSO and content access.",fields:[]},{key:"quickBooks",name:"QuickBooks Online",description:"Post Stripe payments, refunds, and payouts to QuickBooks automatically.",fields:[]}];function tE({className:t}){return e.jsxs("svg",{className:t,viewBox:"0 0 40 40",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[e.jsx("rect",{width:"40",height:"40",rx:"8",fill:"#635BFF"}),e.jsx("path",{d:"M18.64 16.95c0-1.08.89-1.5 2.36-1.5 2.11 0 4.78.64 6.89 1.78V11.3a18.25 18.25 0 00-6.89-1.27c-5.63 0-9.37 2.94-9.37 7.85 0 7.66 10.55 6.44 10.55 9.74 0 1.28-1.11 1.7-2.67 1.7-2.31 0-5.27-.95-7.61-2.23v6.04a19.34 19.34 0 007.61 1.62c5.77 0 9.73-2.85 9.73-7.83-.01-8.27-10.6-6.8-10.6-9.97z",f
3957ill:"white"})]})}function sE({className:t}){return e.jsxs("svg",{className:t,viewBox:"0 0 40 40",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[e.jsx("rect",{width:"40",height:"40",rx:"8",fill:"#FFE01B"}),e.jsx("path",{d:"M27.5 22.8c-.2-.1-.4 0-.5.1-.3.4-.7.6-1.1.7-.2 0-.3 0-.4-.1-.1-.2 0-.5.1-.8.2-.5.3-1 .2-1.4-.1-.5-.5-.8-1-.8-.1 0-.3 0-.4.1-.8.3-1.4.9-1.9 1.6 0 0-.3-.6-.3-.6-.1-.2-.3-.3-.5-.2-.2.1-.3.3-.2.5l.5 1.1c-.4.7-.7 1.2-.8 1.7-.1.3-.1.6 0 .8.1.3.4.5.7.5h.2c.9-.2 1.6-.7 2.1-1.4.4.2.9.2 1.4.1.7-.2 1.3-.7 1.6-1.3.1-.2.1-.4-.1-.6zm-4.5 2c-.1 0-.2-.1-.2-.2 0-.2.1-.5.4-1 .1.2.2.5.3.7.1.2.2.3.2.4-.3.1-.5.2-.7.1zm2.8-1c-.2.3-.6.6-1 .7-.2.1-.3 0-.5 0 .3-.5.5-1.1.6-1.6.1-.2.1-.4 0-.5.3-.4.6-.6.8-.7.2-.1.3 0 .4.2.1.3 0 .6-.1 1-.1.3-.2.6-.2.9z",fill:"#241C15"}),e.jsx("path",{d:"M29.1 20.5c-.5-1.1-1.7-1.3-2.3-1.2.1-.4 0-.9-.3-1.4-.4-.6-1-1-1.7-1-.1-1.3-.9-2.4-2.1-2.8-.4-.1-.8-.2-1.2-.1 0 0-.5-1-1.6-1.8-1.3-.9-2.7-1-3.9-.2-1 .6-1.5 1.7-1.7 2.5-.8.2-1.4.6-1.9 1.2-.6.8-.8 1.8-.5 2.9-.9.7-1.4 1.7-1.3 2.8.1 1 .6 1.9 1.5 2.5.1 1.2.7 2.3 1.6 3 1 .8 2.3 1.1 3.5.8l.2-.1c.4.4 1 .6 1.5.6.6 0 1.2-.3 1.6-.7.6.2 1.2.2 1.8 0 .5-.2.9-.5 1.2-.9.6.1 1.3 0 1.9-.3.7-.4 1.2-1 1.4-1.7.9-.2 1.6-.7 2-1.5.5-.8.5-1.7.3-2.6zm-1 2.1c-.3.5-.8.9-1.4 1l-.3.1v.3c-.1.6-.5 1.2-1.1 1.5-.5.3-1 .3-1.5.2l-.3-.1-.1.3c-.2.4-.5.7-.9.8-.4.2-.9.2-1.4 0l-.2-.1-.2.2c-.3.4-.8.6-1.3.6-.4 0-.8-.2-1.1-.5l-.2-.2-.3.1c-1 .3-2.1.1-2.9-.6-.7-.6-1.2-1.5-1.2-2.5v-.3l-.3-.1c-.7-.4-1.2-1.1-1.2-1.9-.1-.9.3-1.7 1-2.2l.2-.2-.1-.2c-.3-.9-.1-1.7.3-2.3.4-.5.9-.8 1.5-1l.3-.1v-.3c.1-.8.5-1.8 1.3-2.3.9-.6 2-.5 3.1.2.9.6 1.3 1.4 1.3 1.5l.1.2.2-.1c.3-.1.7-.1 1.1 0 1 .3 1.6 1.2 1.7 2.3v.3l.3.1c.5.1 1 .4 1.3.9.3.4.3.9.2 1.2l-.1.3.3.1c.5.1 1.3.4 1.7 1.2.2.6.2 1.3-.1 1.9z",fill:"#241C15"})]})}function aE({className:t}){return e.jsx("div",{className:`${t} flex items-center justify-center rounded-lg bg-green-100 dark:bg-green-900/40`,children:e.jsx(Pr,{className:"h-5 w-5 text-green-600 dark:text-green-400"})})}function nE({className:t}){return e.jsx("div",{className:`${t} flex items-center justify-center rounded-lg bg-indigo-100 dark:bg-indigo-900/40`,children:e.jsx(Yt,{className:"h-5 w-5 text-indigo-600 dark:text-indigo-400"})})}function rE({className:t}){return e.jsx("div",{className:`${t} flex items-center justify-center rounded-lg bg-emerald-100 dark:bg-emerald-900/40`,children:e.jsx($t,{className:"h-5 w-5 text-emerald-600 dark:text-emerald-400"})})}function iE({className:t}){return e.jsx("div",{className:`${t} flex items-center justify-center rounded-lg bg-blue-100 dark:bg-blue-900/40`,children:e.jsx(Lt,{className:"h-5 w-5 text-blue-600 dark:text-blue-400"})})}function lE({className:t}){return e.jsxs("svg",{className:t,viewBox:"0 0 40 40",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[e.jsx("rect",{width:"40",height:"40",rx:"8",fill:"#2CA01C"}),e.jsx("circle",{cx:"20",cy:"20",r:"12",fill:"white"}),e.jsx("path",{d:"M15 15.5a4.5 4.5 0 000 9h1.5v-2.4H15a2.1 2.1 0 010-4.2h1.5V15.5H15z",fill:"#2CA01C"}),e.jsx("path",{d:"M25 24.5a4.5 4.5 0 000-9h-1.5v2.4H25a2.1 2.1 0 010 4.2h-1.5v2.4H25z",fill:"#2CA01C"}),e.jsx("rect",{x:"19",y:"14.5",width:"2",height:"11",fill:"#2CA01C"})]})}function oE({className:t}){return e.jsx("div",{className:`${t} flex items-center justify-center rounded-lg bg-violet-100 dark:bg-violet-900/40`,children:e.jsx(Kp,{className:"h-5 w-5 text-violet-600 dark:text-violet-400"})})}const cE={stripe:tE,mailchimp:sE,mailerLite:aE,eventApp:nE,email:rE,memberClicks:iE,videoLibrary:oE,quickBooks:lE};function dE({integration:t,className:s="h-10 w-10"}){const a=cE[t];return e.jsx(a,{className:s})}const mE={emerald:"emerald",amber:"amber",sky:"neutral",neutral:"neutral",muted:null};function uE(t){const s=mE[hy[t.state]];return s?{tone:s,label:Ec[t.state]}:null}const nc={emerald:"bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400 [&>span]:bg-emerald-500",amber:"bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400 [&>span]:bg-amber-500",neutral:"bg-muted text-muted-foreground [&>span]:bg-muted-foreground"};function hE({integration:t,connected:s,metadata:a,onConnect:n,onReconfigure:r,onDisconnect:i,onTest:l,actionsDisabled:m,actionsDisabledNote:c,statusOverride:d,note:u,primaryAction:h,secondaryAction:p,health:x}){const f=d??(x?uE(x):null),[b,N]=o.useState(null),[j,w]=o.useState(!1),v=async()=>
3957{if(l){w(!0),N(null);try{const k=await l();N(k)}catch{N({ok:!1,error:"Failed to test connection"})}finally{w(!1)}}};return e.jsxs(L,{className:"min-w-0 overflow-hidden p-5",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsx(dE,{integration:t.key}),s?e.jsxs(Ws,{children:[e.jsx(Vs,{asChild:!0,children:e.jsx(g,{type:"button",variant:"ghost",size:"icon",className:"h-11 w-11 lg:h-8 lg:w-8",disabled:m,"aria-label":`${t.name} actions`,children:e.jsx(Pn,{className:"h-4 w-4","aria-hidden":"true"})})}),e.jsxs($s,{align:"end",children:[l&&e.jsx(wt,{onClick:v,disabled:j||m,children:j?"Testingâ¦":"Test connection"}),e.jsx(wt,{onClick:r,disabled:m,children:"Reconfigure"}),e.jsx(wt,{className:"text-destructive focus:text-destructive",onClick:i,disabled:m,children:"Disconnect"})]})]}):null]}),e.jsxs("div",{className:"mt-3",children:[e.jsx("h3",{className:"text-sm font-semibold text-foreground",children:t.name}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:t.description}),u&&e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:u})]}),e.jsxs("div",{className:"mt-4",children:[s?e.jsxs("div",{className:"space-y-2",children:[e.jsxs("span",{className:`inline-flex items-center gap-1.5 rounded-full px-2.5 py-0.5 text-xs font-medium ${f?nc[f.tone]:nc.neutral}`,children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full"}),f?f.label:"Connected"]}),x&&!d&&f&&e.jsx(dh,{health:x}),a&&e.jsx("p",{className:"truncate text-xs text-muted-foreground",title:a,children:a}),b!==null&&e.jsx("p",{className:`text-xs ${b.ok?"text-emerald-700 dark:text-emerald-400":"text-destructive"}`,children:b.ok?"Connection successful":b.error??"Connection failed"}),(h||p)&&e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[h&&e.jsx(g,{type:"button",variant:"outline",size:"sm",onClick:h.onClick,disabled:m,children:h.label}),p&&e.jsx(g,{type:"button",variant:"ghost",size:"sm",onClick:p.onClick,disabled:m,children:p.label})]})]}):e.jsxs("div",{className:"space-y-2",children:[x&&f&&e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:`inline-flex items-center gap-1.5 rounded-full px-2.5 py-0.5 text-xs font-medium ${nc[f.tone]}`,children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full"}),f.label]}),e.jsx(dh,{health:x})]}),e.jsx(g,{type:"button",variant:"outline",size:"sm",onClick:n,disabled:m,children:"Connect"})]}),m&&c&&e.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:c})]})]})}function dh({health:t}){return e.jsxs("p",{className:"text-xs text-muted-foreground",children:[t.detail,t.checked_at&&e.jsxs(e.Fragment,{children:[" ",e.jsx("span",{className:"opacity-80",children:py(t.checked_at)})]})]})}function pE({open:t,onOpenChange:s,integration:a,configureStripe:n,testStripe:r,configureMailchimp:i,testMailchimp:l,selectMailchimpList:m,configureMailerLite:c,testMailerLite:d,selectMailerLiteGroup:u,configureEventApp:h,configureMemberClicks:p,testMemberClicks:x,configureEmail:f,testEmail:b,configureVideoLibrary:N}){const[j,w]=o.useState("form"),[v,k]=o.useState({}),[S,_]=o.useState(""),[y,C]=o.useState(""),[P,A]=o.useState([]),[E,Q]=o.useState([]),[U,D]=o.useState(!1),[K,xe]=o.useState("ses"),z=o.useCallback(()=>{w("form"),k({}),_(""),C(""),A([]),Q([]),D(!1),xe("ses")},[]),ae=R=>{j==="loading"||U||(R||z(),s(R))},ue=(R,X)=>{k(Se=>({...Se,[R]:X}))},_e=()=>v.from_address?.trim()?K==="ses"?!!(v.ses_access_key?.trim()&&v.ses_secret_key?.trim()):!!v.smtp_host?.trim():!1,ee=()=>!0,se=a.key==="email"?_e():a.key==="videoLibrary"?ee():a.fields.filter(R=>R.required).every(R=>v[R.name]?.trim()),le=async()=>{w("loading"),_("");try{if(a.key==="stripe"){await n(v);const R=await r();R.success?(C(R.account_name?`Connected to ${R.account_name}`:"Stripe connected successfully"),w("success")):(_(R.error||"Connection test failed"),w("error"))}else if(a.key==="mailchimp"){await i(v);const R=await l();R.success?R.lists&&R.lists.length>0?(A(R.lists),w("audience")):(C("Mailchimp connected (no audiences found)"),w("success")):(_(R.error||"Connection test failed"),w("error"))}else if(a.key==="mailerLite"){await c(v);const R=await d();R.success?R.groups&&R.groups.length>0?(Q(R.groups),w("audience")):(C("MailerLite connected (no groups foun
3957d)"),w("success")):(_(R.error||"Connection test failed"),w("error"))}else if(a.key==="eventApp")await h(v),C("Event App connected successfully"),w("success");else if(a.key==="memberClicks"){await p(v);const R=await x();R.success?(C(`Connected to MemberClicks â ${R.type_count||0} types, ${R.status_count||0} statuses found`),w("success")):(_(R.error||"Connection test failed"),w("error"))}else if(a.key==="videoLibrary")await N({base_url:"",sso_key:"",enabled:!0}),C("Video Library provisioned successfully"),w("success");else if(a.key==="email"){const R={provider:K,from_address:v.from_address,from_name:v.from_name||void 0,...K==="ses"?{ses_access_key:v.ses_access_key,ses_secret_key:v.ses_secret_key,ses_region:v.ses_region||void 0}:{smtp_host:v.smtp_host,smtp_port:v.smtp_port?parseInt(v.smtp_port):void 0,smtp_username:v.smtp_username||void 0,smtp_password:v.smtp_password||void 0}};await f(R);const X=await b();X.success?(C("Email configured and test sent successfully"),w("success")):(_(X.error||"Test email failed"),w("error"))}}catch{_("An unexpected error occurred"),w("error")}},oe=async R=>{D(!0);try{await m(R.id),C(`Connected to Mailchimp â audience: ${R.name}`),w("success")}catch{_("Failed to select audience"),w("error")}finally{D(!1)}},Pe=async R=>{D(!0);try{await u(R.id),C(`Connected to MailerLite â group: ${R.name}`),w("success")}catch{_("Failed to select group"),w("error")}finally{D(!1)}},M=()=>{z(),s(!1)},I=()=>{w("form"),_("")};return e.jsx(Fe,{open:t,onOpenChange:ae,children:e.jsxs(Te,{onPointerDownOutside:R=>{(j==="loading"||U)&&R.preventDefault()},onEscapeKeyDown:R=>{(j==="loading"||U)&&R.preventDefault()},children:[j==="form"&&e.jsxs(e.Fragment,{children:[e.jsxs(Ae,{children:[e.jsxs(Ee,{children:["Connect ",a.name]}),e.jsx(tt,{children:a.key==="email"?"Choose a provider and enter credentials to send transactional emails.":a.key==="videoLibrary"?"Click Provision to create a video library for this society.":`Enter your ${a.name} credentials to connect.`})]}),e.jsx("div",{className:"space-y-4 py-2",children:a.key==="email"?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(T,{children:["Provider ",e.jsx("span",{className:"ml-1 text-destructive",children:"*"})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("button",{type:"button",className:`flex-1 rounded-md border p-2 text-sm font-medium transition-colors ${K==="ses"?"border-primary bg-primary/10 text-primary":"border-border text-muted-foreground hover:bg-muted"}`,onClick:()=>xe("ses"),children:"Amazon SES"}),e.jsx("button",{type:"button",className:`flex-1 rounded-md border p-2 text-sm font-medium transition-colors ${K==="smtp"?"border-primary bg-primary/10 text-primary":"border-border text-muted-foreground hover:bg-muted"}`,onClick:()=>xe("smtp"),children:"SMTP"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(T,{htmlFor:"from_address",children:["From Email ",e.jsx("span",{className:"ml-1 text-destructive",children:"*"})]}),e.jsx(O,{id:"from_address",type:"text",placeholder:"[email protected]",value:v.from_address||"",onChange:R=>ue("from_address",R.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"from_name",children:"From name"}),e.jsx(O,{id:"from_name",type:"text",placeholder:"My Society",value:v.from_name||"",onChange:R=>ue("from_name",R.target.value)})]}),K==="ses"?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(T,{htmlFor:"ses_access_key",children:["AWS Access Key ID ",e.jsx("span",{className:"ml-1 text-destructive",children:"*"})]}),e.jsx(O,{id:"ses_access_key",type:"password",placeholder:"AKIA...",value:v.ses_access_key||"",onChange:R=>ue("ses_access_key",R.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(T,{htmlFor:"ses_secret_key",children:["AWS Secret Access Key ",e.jsx("span",{className:"ml-1 text-destructive",children:"*"})]}),e.jsx(O,{id:"ses_secret_key",type:"password",placeholder:"Enter secret key",value:v.ses_secret_key||"",onChange:R=>ue("ses_secret_key",R.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"ses_region",children:"AWS Region"}),e.jsx(O,{id:"ses_region",type:"text",placeholder:"us-east-1",value:v.ses_region||"",onChange:R=>ue("ses_region",R.target.value)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Defaults to us-east-1 if blank"})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(T,{htmlFor:"smtp_host",children:["SMTP Host ",e.jsx("span",{className:"ml-1 text-destructive",children:"*"})]}),e.jsx(O,{id:"smtp_host",type:"text",placeholder:"smtp.sendgrid.net",value:v.smtp_host||"",onChange:R=>ue("smtp_host",R.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"smtp_port",children:"SMTP Port"}),e.jsx(O,{id:"smtp_port",type:"text",placeholder:"587",value:v.smtp_port||"",onChange:R=>ue("smtp_port",R.target.value)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Defaults to 587 (STARTTLS). Use 465 for SSL."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"smtp_username",children:"Username"}),e.jsx(O,{id:"smtp_username",type:"text",placeholder:"apikey or [email protected]",value:v.smtp_username||"",onChange:R=>ue("smtp_username",R.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"smtp_password",children:"Password"}),e.jsx(O,{id:"smtp_password",type:"password",placeholder:"Enter SMTP password",value:v.smtp_password||"",onChange:R=>ue("smtp_password",R.target.value)})]})]})]}):a.key==="videoLibrary"?e.jsxs("div",{className:"rounded-md border border-border bg-muted/50 p-4 text-sm text-foreground",children:[e.jsx("p",{className:"font-medium",children:"Provision video library"}),e.jsx("p",{className:"mt-1 text-muted-foreground",children:"This will create a video library for this society. An SSO key will be generated automatically."})]}):a.fields.map(R=>e.jsxs("div",{className:"space-y-2",children:[e.jsxs(T,{htmlFor:R.name,children:[R.label,R.required&&e.jsx("span",{className:"ml-1 text-destructive",children:"*"})]}),e.jsx(O,{id:R.name,type:R.type,placeholder:R.placeholder,value:v[R.name]||"",onChange:X=>ue(R.name,X.target.value)}),R.hint&&e.jsx("p",{className:"text-xs text-muted-foreground",children:R.hint})]},R.name))}),e.jsxs(Ge,{children:[e.jsx(g,{variant:"outline",onClick:()=>ae(!1),children:"Cancel"}),e.jsx(g,{onClick:le,disabled:!se,children:a.key==="email"?"Connect & Test":a.key==="videoLibrary"?"Provision":"Connect"})]})]}),j==="loading"&&e.jsxs("div",{className:"flex flex-col items-center justify-center py-12",children:[e.jsx(He,{className:"h-8 w-8 animate-spin text-muted-foreground"}),e.jsxs("p",{className:"mt-4 text-sm text-muted-foreground",children:["Connecting to ",a.name,"â¦"]})]}),j==="audience"&&P.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs(Ae,{children:[e.jsx(Ee,{children:"Select audience"}),e.jsx(tt,{children:"Choose which Mailchimp audience to sync members to."})]}),e.jsx("div",{className:"max-h-64 space-y-2 overflow-y-auto py-2",children:P.map(R=>e.jsxs("button",{type:"button",className:"w-full rounded-md border p-3 text-left transition-colors hover:bg-muted disabled:opacity-50",onClick:()=>oe(R),disabled:U,children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm font-medium",children:R.name}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[R.member_count.toLocaleStr
3957ing()," contacts"]})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:R.id})]},R.id))})]}),j==="audience"&&E.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs(Ae,{children:[e.jsx(Ee,{children:"Select group"}),e.jsx(tt,{children:"Choose which MailerLite group to sync members to."})]}),e.jsx("div",{className:"max-h-64 space-y-2 overflow-y-auto py-2",children:E.map(R=>e.jsx("button",{type:"button",className:"w-full rounded-md border p-3 text-left transition-colors hover:bg-muted disabled:opacity-50",onClick:()=>Pe(R),disabled:U,children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm font-medium",children:R.name}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[R.subscriber_count.toLocaleString()," subscribers"]})]})},R.id))})]}),j==="success"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-col items-center justify-center py-8",children:[e.jsx("div",{className:"duration-300 animate-in fade-in zoom-in-50",children:e.jsx(vn,{className:"h-12 w-12 text-emerald-500"})}),e.jsx("p",{className:"mt-4 text-sm font-medium text-foreground",children:y})]}),e.jsx(Ge,{children:e.jsx(g,{onClick:M,children:"Done"})})]}),j==="error"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-col items-center justify-center py-8",children:[e.jsx("div",{className:"duration-300 animate-in fade-in zoom-in-50",children:e.jsx(Ca,{className:"h-12 w-12 text-destructive"})}),e.jsx("p",{className:"mt-4 text-sm text-destructive",children:S})]}),e.jsxs(Ge,{children:[e.jsx(g,{variant:"outline",onClick:()=>ae(!1),children:"Cancel"}),e.jsx(g,{onClick:I,children:"Try again"})]})]})]})})}function xE({open:t,onOpenChange:s,integrationName:a,isPending:n,onConfirm:r}){return e.jsx(Fe,{open:t,onOpenChange:n?void 0:s,children:e.jsxs(Te,{children:[e.jsxs(Ae,{children:[e.jsxs(Ee,{children:["Disconnect ",a,"?"]}),e.jsxs(tt,{children:["This will remove all stored credentials for ",a,". You can reconnect at any time by entering new credentials."]})]}),e.jsxs(Ge,{children:[e.jsx(g,{variant:"outline",onClick:()=>s(!1),disabled:n,children:"Cancel"}),e.jsx(g,{variant:"destructive",onClick:r,disabled:n,children:n?"Disconnectingâ¦":"Disconnect"})]})]})})}function gE(t){return re({queryKey:["mc-status",t],queryFn:()=>ki.getStatus(t),enabled:!!t})}function fE(t){return re({queryKey:["mc-types",t],queryFn:()=>ba.getTypes(t),enabled:!!t})}function yE(t){return re({queryKey:["mc-statuses",t],queryFn:()=>ba.getStatuses(t),enabled:!!t})}function bE(t){return re({queryKey:["mc-type-mappings",t],queryFn:()=>ba.getTypeMappings(t),enabled:!!t})}function jE(){const t=J();return W({mutationFn:({mappings:s,societyId:a})=>ba.saveTypeMappings(s,a),onSuccess:(s,{societyId:a})=>{t.invalidateQueries({queryKey:["mc-type-mappings",a]})}})}function vE(t){return re({queryKey:["mc-status-mappings",t],queryFn:()=>ba.getStatusMappings(t),enabled:!!t})}function wE(){const t=J();return W({mutationFn:({mappings:s,societyId:a})=>ba.saveStatusMappings(s,a),onSuccess:(s,{societyId:a})=>{t.invalidateQueries({queryKey:["mc-status-mappings",a]})}})}function NE(t){return re({queryKey:["mc-field-preview",t],queryFn:()=>ba.getFieldPreview(t),enabled:!1})}function kE(){const t=J();return W({mutationFn:({mappings:s,societyId:a})=>ba.saveFieldMappings(s,a),onSuccess:(s,{societyId:a})=>{t.invalidateQueries({queryKey:["mc-field-preview",a]})}})}function _E(){return W({mutationFn:t=>ba.preview(t)})}function SE(){return W({mutationFn:t=>ba.executeImport(t)})}function CE(){const t=J();return W({mutationFn:s=>ba.sync(s),onSuccess:(s,a)=>{t.invalidateQueries({queryKey:["mc-sync-logs",a]}),t.invalidateQueries({queryKey:["mc-status",a]})}})}function PE(t){return re({queryKey:["mc-sync-logs",t],queryFn:()=>ba.getSyncLogs(t),enabled:!!t})}const AE=[{value:"ACTIVE",label:"Active"},{value:"PENDING",label:"Pending"},{value:"LAPSED",label:"Lapsed"},{value:"GRACE",label:"Grace"},{value:"EXPIRED",label:"Expired"},{value:"CANCELLED",label:"Cancelled"},{value:"SUSPENDED",label:"Suspended"},{value:"ARCHIVED",label:"Archived"}],EE={active:"ACTIVE",inactive:"LAPSED",lapsed:"LAPSED",pending:"PENDING",suspended:"SUSPENDED",expired:"EXPIRED",cancelled:"CANCELLED",archived:"ARCHIVED"},TE=[{value:"text",label:"Text"},{value:"number",label:"Number"},{value:"date",label:"Date"},{value:"checkbox",label:"Checkbox"}];function rl({title:t,icon:s,defaultOpen:a,badge:n,children:r}){const[i,l]=o.useState(a??!1);return e.jsxs("div",{children:[e.jsxs("button",{type:"button",className:"flex w-full items-center gap-2 py-2 text-sm font-medium text-foreground transition-colors hover:text-foreground
3957/80",onClick:()=>l(m=>!m),children:[e.jsx(ts,{className:`h-4 w-4 text-muted-foreground transition-transform ${i?"rotate-90":""}`}),e.jsx(s,{className:"h-4 w-4 text-muted-foreground"}),t,n&&e.jsx(Ts,{variant:"secondary",className:"ml-auto text-xs",children:n})]}),i&&e.jsx("div",{className:"mt-2",children:r})]})}function FE({societyId:t}){const{data:s,isLoading:a}=gE(t);return a?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(He,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):s?.connected?e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"border-t pt-4",children:e.jsx("h3",{className:"mb-3 text-sm font-semibold text-foreground",children:"MemberClicks Configuration"})}),e.jsx(rl,{title:"Type mapping",icon:as,children:e.jsx(RE,{societyId:t})}),e.jsx("div",{className:"border-t"}),e.jsx(rl,{title:"Status mapping",icon:as,children:e.jsx(ME,{societyId:t})}),e.jsx("div",{className:"border-t"}),e.jsx(rl,{title:"Field mapping",icon:as,children:e.jsx(qE,{societyId:t})}),e.jsx("div",{className:"border-t"}),e.jsx(rl,{title:"Import & Sync",icon:St,children:e.jsx(IE,{societyId:t})})]}):null}function RE({societyId:t}){const{data:s,isLoading:a}=fE(t),{data:n}=bE(t),{data:r}=re({queryKey:["membership-types",t],queryFn:()=>Zn.list(t),enabled:!!t}),i=jE(),[l,m]=o.useState([]),[c,d]=o.useState(!1),[u,h]=o.useState(!1);o.useEffect(()=>{if(!s||c)return;const x=new Map((n||[]).map(b=>[b.mc_type_name,b])),f=s.map(b=>{const N=b.name||String(b.id||""),j=x.get(N);return{mc_type_name:N,mc_type_id:String(b.id||""),ams_membership_type_id:j?.ams_membership_type_id??null}});m(f),d(!0)},[s,n,c]);const p=async()=>{await i.mutateAsync({mappings:l,societyId:t}),h(!0),setTimeout(()=>h(!1),2e3)};return a?e.jsxs("div",{className:"py-6 text-center",children:[e.jsx(He,{className:"mx-auto h-6 w-6 animate-spin text-muted-foreground"}),e.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"Fetching member types from MemberClicksâ¦"})]}):e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Map each MemberClicks member type to an AMS membership type. Unmapped types will default to no membership type."}),l.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No member types found in MemberClicks."}):e.jsxs(Pt,{children:[e.jsx(At,{className:"bg-muted/30",children:e.jsxs(Ue,{className:"hover:bg-transparent",children:[e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"MemberClicks Type"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"AMS Membership Type"})]})}),e.jsx(Et,{children:l.map((x,f)=>e.jsxs(Ue,{className:"hover:bg-brand-navy/[0.04] dark:hover:bg-brand-navy/10",children:[e.jsx(G,{className:"font-medium",children:x.mc_type_name}),e.jsx(G,{children:e.jsx(Ss,{value:x.ams_membership_type_id??null,onChange:b=>{const N=[...l];N[f]={...x,ams_membership_type_id:b},m(N)},noneLabel:"-- None --",placeholder:"Select typeâ¦",className:"w-64",children:(r||[]).map(b=>e.jsx(q,{value:b.id,children:b.name},b.id))})})]},x.mc_type_name))})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(g,{type:"button",onClick:p,disabled:i.isPending,size:"sm",children:i.isPending?"Savingâ¦":"Save mappings"}),u&&e.jsxs("span",{className:"flex items-center gap-1 text-sm text-emerald-700 dark:text-emerald-400",children:[e.jsx(Kt,{className:"h-3.5 w-3.5"})," Saved"]})]})]})}function ME({societyId:t}){const{data:s,isLoading:a}=yE(t),{data:n}=vE(t),r=wE(),[i,l]=o.useState([]),[m,c]=o.useState(!1),[d,u]=o.useState(!1);o.useEffect(()=>{if(!s||m)return;const p=new Map((n||[]).map(f=>[f.mc_status_name,f])),x=s.map(f=>{const b=f.name||String(f.id||""),N=p.get(b),j=EE[b.toLowerCase()]||"ACTIVE";return{mc_status_name:b,ams_status:N?.ams_status??j}});l(x),c(!0)},[s,n,m]);const h=async()=>{await r.mutateAsync({mappings:i,societyId:t}),u(!0),setTimeout(()=>u(!1),2e3)};return a?e.jsxs("div",{className:"py-6 text-center",children:[e.jsx(He,{className:"mx-auto h-6 w-6 animate-spin text-muted-foreground"}),e.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"Fetching member statuses from MemberClicksâ¦"})]}):e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Map each MemberClicks status to an AMS member status. Smart defaults are pre-filled."}),i.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No member statuses found in MemberClicks."}):e.jsxs(Pt,{children:[e.jsx(At,{className:"bg-muted/30",children:e.jsxs(Ue,{className:"hover:bg-transparent",children:[e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground
3957/80",children:"MemberClicks Status"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"AMS Status"})]})}),e.jsx(Et,{children:i.map((p,x)=>e.jsxs(Ue,{className:"hover:bg-brand-navy/[0.04] dark:hover:bg-brand-navy/10",children:[e.jsx(G,{className:"font-medium",children:p.mc_status_name}),e.jsx(G,{children:e.jsxs(qe,{value:p.ams_status,onValueChange:f=>{const b=[...i];b[x]={...p,ams_status:f},l(b)},children:[e.jsx(Le,{className:"w-48",children:e.jsx(Ie,{})}),e.jsx($e,{children:AE.map(f=>e.jsx(q,{value:f.value,children:f.label},f.value))})]})})]},p.mc_status_name))})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(g,{type:"button",onClick:h,disabled:r.isPending,size:"sm",children:r.isPending?"Savingâ¦":"Save mappings"}),d&&e.jsxs("span",{className:"flex items-center gap-1 text-sm text-emerald-700 dark:text-emerald-400",children:[e.jsx(Kt,{className:"h-3.5 w-3.5"})," Saved"]})]})]})}function DE(t){return t.replace(/_/g," ").replace(/\b\w/g,s=>s.toUpperCase())}function LE(t){if(!t||t==="__skip__")return{action:"skip",target:"",customType:"text"};if(t.startsWith("custom:")){const s=t.slice(7),a=s.lastIndexOf(":"),n=["text","number","date","checkbox"];if(a>0){const r=s.slice(a+1);if(n.includes(r))return{action:"custom",target:s.slice(0,a),customType:r}}return{action:"custom",target:s,customType:"text"}}return{action:"map",target:t,customType:"text"}}function $E(t,s,a){return t==="skip"?"__skip__":t==="custom"?`custom:${s}:${a}`:s}function qE({societyId:t}){const{data:s,isLoading:a,refetch:n,isFetched:r}=NE(t),i=kE(),[l,m]=o.useState([]),[c,d]=o.useState(!1),[u,h]=o.useState(!1);o.useEffect(()=>{!r&&t&&n()},[r,t,n]),o.useEffect(()=>{if(!s||c)return;const N=s.saved_mappings||{},j=s.mc_fields.map(w=>{const v=N[w.name];if(v){const k=LE(v);return{mc_field_name:w.name,...k}}return{mc_field_name:w.name,action:"skip",target:"",customType:"text"}});m(j),d(!0)},[s,c]);const p=(N,j,w,v)=>{const k=[...l];k[N]={...k[N],action:j,target:w,customType:v??k[N].customType},m(k)},x=async()=>{const N={};for(const j of l)N[j.mc_field_name]=$E(j.action,j.target,j.customType);await i.mutateAsync({mappings:N,societyId:t}),h(!0),setTimeout(()=>h(!1),2e3)};if(a)return e.jsxs("div",{className:"py-6 text-center",children:[e.jsx(He,{className:"mx-auto h-6 w-6 animate-spin text-muted-foreground"}),e.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"Fetching field information from MemberClicksâ¦"})]});if(!s)return e.jsxs("div",{className:"space-y-4 py-6 text-center",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Load a sample of profiles from MemberClicks to see available fields for mapping."}),e.jsx(g,{type:"button",onClick:()=>n(),size:"sm",children:"Load Fields"})]});const f=s.ams_targets||[],b=l.filter(N=>N.action!=="skip").length;return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:[s.mc_fields.length," custom fields found in ",s.sample_size," sampled profiles. Map each to an AMS field, create a custom field, or skip.",b>0&&e.jsxs("span",{className:"font-medium text-foreground",children:[" (",b," mapped)"]})]}),l.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No custom fields found in MemberClicks profiles."}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(Pt,{children:[e.jsx(At,{className:"bg-muted/30",children:e.jsxs(Ue,{className:"hover:bg-transparent",children:[e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"MemberClicks Field"}),e.jsx(H,{className:"h-10 w-20 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Fill %"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Sample Values"}),e.jsx(H,{className:"h-10 min-w-[240px] text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Map To"})]})}),e.jsx(Et,{children:l.map((N,j)=>{const w=s.mc_fields.find(k=>k.name===N.mc_field_name),v=w?Math.round(w.fill_rate*100):0;return e.jsxs(Ue,{className:N.action==="skip"?"opacity-50 hover:bg-brand-navy
3957/[0.04] dark:hover:bg-brand-navy/10":"hover:bg-brand-navy/[0.04] dark:hover:bg-brand-navy/10",children:[e.jsx(G,{className:"text-sm font-medium",children:N.mc_field_name}),e.jsx(G,{children:e.jsxs("span",{className:"inline-flex items-center gap-1.5 whitespace-nowrap",children:[e.jsx("span",{className:`h-1.5 w-1.5 shrink-0 rounded-full ${v>50?"bg-emerald-500":v>0?"bg-amber-500":"bg-muted-foreground/60"}`}),e.jsxs("span",{className:"text-xs font-medium",children:[v,"%"]})]})}),e.jsx(G,{className:"max-w-[200px] truncate text-xs text-muted-foreground",children:w?.sample_values?.join(", ")||"â"}),e.jsx(G,{children:e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(qe,{value:N.action==="skip"?"__skip__":N.action==="custom"?"__custom__":N.target,onValueChange:k=>{k==="__skip__"?p(j,"skip",""):k==="__custom__"?p(j,"custom",DE(N.mc_field_name),"text"):p(j,"map",k)},children:[e.jsx(Le,{className:"w-[200px]",children:e.jsx(Ie,{})}),e.jsxs($e,{children:[e.jsx(q,{value:"__skip__",children:"Skip (Don't Import)"}),e.jsxs(Rm,{children:[e.jsx(_c,{children:"Map to AMS Field"}),f.map(k=>e.jsx(q,{value:k.value,children:k.label},k.value))]}),e.jsxs(Rm,{children:[e.jsx(_c,{children:"Other"}),e.jsx(q,{value:"__custom__",children:"Create custom field"})]})]})]}),N.action==="custom"&&e.jsxs(e.Fragment,{children:[e.jsx(O,{className:"w-[150px]",value:N.target,onChange:k=>p(j,"custom",k.target.value),placeholder:"Field labelâ¦"}),e.jsxs(qe,{value:N.customType,onValueChange:k=>p(j,"custom",N.target,k),children:[e.jsx(Le,{className:"w-[110px]",children:e.jsx(Ie,{})}),e.jsx($e,{children:TE.map(k=>e.jsx(q,{value:k.value,children:k.label},k.value))})]})]})]})})]},N.mc_field_name)})})]})}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(g,{type:"button",onClick:x,disabled:i.isPending,size:"sm",children:i.isPending?"Savingâ¦":"Save mappings"}),u&&e.jsxs("span",{className:"flex items-center gap-1 text-sm text-emerald-700 dark:text-emerald-400",children:[e.jsx(Kt,{className:"h-3.5 w-3.5"})," Saved"]})]})]})}function IE({societyId:t}){const s=_E(),a=SE(),n=CE(),{data:r,isLoading:i}=PE(t),[l,m]=o.useState(null),[c,d]=o.useState(null),u=()=>{s.mutate(t,{onSuccess:x=>m(x)})},h=()=>{a.mutate(t,{onSuccess:x=>d(x)})},p=()=>{n.mutate(t)};return e.jsxs("div",{className:"space-y-6",children:[!c&&!l&&e.jsx(L,{className:"min-w-0 overflow-hidden",children:e.jsxs($,{className:"space-y-4 py-6",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Fetch all profiles from MemberClicks and preview before importing. No data will be written until you confirm."}),s.error&&e.jsxs("div",{className:"flex items-start gap-2 rounded-md bg-destructive/10 p-3 text-sm text-destructive",children:[e.jsx(Dt,{className:"mt-0.5 h-4 w-4 shrink-0"}),s.error?.response?.data?.detail||s.error.message]}),e.jsx(g,{type:"button",onClick:u,disabled:s.isPending,size:"sm",children:s.isPending?e.jsxs(e.Fragment,{children:[e.jsx(He,{className:"mr-2 h-4 w-4 animate-spin"})," Fetching profilesâ¦"]}):"Run preview"})]})}),l&&!c&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3 md:grid-cols-5",children:[e.jsx(Ja,{label:"Total profiles",value:l.total_profiles}),e.jsx(Ja,{label:"Valid",value:l.valid_count,variant:"success"}),e.jsx(Ja,{label:"New members",value:l.new_members,variant:"info"}),e.jsx(Ja,{label:"Existing",value:l.existing_members}),e.jsx(Ja,{label:"Errors",value:l.error_count,variant:l.error_count>0?"danger":"default"})]}),(l.unmapped_types.length>0||l.unmapped_statuses.length>0)&&e.jsxs("div",{className:"flex items-start gap-2 rounded-md bg-amber-50 p-3 text-sm text-amber-700 dark:bg-amber-950/20 dark:text-amber-300",children:[e.jsx(Dt,{className:"mt-0.5 h-4 w-4 shrink-0"}),e.jsxs("div",{className:"space-y-1",children:[l.unmapped_types.length>0&&e.jsxs("p",{children:["Unmapped types: ",l.unmapped_types.join(", ")]}),l.unmapped_statuses.length>0&&e.jsxs("p",{children:["Unmapped statuses: ",l.unmapped_statuses.join(", ")]})]})]}),l.sample_data.length>0&&e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"py-3",children:e.jsxs(ie,{className:"flex items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy
3957/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(ca,{className:"h-4 w-4"})}),"Sample data (first ",l.sample_data.length,")"]})}),e.jsx($,{className:"overflow-x-auto pt-0",children:e.jsxs(Pt,{children:[e.jsx(At,{className:"bg-muted/30",children:e.jsx(Ue,{className:"hover:bg-transparent",children:Object.keys(l.sample_data[0]).map(x=>e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:x},x))})}),e.jsx(Et,{children:l.sample_data.map((x,f)=>e.jsx(Ue,{className:"hover:bg-brand-navy/[0.04] dark:hover:bg-brand-navy/10",children:Object.values(x).map((b,N)=>e.jsx(G,{className:"text-sm",children:String(b??"")},N))},f))})]})})]}),l.errors.length>0&&e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"py-3",children:e.jsxs(ie,{className:"flex items-center gap-2.5 text-sm font-semibold tracking-tight text-destructive",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-red-100 text-red-600 dark:bg-red-900/30 dark:text-red-400",children:e.jsx(Dt,{className:"h-4 w-4"})}),l.errors.length," profile",l.errors.length!==1?"s":""," with errors"]})}),e.jsx($,{className:"overflow-x-auto pt-0",children:e.jsxs(Pt,{children:[e.jsx(At,{className:"bg-muted/30",children:e.jsxs(Ue,{className:"hover:bg-transparent",children:[e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Row"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Email"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Profile ID"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Errors"})]})}),e.jsx(Et,{children:l.errors.slice(0,20).map((x,f)=>e.jsxs(Ue,{className:"hover:bg-brand-navy/[0.04] dark:hover:bg-brand-navy/10",children:[e.jsx(G,{children:x.row}),e.jsx(G,{children:x.email||"â"}),e.jsx(G,{children:x.mc_profile_id||"â"}),e.jsx(G,{children:x.errors.join(", ")})]},f))})]})})]}),e.jsxs("div",{className:"flex gap-3",children:[e.jsx(g,{type:"button",variant:"outline",size:"sm",onClick:()=>m(null),children:"Back"}),a.error&&e.jsxs("div",{className:"flex items-start gap-2 rounded-md bg-destructive/10 p-3 text-sm text-destructive",children:[e.jsx(Dt,{className:"mt-0.5 h-4 w-4 shrink-0"}),a.error?.response?.data?.detail||a.error.message]}),e.jsx(g,{type:"button",onClick:h,disabled:a.isPending,size:"sm",children:a.isPending?e.jsxs(e.Fragment,{children:[e.jsx(He,{className:"mr-2 h-4 w-4 animate-spin"})," Importingâ¦"]}):"Start import"})]})]}),c&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-start gap-2 rounded-md bg-emerald-50 p-3 text-sm text-emerald-900 dark:bg-emerald-950/20 dark:text-emerald-100",children:[e.jsx(Kt,{className:"mt-0.5 h-4 w-4 shrink-0"}),e.jsx("span",{className:"font-medium",children:"Import complete"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3 md:grid-cols-4",children:[e.jsx(Ja,{label:"Created",value:c.created,variant:"success"}),e.jsx(Ja,{label:"Updated",value:c.updated,variant:"info"}),e.jsx(Ja,{label:"Skipped",value:c.skipped}),e.jsx(Ja,{label:"Failed",value:c.failed,variant:c.failed>0?"danger":"default"})]}),c.errors.length>0&&e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"py-3",children:e.jsxs(ie,{className:"flex items-center gap-2.5 text-sm font-semibold tracking-tight text-destructive",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-red-100 text-red-600 dark:bg-red-900/30 dark:text-red-400",children:e.jsx(Dt,{className:"h-4 w-4"})}),c.errors.length," failure",c.errors.length!==1?"s":""]})}),e.jsx($,{className:"overflow-x-auto pt-0",children:e.jsxs(Pt,{children:[e.jsx(At,{className:"bg-muted/30",children:e.jsxs(Ue,{className:"hover:bg-transparent",children:[e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground
3957/80",children:"Email"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Profile ID"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Error"})]})}),e.jsx(Et,{children:c.errors.slice(0,20).map((x,f)=>e.jsxs(Ue,{className:"hover:bg-brand-navy/[0.04] dark:hover:bg-brand-navy/10",children:[e.jsx(G,{children:x.email||"â"}),e.jsx(G,{children:x.mc_profile_id||"â"}),e.jsx(G,{children:x.error})]},f))})]})})]}),e.jsx(g,{type:"button",variant:"outline",size:"sm",onClick:()=>{d(null),m(null)},children:"Done"})]}),e.jsxs("div",{className:"border-t pt-4",children:[e.jsxs("div",{className:"mb-3 flex items-center justify-between",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Sync history"}),e.jsxs(g,{type:"button",onClick:p,disabled:n.isPending,size:"sm",variant:"outline",children:[n.isPending?e.jsx(He,{className:"mr-1 h-4 w-4 animate-spin"}):e.jsx(St,{className:"mr-1 h-4 w-4"}),"Sync now"]})]}),n.data&&e.jsxs("div",{className:"mb-3 flex items-start gap-2 rounded-md bg-emerald-50 p-3 text-sm text-emerald-900 dark:bg-emerald-950/20 dark:text-emerald-100",children:[e.jsx(Kt,{className:"mt-0.5 h-4 w-4 shrink-0"}),"Sync complete: ",n.data.created," created, ",n.data.updated," updated,"," ",n.data.skipped," skipped, ",n.data.failed," failed"]}),i?e.jsx("div",{className:"py-6 text-center",children:e.jsx(He,{className:"mx-auto h-5 w-5 animate-spin text-muted-foreground"})}):r&&r.length>0?e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(Pt,{children:[e.jsx(At,{className:"bg-muted/30",children:e.jsxs(Ue,{className:"hover:bg-transparent",children:[e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Type"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Status"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Started"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Profiles"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Created"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Updated"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Skipped"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Failed"})]})}),e.jsx(Et,{children:r.map(x=>e.jsxs(Ue,{className:"hover:bg-brand-navy/[0.04] dark:hover:bg-brand-navy/10",children:[e.jsx(G,{children:e.jsxs("span",{className:"inline-flex items-center gap-1.5 whitespace-nowrap",children:[e.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-muted-foreground/60"}),e.jsx("span",{className:"text-xs font-medium",children:x.sync_type==="bulk_import"?"Import":"Sync"})]})}),e.jsx(G,{children:e.jsxs("span",{className:"inline-flex items-center gap-1.5 whitespace-nowrap capitalize",children:[e.jsx("span",{className:`h-1.5 w-1.5 shrink-0 rounded-full ${x.status==="completed"?"bg-emerald-500":x.status==="running"?"bg-amber-500":"bg-red-500"}`}),e.jsx("span",{className:"text-xs font-medium",children:x.status})]})}),e.jsx(G,{className:"text-sm",children:Ct(x.started_at).toLocaleString()}),e.jsx(G,{children:x.total_profiles}),e.jsx(G,{className:"text-emerald-700 dark:text-emerald-400",children:x.created}),e.jsx(G,{className:"text-foreground",children:x.updated}),e.jsx(G,{children:x.skipped}),e.jsx(G,{className:x.failed>0?"text-destructive":"",children:x.failed})]},x.id))})]})}):e.jsx("p",{className:"py-4 text-center text-sm text-muted-foreground",children:"No sync history yet."})]})]})}function Ja({label:t,value:s,variant:a="default"}){const n={default:"text-foreground",success:"text-emerald-700 dark:text-emerald-400",info:"text-foreground",danger:"text-destructive"};return e.jsx(L,{className:"min-w-0 overflow-hidden",children:e.jsxs($,{className:"pb-3 pt-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:t}),e.jsx("p",{className:`text-xl font-semibold tracking-tight ${n[a]}`,children:s})]})})}function OE({open:t,onOpenChange:s,step:a,isPending:n,onConfirm:r,errorMessage:i}){return e.jsx(Fe,{open:t,onOpenChange:n?void 0:s,children:e.jsxs(Te,{children:[e.jsxs(Ae,{children:[e.jsx(Ee,{children:"Disconnect QuickBooks?"}),e.jsx(tt,{children:a==="confirm"?"Disconnect QuickBooks? This revokes the connection at Intuit and stops all syncing. Configuration and sync history are kept.":"QuickBooks could not confirm the token was revoked (Intuit unreachable). You can force-disconnect â the connection is cleared on our side; revoke access from the Intuit account page if needed."})]}),i&&e.jsx("p",{className:"text-sm text-destructive",children:i}),e.jsxs(Ge,{children:[e.jsx(g,{type:"button",variant:"outline",onClick:()=>s(!1),disabled:n,children:"Cancel"}),e.jsx(g,{type:"button",variant:"destructive",onClick:()=>r(a==="offer-force"),disabled:n,children:n?"Disconnectingâ¦":a==="offer-force"?"Force disconnect":"Disconnect"})]})]})})}function UE(t){const s=t?.response,a=typeof s?.data?.detail=="string"?s.data.detail:"";return s?.status===502&&a==="revoke_uncertain"?"offer-force":a==="sync_in_progress"?"sync-busy":a==="not_connected"?"not-connected":"generic"}const mh={stripe:"stripe",mailchimp:"mailchimp",mailerLite:"mailerlite",eventApp:"event_app",email:"email",memberClicks:"memberclicks",videoLibrary:"video_library",quickBooks:"quickbooks"},zE={mailchimp:"Mailchimp",mailerLite:"MailerLite"};function BE(t,s,a){const n=zE[t];if(!(!n||!a||s?.state!=="not_enabled"))return`The ${n} feature is off (Features tab): its workspace tools are hidden, but existing sync rules still run while it's connected. Disconnect to stop them.`}function KE(t){return Ni(t)??"Something went wrong. Please try again."}function QE({societyId:t}){const s=re({queryKey:["platform","integration-health",t],queryFn:()=>bi.getIntegrationHealth(t),staleTime:0}),a=new Map((s.data??[]).map(he=>[he.key,he])),n=tb(),r=s.refetch,i=J(),l=o.useRef(!1);o.useEffect(()=>{n>0?l.current=!0:l.current&&(l.current=!1,r(),i.invalidateQueries({queryKey:["platform","dashboard"]}))},[n,r,i]);const m=kt(),{user:c}=V(),d=c?.role==="super_admin",{data:u}=to(t),{data:h}=tr(t),{data:p}=sr(t),{data:x}=Kx(t),{data:f}=Or(t),{data:b}=l0(t),{data:N}=Wx(t),j=Qd(t),w=Lx(),v=$x(),k=Jv(),S=qx(),_=Ix(),y=Ox(),C=Zv(),P=Ux(),A=zx(),E=Bx(),Q=Xv(),U=n0(),D=a0(),K=r0(),xe=Q
3957x(),z=i0(),ae=o0(),ue=c0(),_e=d0(),ee=m0(),se=u0(),le=VA(),oe=GA(),[Pe,M]=o.useState(!1),[I,R]=o.useState(!1),[X,Se]=o.useState(null),[ce,ke]=o.useState(!1),[ve,Ne]=o.useState("confirm"),[Qe,Oe]=o.useState(null),Ce=o.useCallback(he=>{he.key==="videoLibrary"&&!d||(Se(he),M(!0))},[d]),ze=o.useCallback(he=>{if(!(he.key==="videoLibrary"&&!d)){if(he.key==="quickBooks"){Ne("confirm"),Oe(null),ke(!0);return}Se(he),R(!0)}},[d]),Ze=he=>{oe.mutate({societyId:t,force:he},{onSuccess:()=>{ke(!1),Ne("confirm"),Oe(null)},onError:Xe=>{const rt=UE(Xe);if(rt==="offer-force"){Ne("offer-force"),Oe(null);return}if(rt==="sync-busy"){Oe("A sync is currently running for this society â try again in a minute.");return}if(rt==="not-connected"){ke(!1),Ne("confirm"),Oe(null);return}Oe(KE(Xe))}})},Re=he=>{switch(he){case"stripe":return u?.stripe_connected??!1;case"mailchimp":return h?.mailchimp_connected??!1;case"mailerLite":return p?.mailerlite_connected??!1;case"eventApp":return x?.configured??!1;case"email":return f?.connected??!1;case"memberClicks":return b?.connected??!1;case"videoLibrary":return N?.configured??!1;case"quickBooks":return j.data?.connected===!0}},de=he=>{switch(he){case"stripe":return u?.publishable_key_prefix||void 0;case"mailchimp":{const Xe=[];return h?.server_prefix&&Xe.push(`Server: ${h.server_prefix}`),h?.list_name?Xe.push(`Audience: ${h.list_name}`):h?.list_id&&Xe.push(`List: ${h.list_id}`),Xe.length?Xe.join(" · "):void 0}case"mailerLite":{const Xe=[];return p?.group_name?Xe.push(`Group: ${p.group_name}`):p?.group_id&&Xe.push(`Group: ${p.group_id}`),Xe.length?Xe.join(" · "):void 0}case"eventApp":return x&&[x.base_url,x.api_key_configured?"AMS API key set":void 0].filter(Boolean).join(" · ")||void 0;case"email":{const Xe=[];return f?.provider&&Xe.push(f.provider.toUpperCase()),f?.from_address&&Xe.push(f.from_address),Xe.length?Xe.join(" · "):void 0}case"memberClicks":return b?.org_id?`Org: ${b.org_id}`:void 0;case"videoLibrary":return N?.base_url||void 0;case"quickBooks":{const Xe=[j.data?.company_name,j.data?.enabled?"Sync enabled":"Sync paused"].filter(Boolean);return Xe.length?Xe.join(" · "):void 0}}},ge=k.isPending||C.isPending||Q.isPending||D.isPending||z.isPending||_e.isPending||se.isPending||oe.isPending,mt=async()=>{if(X){switch(X.key){case"stripe":await k.mutateAsync(t);break;case"mailchimp":await C.mutateAsync(t);break;case"mailerLite":await Q.mutateAsync(t);break;case"eventApp":await D.mutateAsync(t);break;case"email":await z.mutateAsync(t);break;case"memberClicks":await _e.mutateAsync(t);break;case"videoLibrary":await se.mutateAsync(t);break}R(!1),Se(null)}},ye=j.data?.connection_status==="broken",Ke=Re("quickBooks")||ye,ut=()=>le.mutate({societyId:t}),De=()=>m(`/platform/societies/${t}/quickbooks/config`);return e.jsxs("div",{className:"space-y-6",children:[e.jsx(Ri,{children:"Connecting, reconfiguring, or disconnecting an integration saves immediately."}),s.isError&&!s.data&&e.jsxs("p",{role:"status",className:"text-sm text-muted-foreground",children:["Integration status couldnât be loaded, so the cards show setup only."," ",e.jsx("button",{type:"button",className:"font-medium text-foreground underline underline-offset-2",onClick:()=>{s.refetch()},children:"Try again"})]}),e.jsx("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3",children:eE.map(he=>{const Xe=he.key==="videoLibrary",rt=he.key==="quickBooks";return e.jsx(hE,{integration:he,health:a.get(mh[he.key]),connected:rt?Ke:Re(he.key),metadata:de(he.key),onConnect:()=>rt?ut():Ce(he),onReconfigure:()=>rt?De():Ce(he),onDisconnect:()=>ze(he),onTest:he.key==="eventApp"&&Re("eventApp")?async()=>{const yt=await Dr.testSync(t);return{ok:yt.connectivity.ok,error:yt.connectivity.error}}:void 0,actionsDisabled:Xe?!d:void 0,actionsDisabledNote:Xe&&!d?"Managed by Korevera â contact support to enable.":void 0,statusOverride:rt&&ye?{tone:"amber",label:"Connection broken"}:void 0,note:rt&&ye?`Connection broken (${j.data?.broken_reason??"unknown reason"}) â reconnect to resume syncing.`:BE(he.key,a.get(mh[he.key]),Re(he.key)),primaryAction:rt?ye?{label:"Reconnect",onClick:ut}:Ke?{label:"Configure",onClick:De}:void 0:void 0,secondaryAction:rt&&ye?{label:"Configure",onClick:De}:void 0}
3957,he.key)})}),X&&e.jsx(pE,{open:Pe,onOpenChange:he=>{M(he),he||Se(null)},integration:X,societyId:t,configureStripe:X.key==="stripe"?async he=>{await w.mutateAsync({societyId:t,data:{stripe_publishable_key:he.stripe_publishable_key,stripe_secret_key:he.stripe_secret_key,stripe_webhook_secret:he.stripe_webhook_secret||void 0}})}:void 0,testStripe:X.key==="stripe"?async()=>{const he=await v.mutateAsync(t);return{success:he.success,account_name:he.account_name,error:he.error}}:void 0,configureMailchimp:X.key==="mailchimp"?async he=>{await S.mutateAsync({societyId:t,data:{mailchimp_api_key:he.mailchimp_api_key,mailchimp_server_prefix:he.mailchimp_server_prefix}})}:void 0,testMailchimp:X.key==="mailchimp"?async()=>{const he=await _.mutateAsync(t);return{success:he.success,account_name:he.account_name,lists:he.lists,error:he.error}}:void 0,selectMailchimpList:X.key==="mailchimp"?async he=>{await y.mutateAsync({societyId:t,listId:he})}:void 0,configureMailerLite:X.key==="mailerLite"?async he=>{await P.mutateAsync({societyId:t,data:{mailerlite_api_key:he.mailerlite_api_key}})}:void 0,testMailerLite:X.key==="mailerLite"?async()=>{const he=await A.mutateAsync(t);return{success:he.success,account_name:he.account_name,groups:he.groups,error:he.error}}:void 0,selectMailerLiteGroup:X.key==="mailerLite"?async he=>{await E.mutateAsync({societyId:t,groupId:he})}:void 0,configureEventApp:X.key==="eventApp"?async he=>{await U.mutateAsync({societyId:t,data:{base_url:he.base_url,import_key:he.import_key,...he.api_key?.trim()?{api_key:he.api_key.trim()}:{}}})}:void 0,configureMemberClicks:X.key==="memberClicks"?async he=>{await ae.mutateAsync({societyId:t,data:{org_id:he.org_id,client_id:he.client_id,client_secret:he.client_secret}})}:void 0,testMemberClicks:X.key==="memberClicks"?async()=>{const he=await ue.mutateAsync(t);return{success:he.success,org_id:he.org_id,type_count:he.type_count,status_count:he.status_count,error:he.error}}:void 0,configureEmail:X.key==="email"?async he=>{await K.mutateAsync({societyId:t,data:he})}:void 0,testEmail:X.key==="email"?async()=>{const he=await xe.mutateAsync(t);return{success:he.success,error:he.error}}:void 0,configureVideoLibrary:X.key==="videoLibrary"?async he=>{await ee.mutateAsync({societyId:t,data:{base_url:he.base_url,sso_key:he.sso_key,enabled:he.enabled}})}:void 0}),e.jsx(FE,{societyId:t}),X&&e.jsx(xE,{open:I,onOpenChange:he=>{R(he),he||Se(null)},integrationName:X.name,isPending:ge,onConfirm:mt}),e.jsx(OE,{open:ce,onOpenChange:he=>{ke(he),he||(Ne("confirm"),Oe(null))},step:ve,isPending:oe.isPending,onConfirm:Ze,errorMessage:Qe})]})}const WE={text:"Text",textarea:"Text area",number:"Number",date:"Date",dropdown:"Dropdown",multi_select:"Multi select",checkbox:"Checkbox",file:"File",email:"Email",phone:"Phone",url:"URL"};function VE({fields:t,onEdit:s,onDelete:a,onToggleActive:n,onReorder:r}){const i=(c,d)=>{c.dataTransfer.setData("text/plain",String(d)),c.dataTransfer.effectAllowed="move"},l=c=>{c.preventDefault(),c.dataTransfer.dropEffect="move"},m=(c,d)=>{c.preventDefault();const u=parseInt(c.dataTransfer.getData("text/plain"),10);u!==d&&r(u,d)};return t.length===0?e.jsxs("div",{className:"rounded-md border bg-muted py-12 text-center",children:[e.jsx("p",{className:"text-muted-foreground",children:"No custom fields defined yet."}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:'Click "Add field" to create your first custom field.'})]}):e.jsxs("div",{className:"overflow-hidden rounded-md border",children:[e.jsxs("div",{className:"grid grid-cols-[24px_1fr_80px_auto_auto_auto_60px] items-center gap-2 border-b bg-muted/30 px-3 py-2",children:[e.jsx("span",{}),e.jsx("span",{className:"text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Label"}),e.jsx("span",{className:"text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Type"}),e.jsx("span",{className:"w-14 text-center text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Signup"}),e.jsx("span",{className:"w-14 text-center text-[11px] font-semibold uppercase tracking-wider text-muted-foreground
3957/80",children:"Directory"}),e.jsx("span",{className:"w-10 text-center text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Active"}),e.jsx("span",{})]}),t.map((c,d)=>e.jsxs("div",{draggable:!0,onDragStart:u=>i(u,d),onDragOver:l,onDrop:u=>m(u,d),className:`grid cursor-move grid-cols-[24px_1fr_80px_auto_auto_auto_60px] items-center gap-2 border-b px-3 py-1.5 transition-colors last:border-b-0 hover:bg-brand-navy/[0.04] dark:hover:bg-brand-navy/10 ${c.is_active?"":"opacity-50"}`,children:[e.jsx(Tr,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("span",{className:"block truncate text-sm font-medium",children:c.label}),e.jsx("span",{className:"text-[11px] text-muted-foreground",children:c.field_key})]}),e.jsxs("span",{className:"inline-flex items-center gap-1.5 whitespace-nowrap",children:[e.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-muted-foreground/60"}),e.jsx("span",{className:"text-xs font-medium",children:WE[c.field_type]||c.field_type})]}),e.jsx("span",{className:"w-14 text-center text-xs text-muted-foreground",children:c.show_on_signup?"â":"â"}),e.jsx("span",{className:"w-14 text-center text-xs text-muted-foreground",children:c.show_in_directory?"â":"â"}),e.jsx("div",{className:"flex w-10 justify-center",children:e.jsx(ss,{checked:c.is_active,onCheckedChange:()=>n(c),"aria-label":c.is_active?"Deactivate field":"Activate field",className:"scale-75"})}),e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsxs(fs,{children:[e.jsx(ys,{asChild:!0,children:e.jsxs(g,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>s(c),children:[e.jsx(Hs,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"sr-only",children:"Edit"})]})}),e.jsx(hs,{children:"Edit"})]}),e.jsxs(fs,{children:[e.jsx(ys,{asChild:!0,children:e.jsxs(g,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>a(c),children:[e.jsx(Ft,{className:"h-3.5 w-3.5 text-destructive"}),e.jsx("span",{className:"sr-only",children:"Delete"})]})}),e.jsx(hs,{children:"Delete"})]})]})]},c.id))]})}const GE=[{value:"text",label:"Text"},{value:"textarea",label:"Text area"},{value:"number",label:"Number"},{value:"date",label:"Date"},{value:"email",label:"Email"},{value:"phone",label:"Phone"},{value:"url",label:"URL"},{value:"dropdown",label:"Dropdown"},{value:"multi_select",label:"Multi select"},{value:"checkbox",label:"Checkbox"},{value:"file",label:"File upload"}];function YE({open:t,onOpenChange:s,field:a,onSave:n,isSubmitting:r,membershipTypes:i=[]}){const l=!!a,{register:m,handleSubmit:c,reset:d,watch:u,setValue:h,formState:{errors:p}}=Fr({defaultValues:{field_key:"",label:"",field_type:"text",is_required:!1,help_text:"",placeholder:"",options:"",show_on_signup:!0,show_in_directory:!1,show_on_profile:!0,applicable_membership_type_ids:[]}}),x=u("field_type"),f=x==="dropdown"||x==="multi_select";o.useEffect(()=>{d(a?{field_key:a.field_key,label:a.label,field_type:a.field_type,is_required:a.is_required,help_text:a.help_text||"",placeholder:a.placeholder||"",options:a.options?.join(` 3958`)||"",show_on_signup:a.show_on_signup,show_in_directory:a.show_in_directory,show_on_profile:a.show_on_profile,applicable_membership_type_ids:a.applicable_membership_type_ids||[]}:{field_key:"",label:"",field_type:"text",is_required:!1,help_text:"",placeholder:"",options:"",show_on_signup:!0,show_in_directory:!1,show_on_profile:!0,applicable_membership_type_ids:[]})},[a,d]);const b=u("label");o.useEffect(()=>{if(!l&&b){const j=b.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_|_$/g,"");h("field_key",j)}},[b,l,h]);const N=async j=>{const w=f?j.options.split(` 3959`).map(k=>k.trim()).filter(Boolean):null,v=j.applicable_membership_type_ids.length>0?j.applicable_membership_type_ids:null;if(l){const k={label:j.label,is_required:j.is_required,help_text:j.help_text||null,placeholder:j.placeholder||null,options:w,show_on_signup:j.show_on_signup,show_in_directory:j.show_in_directory,show_on_profile:j.show_on_profile,applicable_membership_type_ids:v};await n(k)}
3959else{const k={field_key:j.field_key,label:j.label,field_type:j.field_type,is_required:j.is_required,help_text:j.help_text||null,placeholder:j.placeholder||null,options:w,show_on_signup:j.show_on_signup,show_in_directory:j.show_in_directory,show_on_profile:j.show_on_profile,applicable_membership_type_ids:v};await n(k)}};return e.jsx(Fe,{open:t,onOpenChange:s,children:e.jsxs(Te,{className:"max-h-[90vh] max-w-lg overflow-y-auto",children:[e.jsxs(Ae,{children:[e.jsx(Ee,{children:l?"Edit custom field":"Add custom field"}),e.jsx(tt,{children:l?"Update the field configuration below.":"Define a new custom field for member records."})]}),e.jsxs("form",{onSubmit:c(N),className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"label",children:"Label *"}),e.jsx(O,{id:"label",...m("label",{required:"Label is required"}),placeholder:"Company name"}),p.label&&e.jsx("p",{className:"text-sm text-destructive",children:p.label.message})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"field_key",children:"Field key *"}),e.jsx(O,{id:"field_key",...m("field_key",{required:"Key is required",pattern:{value:/^[a-z0-9_]+$/,message:"Only lowercase letters, numbers, and underscores"}}),placeholder:"company_name",disabled:l}),p.field_key&&e.jsx("p",{className:"text-sm text-destructive",children:p.field_key.message})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"field_type",children:"Field type *"}),e.jsxs(qe,{value:u("field_type"),onValueChange:j=>h("field_type",j),disabled:l,children:[e.jsx(Le,{children:e.jsx(Ie,{placeholder:"Select type"})}),e.jsx($e,{children:GE.map(j=>e.jsx(q,{value:j.value,children:j.label},j.value))})]}),l&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Field type cannot be changed after creation"})]}),f&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"options",children:"Options (one per line) *"}),e.jsx(It,{id:"options",...m("options",{validate:j=>f?j.split(` 3960`).filter(v=>v.trim()).length>=2||"At least 2 options required":!0}),placeholder:`Option 1 3961Option 2 3962Option 3`,rows:4}),p.options&&e.jsx("p",{className:"text-sm text-destructive",children:p.options.message})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"placeholder",children:"Placeholder"}),e.jsx(O,{id:"placeholder",...m("placeholder"),placeholder:"Enter your companyâ¦"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"help_text",children:"Help text"}),e.jsx(O,{id:"help_text",...m("help_text"),placeholder:"Brief descriptionâ¦"})]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(ot,{id:"is_required",checked:u("is_required"),onCheckedChange:j=>h("is_required",!!j)}),e.jsx(T,{htmlFor:"is_required",className:"cursor-pointer",children:"Required field"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{children:"Display settings"}),e.jsxs("div",{className:"space-y-2 pl-2",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(ot,{id:"show_on_signup",checked:u("show_on_signup"),onCheckedChange:j=>h("show_on_signup",!!j)}),e.jsx(T,{htmlFor:"show_on_signup",className:"cursor-pointer font-normal",children:"Show on signup form"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(ot,{id:"show_on_profile",checked:u("show_on_profile"),onCheckedChange:j=>h("show_on_profile",!!j)}),e.jsx(T,{htmlFor:"show_on_profile",className:"cursor-pointer font-normal",children:"Show on member profile"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(ot,{id:"show_in_directory",checked:u("show_in_directory"),onCheckedChange:j=>h("show_in_directory",!!j)}),e.jsx(T,{htmlFor:"show_in_directory",className:"cursor-pointer font-normal",children:"Show in member directory"})]})]})]}),i.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{children:"Applies to Membership Types"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"When none selected, this field applies to all types."}),e.jsx("div",{className:"space-y-2 pl-2",children:i.map(j=>
3962{const v=u("applicable_membership_type_ids").includes(j.id);return e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(ot,{id:`mt-${j.id}`,checked:v,onCheckedChange:k=>{const S=u("applicable_membership_type_ids");k?h("applicable_membership_type_ids",[...S,j.id]):h("applicable_membership_type_ids",S.filter(_=>_!==j.id))}}),e.jsx(T,{htmlFor:`mt-${j.id}`,className:"cursor-pointer font-normal",children:j.name})]},j.id)})})]}),e.jsxs(Ge,{children:[e.jsx(g,{type:"button",variant:"outline",onClick:()=>s(!1),disabled:r,children:"Cancel"}),e.jsx(g,{type:"submit",disabled:r,children:r?"Savingâ¦":l?"Update field":"Add field"})]})]})]})})}function HE({societyId:t}){const s=J(),[a,n]=o.useState(null),[r,i]=o.useState(!1),[l,m]=o.useState(null),[c,d]=o.useState(!1),u=Ms(re({queryKey:["customFields",t],queryFn:()=>Lr.list(t)}),t),h=u.readyData,p=Ms(re({queryKey:["membershipTypes",t],queryFn:()=>Zn.list(t)}),t),x=p.readyData,f=p.state==="failed"||p.state==="offline",b=Vx(t),N=g0(t),j=f0(t),w=y0(t),v=()=>{f||(n(null),i(!0))},k=Q=>{f||(n(Q),i(!0))},S=async Q=>{try{a?await N.mutateAsync({id:a.id,data:Q}):await b.mutateAsync(Q),i(!1),n(null)}catch(U){throw console.error("Failed to save field:",U),U}},_=async Q=>{try{await N.mutateAsync({id:Q.id,data:{is_active:!Q.is_active}})}catch(U){console.error("Failed to toggle field:",U)}},y=Q=>{m(Q),d(!1)},C=async()=>{if(l)try{await j.mutateAsync({id:l.id,force:c}),m(null)}catch(Q){Q?.response?.data?.detail?.includes("members have data")&&d(!0)}},P=o.useCallback((Q,U)=>{if(!h)return;const D=[...h],[K]=D.splice(Q,1);D.splice(U,0,K),s.setQueryData(["customFields",t],D);const xe=D.map(z=>z.id);w.mutate(xe,{onError:()=>{s.invalidateQueries({queryKey:["customFields",t]}),Ut.error("Could not save the new field order. Please try again.")}})},[h,t,s,w]);if(u.state==="loading")return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(Y,{className:"h-10 w-10"}),e.jsx(Y,{className:"h-8 w-64"})]}),e.jsx(Y,{className:"h-96 w-full"})]});const A=u.state!=="ready"||f,E=[...h||[]].sort((Q,U)=>Q.display_order-U.display_order);return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Drag to reorder. Order determines display on signup forms and profiles."}),e.jsxs(g,{type:"button",onClick:v,variant:"outline",size:"sm",disabled:A,children:[e.jsx(Rt,{className:"mr-1.5 h-3.5 w-3.5"}),"Add field"]})]}),e.jsx(Ma,{view:u,what:"custom fields"}),f&&e.jsxs("div",{role:"alert",className:"flex flex-col gap-2 rounded-lg border border-amber-500/40 bg-amber-50 px-4 py-3 text-sm text-amber-900 dark:bg-amber-950/30 dark:text-amber-200 sm:flex-row sm:items-center sm:justify-between",children:[e.jsx("p",{children:"Membership types couldnât be loaded, so fields canât be added or edited right now (their type restrictions would be lost)."}),p.state==="failed"&&e.jsx(g,{size:"sm",variant:"outline",onClick:p.retry,disabled:p.retrying,children:p.retrying?"Trying againâ¦":"Try again"})]}),u.state==="offline"?e.jsx("div",{className:"rounded-md border",children:e.jsx(Wa,{title:"Custom fields canât be loaded right now."})}):A?e.jsx("div",{className:"rounded-md border",children:e.jsx(ja,{title:"Custom fields couldnât be loaded.",error:u.error,onRetry:u.retry,isRetrying:u.retrying})}):e.jsx(VE,{fields:E,onEdit:k,onDelete:y,onToggleActive:_,onReorder:P}),e.jsx(YE,{open:r,onOpenChange:i,field:a,onSave:S,isSubmitting:b.isPending||N.isPending,membershipTypes:x?.map(Q=>({id:Q.id,name:Q.name}))||[]}),e.jsx(Fe,{open:!!l,onOpenChange:Q=>!Q&&m(null),children:e.jsxs(Te,{children:[e.jsxs(Ae,{children:[e.jsx(Ee,{children:"Delete custom field"}),e.jsx(tt,{children:c?e.jsxs("span",{className:"flex items-start gap-2 text-amber-600 dark:text-amber-400",children:[e.jsx(Bt,{className:"mt-0.5 h-5 w-5 flex-shrink-0"}),e.jsx("span",{children:"Some members have data for this field. Deleting it will orphan their data. Are you sure you want to proceed?"})]}):e.jsxs(e.Fragment,{children:["Are you sure you want to delete the field ",e.jsx("strong",{children:l?.label}),"? This action cannot be undone."]})})]}),e.jsxs(Ge,{children:[e.jsx(g,{variant:"outline",onClick:()=>m(null),disabled:j.isPending,children:"Cancel"}),e.jsx(g,{variant:"destructive",onClick:C,disabled:j.isPending,children:j.isPending?"Deletingâ¦":c?"Force delete":"Delete field"})]})]})})]})}const vy=ds;function JE({bt:t,index:s,onEdit:a,onToggleActive:n,onDelete:r,onUploadClick:i,onIconDelete:l,uploadingId:m,uploadPending:c}
3962){const{attributes:d,listeners:u,setNodeRef:h,transform:p,transition:x,isDragging:f}=id({id:t.id}),b={transform:ld.Transform.toString(p),transition:x,opacity:f?.5:void 0};return e.jsxs(Ue,{ref:h,style:b,className:`hover:bg-brand-navy/[0.04] dark:hover:bg-brand-navy/10 ${t.is_active?"":"opacity-50"}`,children:[e.jsx(G,{className:"w-10",children:e.jsx("button",{type:"button",className:"cursor-grab touch-none p-3 text-muted-foreground hover:text-foreground active:cursor-grabbing lg:p-1",...d,...u,"aria-label":`Reorder ${t.name}`,children:e.jsx(Tr,{className:"h-4 w-4","aria-hidden":"true"})})}),e.jsx(G,{className:"w-8 text-center font-mono text-xs text-muted-foreground",children:s+1}),e.jsx(G,{children:t.icon_url?e.jsx("img",{src:`${vy}${t.icon_url}`,alt:t.name,className:"h-8 w-8 rounded object-cover"}):e.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded",style:{backgroundColor:t.color+"20"},children:e.jsx("div",{className:"h-3 w-3 rounded-full",style:{backgroundColor:t.color}})})}),e.jsxs(G,{children:[e.jsx("button",{type:"button",className:"text-left font-medium hover:underline",onClick:()=>a(t),children:t.name}),e.jsx("span",{className:"ml-2 text-xs text-muted-foreground",children:t.slug})]}),e.jsx(G,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-5 w-5 rounded border",style:{backgroundColor:t.color}}),e.jsx("span",{className:"text-xs text-muted-foreground",children:t.color})]})}),e.jsx(G,{className:"text-center",children:t.is_system&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"System"})}),e.jsx(G,{children:e.jsx(ss,{checked:t.is_active,onCheckedChange:()=>n(t),"aria-label":`${t.name} active`})}),e.jsx(G,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(g,{type:"button",variant:"ghost",size:"icon",className:"h-11 w-11 lg:h-8 lg:w-8",onClick:()=>i(t.id),title:"Upload icon","aria-label":`Upload icon for ${t.name}`,children:m===t.id&&c?e.jsx(He,{className:"h-4 w-4 animate-spin","aria-hidden":"true"}):e.jsx(en,{className:"h-4 w-4","aria-hidden":"true"})}),t.icon_url&&e.jsx(g,{type:"button",variant:"ghost",size:"icon",className:"h-11 w-11 lg:h-8 lg:w-8",onClick:()=>l(t.id),title:"Remove icon","aria-label":`Remove icon from ${t.name}`,children:e.jsx(Wl,{className:"h-4 w-4 text-destructive","aria-hidden":"true"})}),e.jsx(g,{type:"button",variant:"ghost",size:"icon",className:"h-11 w-11 lg:h-8 lg:w-8",onClick:()=>r(t),title:"Delete","aria-label":`Delete ${t.name}`,children:e.jsx(Ft,{className:"h-4 w-4 text-destructive","aria-hidden":"true"})})]})})]})}function ZE({societyId:t}){const[s,a]=o.useState(!1),[n,r]=o.useState(null),[i,l]=o.useState(null),[m,c]=o.useState(!1),[d,u]=o.useState(""),[h,p]=o.useState("#3b82f6"),[x,f]=o.useState(0),b=o.useRef(null),N=o.useRef(null),[j,w]=o.useState(null),v=o.useRef(null),[k,S]=o.useState(null),[_,y]=o.useState(null),C=od(kr(ud,{activationConstraint:{distance:5}}),kr(md,{coordinateGetter:dd})),P=Ms(Yg(t,!0),t),A=P.readyData,E=f_(t),Q=y_(t),U=b_(t),D=j_(t),K=v_(t),xe=w_(t),z=()=>{r(null),u(""),p("#3b82f6"),f(A?.length??0),S(null),y(null),a(!0)},ae=I=>{r(I),u(I.name),p(I.color),f(I.sort_order),S(null),y(I.icon_url?`${vy}${I.icon_url}`:null),a(!0)},ue=async()=>{let I;if(n){const R={id:n.id};d!==n.name&&(R.name=d),h!==n.color&&(R.color=h),x!==n.sort_order&&(R.sort_order=x),I=(await Q.mutateAsync(R)).id}else{const R={name:d,color:h,sort_order:x};I=(await E.mutateAsync(R)).id}k&&await D.mutateAsync({id:I,file:k}),S(null),y(null),a(!1)},_e=async I=>{await Q.mutateAsync({id:I.id,is_active:!I.is_active})},ee=I=>{l(I),c(!1)},se=async()=>{if(i)try{await U.mutateAsync({id:i.id,force:m}),l(null)}catch(I){I?.response?.data?.detail?.includes("member(s) have this badge")&&c(!0)}},le=async(I,R)=>{w(I);try{await D.mutateAsync({id:I,file:R})}finally{w(null)}},oe=async I=>{await K.mutateAsync(I)},Pe=async I=>{const{active:R,over:X}=I;if(!X||R.id===X.id||!A)return;const Se=A.findIndex(Ne=>Ne.id===R.id),ce=A.findIndex(Ne=>Ne.id===X.id);if(Se===-1||ce===-1)return;const ve=cd(A,Se,ce).map((Ne,Qe)=>({id:Ne.id,sort_order:Qe}));await xe.mutateAsync(ve)},M=P.state==="offline"?e.jsx(Wa,{title:"Badge types canât be loaded right now."}):P.state==="failed"?e.jsx(ja,{title:"Badge types couldnât be loaded.",error:P.error,onRetry:P.retry,isRetrying:P.retrying}):A&&A.length>0?e.jsx(jl,{sensors:C,collisionDetection:vl,onDragEnd:Pe,children:e.jsxs(Pt,{children:[e.jsx(At,{className:"bg-muted/30",children:e.jsxs(Ue,{className:"hover:bg-transparent",children:[e.jsx(H,{className:"h-10 w-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground
3962/80"}),e.jsx(H,{className:"h-10 w-8 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"#"}),e.jsx(H,{className:"h-10 w-12 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Icon"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Name"}),e.jsx(H,{className:"h-10 w-20 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Color"}),e.jsx(H,{className:"h-10 w-20 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"System"}),e.jsx(H,{className:"h-10 w-20 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Active"}),e.jsx(H,{className:"h-10 w-32 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Actions"})]})}),e.jsx(wl,{items:A.map(I=>I.id),strategy:Nl,children:e.jsx(Et,{children:A.map((I,R)=>e.jsx(JE,{bt:I,index:R,onEdit:ae,onToggleActive:_e,onDelete:ee,onUploadClick:X=>{v.current=X,w(X),b.current?.click()},onIconDelete:oe,uploadingId:j,uploadPending:D.isPending},I.id))})})]})}):e.jsx("p",{className:"py-4 text-center text-sm text-muted-foreground",children:"No badge types configured yet."});return P.state==="loading"?e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(Y,{className:"h-10 w-10"}),e.jsx(Y,{className:"h-8 w-64"})]}),e.jsx(Y,{className:"h-96 w-full"})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Drag to reorder. Top row displays first on the portal."}),e.jsxs(g,{type:"button",onClick:z,variant:"outline",size:"sm",disabled:!A,children:[e.jsx(Rt,{className:"mr-1.5 h-3.5 w-3.5"}),"Add badge type"]})]}),e.jsx(Ma,{view:P,what:"badge types"}),M,e.jsx("input",{ref:b,type:"file",accept:"image/png,image/jpeg,image/webp",className:"hidden",onChange:I=>{const R=I.target.files?.[0],X=v.current;R&&X&&le(X,R),I.target.value=""}}),e.jsx(Fe,{open:s,onOpenChange:a,children:e.jsxs(Te,{className:"sm:max-w-md",children:[e.jsxs(Ae,{children:[e.jsx(Ee,{children:n?"Edit badge type":"New badge type"}),e.jsx(tt,{children:n?"Update the badge type settings.":"Create a new badge type for this society."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"bt-name",children:"Name"}),e.jsx(O,{id:"bt-name",value:d,onChange:I=>u(I.target.value),placeholder:"e.g. Speaker, Past President"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"bt-color",children:"Color"}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("input",{id:"bt-color",type:"color",value:h,onChange:I=>p(I.target.value),className:"h-10 w-14 cursor-pointer rounded border"}),e.jsx(O,{value:h,onChange:I=>p(I.target.value),className:"flex-1",maxLength:7}),e.jsx("span",{className:"inline-flex items-center gap-1 rounded-full px-3 py-1 text-xs font-medium text-white",style:{backgroundColor:h},children:d||"Preview"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{children:"Icon (optional)"}),e.jsxs("div",{className:"flex items-center gap-3",children:[_?e.jsx("img",{src:_,alt:"Icon preview",className:"h-10 w-10 rounded border object-cover"}):e.jsx("div",{className:"flex h-10 w-10 items-center justify-center rounded border bg-muted",children:e.jsx(Wl,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs(g,{type:"button",variant:"outline",size:"sm",onClick:()=>N.current?.click(),children:[e.jsx(en,{className:"mr-2 h-3.5 w-3.5"}),_?"Change":"Upload"]}),_&&e.jsx(g,{type:"button",variant:"ghost",size:"sm",onClick:()=>{S(null),y(null)},children:"Remove"}),e.jsx("input",{ref:N,type:"file",accept:"image/png,image/jpeg,image/webp",className:"hidden",onChange:I=>{const R=I.target.files?.[0];R&&(S(R),y(URL.createObjectURL(R))),I.target.value=""}})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"PNG, JPEG, or WebP. Max 5 MB."})]})]}),e.jsxs(Ge,{children:[e.jsx(g,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsxs(g,{onClick:ue,disabled:!d.trim()||E.isPending||Q.isPending||D.isPending,children:[(E.isPending||Q.isPending||D.isPending)&&e.jsx(He,{className:"mr-2 h-4 w-4 animate-spin"}),n?"Save":"Create"]})]})]})}),e.jsx(Fe,{open:!!i,onOpenChange:I=>!I&&l(null),children:e.jsxs(Te,{className:"sm:max-w-md",children:[e.jsxs(Ae,{children:[e.jsx(Ee,{children:"Delete badge type"}),e.jsx(tt,{children:m?`Members currently have this badge. Deleting will deactivate "${i?.name}" (it won't appear in new assignments).`:`Are you sure you want to delete "${i?.name}"?`})]}),e.jsxs(Ge,{children:[e.jsx(g,{variant:"outline",onClick:()=>l(null),children:"Cancel"}),e.jsxs(g,{variant:"destructive",onClick:se,disabled:U.isPending,children:[U.isPending&&e.jsx(He,{className:"mr-2 h-4 w-4 animate-spin"}),m?"Deactivate anyway":"Delete"]})]})]})})]})}function uh({title:t,icon:s,defaultOpen:a,children:n}){const[r,i]=o.useState(a??!1);return e.jsxs("div",{children:[e.jsxs("button",{type:"button",className:"flex w-full items-center gap-2 py-2 text-sm font-medium text-foreground transition-colors hover:text-foreground
3962/80",onClick:()=>i(l=>!l),children:[e.jsx(ts,{className:`h-4 w-4 text-muted-foreground transition-transform ${r?"rotate-90":""}`}),e.jsx(s,{className:"h-4 w-4 text-muted-foreground"}),t]}),r&&e.jsx("div",{className:"mt-2",children:n})]})}function XE({societyId:t}){return e.jsxs("div",{className:"space-y-4",children:[e.jsx(Ri,{children:"Custom field and badge type changes save immediately."}),e.jsx(uh,{title:"Custom fields",icon:kp,defaultOpen:!0,children:e.jsx(HE,{societyId:t})}),e.jsx("div",{className:"border-t"}),e.jsx(uh,{title:"Badge types",icon:qn,children:e.jsx(ZE,{societyId:t})})]})}const wy=["name","description","contact_email","contact_phone","website_url","primary_color","dues_cycle_start_month","dues_cycle_start_day","dues_cycle_type","grace_period_days","is_active"],Ny={general:["name","slug","description","contact_email","contact_phone","website_url","is_active"],branding:["primary_color"],membership:["dues_cycle_type","dues_cycle_start_month","dues_cycle_start_day","grace_period_days"],features:["modules"]},eT=Object.fromEntries(vo.map(t=>[t.key,t.defaultOn])),Tc={name:"",slug:"",description:"",contact_email:"",contact_phone:"",website_url:"",primary_color:"#1a365d",dues_cycle_start_month:10,dues_cycle_start_day:1,dues_cycle_type:"calendar",grace_period_days:14,is_active:!0,modules:eT};function hh(t){const s=t.settings??{},a=Object.fromEntries(Kd.map(n=>[n,s[n]===!0]));return{name:t.name,slug:t.slug,description:t.description||"",contact_email:t.contact_email,contact_phone:t.contact_phone||"",website_url:t.website_url||"",primary_color:t.primary_color||"#1a365d",dues_cycle_start_month:t.dues_cycle_start_month,dues_cycle_start_day:t.dues_cycle_start_day,dues_cycle_type:t.dues_cycle_type||"calendar",grace_period_days:t.grace_period_days,is_active:t.is_active,modules:a}}const tT=["dues_cycle_start_month","dues_cycle_start_day"];function ky(t,s){return s.dues_cycle_type==="calendar"||!tT.includes(t)}function xl(t,s){return{details:wy.filter(a=>ky(a,t)&&!Object.is(t[a],s[a])),modules:Kd.filter(a=>t.modules[a]!==s.modules[a])}}function rc(t){return t.details.length+t.modules.length}function il(t,s){return(Ny[t]??[]).some(n=>n==="modules"?s.modules.length>0:s.details.includes(n))}const sT=["name","description","contact_email","contact_phone","website_url","dues_cycle_start_month","dues_cycle_start_day","dues_cycle_type","grace_period_days"];function ph(t,s){const a={};for(const n of s)switch(n){case"description":case"contact_phone":case"website_url":a[n]=t[n].trim()||null;break;case"name":case"contact_email":a[n]=t[n].trim();break;default:a[n]=t[n]}return a}function aT(t,s){return Object.fromEntries(s.map(a=>[a,t.modules[a]]))}function nT(t,s,a){const n=[];for(const r of wy)Object.is(t[r],s[r])&&!Object.is(t[r],a[r])&&n.push([r,a[r]]);for(const r of Kd)t.modules[r]===s.modules[r]&&t.modules[r]!==a.modules[r]&&n.push([`modules.${r}`,a.modules[r]]);return n}function rT(t,s,a){const n={...t,modules:{...t.modules}};for(const r of a.details??[])n[r]=s[r];for(const r of a.modules??[])n.modules[r]=s.modules[r];return n}const _y={details:[],modules:[]};function iT({changeCount:t,isSaving:s,error:a,onDiscard:n,onSave:r}){return t===0&&!s&&!a?null:e.jsx("div",{role:"region","aria-label":"Unsaved changes",className:"fixed inset-x-0 bottom-0 z-30 border-t bg-background/95 py-3 shadow-[0_-4px_12px_-8px_rgba(15,31,61,0.25)] backdrop-blur supports-[backdrop-filter]:bg-background/80 lg:left-64",children:e.jsxs("div",{className:"mx-auto flex max-w-7xl flex-col gap-3 px-4 sm:flex-row sm:items-center sm:justify-between sm:px-6 lg:px-8",children:[e.jsx("div",{className:"min-w-0 text-sm","aria-live":"polite",children:a?e.jsxs("p",{className:"flex items-start gap-2 text-destructive",children:[e.jsx(Dt,{className:"mt-0.5 h-4 w-4 shrink-0"}),e.jsxs("span",{children:[e.jsx("span",{className:"font-medium",children:a.partial?"Some changes werenât saved.":"Changes not saved."})," ",a.message," ",a.partial?"The rest were saved; tabs marked with a dot still have unsaved changes â try again.":"Your edits are still here â try again."]})]}):e.jsxs("p",{className:"text-muted-foreground",children:[e.jsxs("span",{className:"font-medium text-foreground",children:[t," unsaved ",t===1?"change":"changes"]})," ","· Uploads, domains, and integrations save on their own."]})}),e.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[e.jsx(g,{type:"button",variant:"outline",onClick:n,disabled:s||t===0,children:"Discard changes"}),e.jsxs(g,{type:"button",onClick:r,disabled:s||t===0,children:[s&&e.jsx(He,{className:"mr-1.5 h-4 w-4 animate-spin"}),s?"Savingâ¦":a?"Retry save":"Save changes"]})]})]})})}function lT({blocker:t,changeCount:s,isSaving:a,isCreating:n=!1}){const r=t.state==="blocked",i=()=>t.reset?.();o.useEffect(()=>{r&&!a&&s===0&&t.proceed?.()},[r,a,s,t]);const l=r&&(a||s>0);return e.jsx(Fe,{open:l,onOpenChange:m=>!m&&i(),children:e.jsx(Te,{children:a?e.jsxs(e.Fragment,{children:[e.jsxs(Ae,{children:[e.jsx(Ee,{children:"Finishing your save"}),e.jsx(tt,{children:"Your changes are being saved. Youâll leave this page as soon as the save finishes. If itâs taking too long you can leave now â the save may still complete, and if it fails youâll see an error."})]}),e.jsxs("p",{className:"flex items-center gap-2 text-sm text-muted-foreground","aria-live":"polite",children:[e.jsx(He,{className:"h-4 w-4 animate-spin","aria-hidden":"true"}),"Savingâ¦"]}),e.jsxs(Ge,{children:[e.jsx(g,{variant:"outline",onClick:()=>t.proceed?.(),children:"Leave now"}),e.jsx(g,{onClick:i,children:"Stay on this page"})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs(Ae,{children:[e.jsx(Ee,{children:n?"Discard this new society?":"Discard unsaved changes?"}),e.jsx(tt,{children:n?"The society hasnât been created yet. If you leave now, what youâve entered will be lost.":`You have ${s} unsaved ${s===1?"change":"changes"} to this society. If you leave now, they will be lost. Changes that apply immediately, such as uploads and integrations, are already saved.`})]}),e.jsxs(Ge,{children:[e.jsx(g,{variant:"outline",onClick:i,children:"Keep editing"}),e.jsx(g,{variant:"destructive",onClick:()=>t.proceed?.(),children:"Discard and leave"})]})]})})})}function xh(t){return vx(Xn(t,"Something went wrong."))}function oT(t){const s=an(t)?t.response?.status:void 0;return s===404?{title:"This society doesnât exist.",detail:"It may have been deleted, or the link is wrong.",retryable:!1}:s===400||s===422?{title:"This link isnât valid.",detail:"Open the society from the societies list instead.",retryable:!1}:s===403?{title:"You donât have access to this society.",detail:"Ask a platform administrator for access.",retryable:!1}:{title:"This society couldnât be loaded.",detail:s?"Nothing has been changed. The server had a problem â try again in a moment.":"Nothing has been changed. Check your connection and try again.",retryable:!0}}const pr="min-h-[40px] gap-2 rounded-md px-4 data-[state=active]:bg-background data-[state=active]:shadow-sm";function ll({show:t}){return t?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-amber-500","aria-hidden":"true"}),e.jsx("span",{className:"sr-only",children:" (unsaved changes)"})]}):null}function cT(){const t=kt(),s=J(),{id:a}=Ds(),n=!!a,{data:r,isError:i,error:l,refetch:m,isRefetching:c}=Ir(a),d=Bv(),[u,h]=ws(),p=u.get("tab")??"general",x=Oe=>{h(Ce=>{const ze=new URLSearchParams(Ce);return ze.set("tab",Oe),ze},{replace:!0})},f=Fr({defaultValues:Tc}),{reset:b,getValues:N,handleSubmit:j,control:w,setValue:v}=f,[k,S]=o.useState(null),[_,y]=o.useState(!1),C=o.useRef(!1),P=o.useRef(!1),A=o.useRef(!1);o.useEffect(()=>(A.current=!0,()=>{A.current=!1}),[]);
3962const[E,Q]=o.useState(null),U=o.useRef(E),D=o.useCallback(Oe=>{U.current=Oe,Q(Oe)},[]),K=o.useCallback(Oe=>{const Ce=hh(Oe),ze=U.current;if(P.current=!0,!ze)b(Ce);else for(const[Ze,Re]of nT(N(),ze,Ce))v(Ze,Re);P.current=!1,JSON.stringify(ze)!==JSON.stringify(Ce)&&D(Ce)},[b,N,v,D]);o.useEffect(()=>{r&&!C.current&&K(r)},[r,K]);const[,xe]=o.useState(""),z=o.useCallback(Oe=>xe(Oe),[]),ae=n&&E?xl(N(),E):_y,ue=n?rc(ae):+(Object.keys(f.formState.dirtyFields).length>0),_e=ue>0,ee=n&&!_e?null:k,{blocker:se,allowNextNavigation:le}=wA(_e||_),oe=o.useRef(se);o.useEffect(()=>{oe.current=se},[se]);const Pe=async(Oe,Ce)=>{const ze=["society",Oe];await s.cancelQueries({queryKey:ze});try{const Ze=await s.fetchQuery({queryKey:ze,queryFn:()=>Ks.get(Oe),staleTime:0,retry:!1});A.current&&K(Ze)}catch{const Ze=s.getQueryData(ze);if(Ze){const Re={...Ze,...Ce.details,settings:{...Ze.settings,...Ce.modules}};s.setQueryData(ze,Re),A.current&&K(Re)}s.invalidateQueries({queryKey:ze})}},M=Oe=>{s.invalidateQueries({queryKey:["societies"]}),s.invalidateQueries({queryKey:["platform","dashboard"]}),s.invalidateQueries({queryKey:["society-settings",Oe]})},I=async(Oe,Ce,ze)=>{const Ze=U.current;if(!Ze)return;const Re=xl(Ce,Ze);if(rc(Re)===0)return;const de={details:{},modules:{}},ge=(Ke,ut)=>{ze.wrote=!0;const De=U.current;De&&D(rT(De,ut,Ke))},mt=[];Re.details.length>0&&mt.push(Ks.update(Oe,ph(Ce,Re.details)).then(Ke=>{const ut=hh(Ke);ge({details:Re.details},ut);for(const De of Re.details)de.details[De]=Ke[De];if(A.current){P.current=!0;for(const De of Re.details)Object.is(Ce[De],ut[De])||v(De,ut[De]);P.current=!1}})),Re.modules.length>0&&mt.push(ks.updateSocietySettings(aT(Ce,Re.modules),Oe).then(Ke=>{const ut={...Ce,modules:{...Ce.modules}};for(const De of Re.modules)ut.modules[De]=Ke[De]===!0,de.modules[De]=ut.modules[De];ge({modules:Re.modules},ut)}));const ye=(await Promise.allSettled(mt)).filter(Ke=>Ke.status==="rejected");if(await Pe(Oe,de),ze.wrote&&M(Oe),ye.length>0){const Ke=[...new Set(ye.map(ut=>xh(ut.reason)))];throw new ic(Ke.join(" "),ye.map(ut=>ut.reason))}Ut.success("Society settings saved")},R=async Oe=>{if(C.current)return;C.current=!0,y(!0),S(null);const Ce={wrote:!1};try{if(n&&a)await I(a,Oe,Ce);else{const ze=sT.filter(Ke=>ky(Ke,Oe)),{name:Ze="",contact_email:Re="",...de}=ph(Oe,ze),ge={...de,name:Ze,contact_email:Re,slug:Oe.slug},mt=await d.mutateAsync(ge),ye=()=>{t(`/platform/societies/${mt.id}?setup=1`)};A.current&&oe.current.state==="unblocked"?(Ut.success(`${mt.name} created`),le(),ye()):(A.current&&b(Tc),Ut.success(`${mt.name} created`,{action:{label:"Open",onClick:ye}}))}}catch(ze){const Ze=U.current;if(n&&a&&Ze&&rc(xl(N(),Ze))===0){M(a),Ut.success("Society settings saved");return}const Re={message:ze instanceof ic?ze.message:xh(ze),partial:Ce.wrote};if(A.current)S(Re),X(ze instanceof ic?ze.causes:[ze]);else{const de=n?Re.partial?"Some society changes were not saved.":"Society changes were not saved.":"The society was not created.";Ut.error(`${de} ${Re.message}`)}}finally{C.current=!1,A.current&&y(!1)}},X=Oe=>{const Ce={};for(const{field:ze,message:Ze}of Oe.flatMap(rv))dT.includes(ze)&&(f.setError(ze,{type:"server",message:Ze}),Ce[ze]=!0);Object.keys(Ce).length>0&&Qe.current(Ce)},Se=()=>{j(R,Ne)()},ce=o.useCallback(()=>S(null),[]),ke=()=>{E&&(S(null),b(E))},ve=o.useRef(null);o.useEffect(()=>{const Oe=ve.current;Oe&&(ve.current=null,f.setFocus(Oe))},[p,f]);const Ne=Oe=>{const Ce=Object.keys(Oe),ze=Object.entries(Ny).sort(([Ze],[Re])=>Ze===p?-1:Re===p?1:0);for(const[Ze,Re]of ze){const de=Re.find(ge=>Ce.includes(ge));if(de){Ze===p?f.setFocus(de):(ve.current=de,x(Ze));return}}},Qe=o.useRef(Ne);if(o.useEffect(()=>{Qe.current=Ne}),n&&(!r||!E)){if(i&&!r){const Oe=oT(l);return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(g,{variant:"ghost",size:"icon","aria-label":"Back to societies",onClick:()=>t("/platform/societies"),children:e.jsx(es,{className:"h-4 w-4"})}),e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:"Society"})]}),e.jsxs("div",{role:"alert",className:"rounded-lg border border-destructive/30 bg-destructive/5 p-6 text-sm",children:[e.jsx("p",{className:"font-medium text-foreground",children:Oe.title}),e.jsx("p",{className:"mt-1 text-muted-foreground",children:Oe.detail}),e.jsxs("div",{className:"mt-4 flex gap-2",children:[Oe.retryable&&e.jsx(g,{onClick:()=>{m()}
3962,disabled:c,children:c?"Trying againâ¦":"Try again"}),e.jsx(g,{variant:"outline",onClick:()=>t("/platform/societies"),children:"Back to societies"})]})]})]})}return e.jsxs("div",{className:"space-y-6",children:[e.jsx(Y,{className:"h-8 w-48"}),e.jsx(Y,{className:"h-96 w-full"})]})}return e.jsxs("div",{className:n&&(_e||_)?"space-y-6 pb-24":"space-y-6",children:[e.jsx(yy,{}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx(g,{variant:"ghost",size:"icon","aria-label":n?"Back to society overview":"Back to societies",onClick:()=>t(n?`/platform/societies/${a}`:"/platform/societies"),children:e.jsx(es,{className:"h-4 w-4","aria-hidden":"true"})}),e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(ga,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0 flex-1 basis-56",children:[n&&e.jsxs("nav",{"aria-label":"Breadcrumb",className:"break-words text-xs text-muted-foreground",children:[e.jsx(je,{to:"/platform/societies",className:"hover:text-foreground hover:underline",children:"Societies"}),e.jsx("span",{"aria-hidden":"true",children:" / "}),e.jsx(je,{to:`/platform/societies/${a}`,className:"hover:text-foreground hover:underline",children:r?.name}),e.jsx("span",{"aria-hidden":"true",children:" / "}),e.jsx("span",{"aria-current":"page",children:"Settings"})]}),e.jsx("h1",{className:"break-words text-2xl font-semibold tracking-tight",children:n?r?.name??"Society":"Create society"}),e.jsx("p",{className:"mt-1 break-words text-sm text-muted-foreground",children:n?`Society configuration${r?.slug?` · ${r.slug}`:""}`:"Add a new society to the platform"})]}),n&&a&&e.jsxs(g,{type:"button",variant:"outline",className:"shrink-0",onClick:()=>{t(Br(a))},children:[e.jsx(Xc,{className:"mr-2 h-4 w-4","aria-hidden":"true"}),"Open society workspace"]})]}),e.jsxs(wj,{...f,children:[n?e.jsx(mT,{control:w,baseline:E,onChange:z}):e.jsx(hT,{control:w}),k&&e.jsx(uT,{onEdit:ce,pageWriteRef:P}),e.jsxs(SA,{value:Se,children:[e.jsx(kA,{value:E,children:e.jsxs(Ur,{value:p,onValueChange:x,children:[e.jsx("div",{className:"-mx-1 overflow-x-auto px-1",children:e.jsxs(ir,{className:"inline-flex h-auto w-auto min-w-full gap-1 rounded-lg bg-muted/60 p-1",children:[e.jsxs(bs,{value:"general",className:pr,children:[e.jsx(ga,{className:"h-4 w-4"}),"General",e.jsx(ll,{show:n&&il("general",ae)})]}),n&&e.jsxs(bs,{value:"branding",className:pr,children:[e.jsx(Vl,{className:"h-4 w-4"}),"Branding",e.jsx(ll,{show:il("branding",ae)})]}),e.jsxs(bs,{value:"membership",className:pr,children:[e.jsx(Lt,{className:"h-4 w-4"}),"Membership",e.jsx(ll,{show:n&&il("membership",ae)})]}),n&&e.jsxs(bs,{value:"features",className:pr,children:[e.jsx(gi,{className:"h-4 w-4"}),"Features",e.jsx(ll,{show:il("features",ae)})]}),n&&e.jsxs(bs,{value:"integrations",className:pr,children:[e.jsx(Ql,{className:"h-4 w-4"}),"Integrations"]}),n&&e.jsxs(bs,{value:"customization",className:pr,children:[e.jsx(vp,{className:"h-4 w-4"}),"Customization"]})]})}),e.jsx(js,{value:"general",forceMount:!0,className:"mt-6 data-[state=inactive]:hidden",children:e.jsx(AA,{isEditing:n,societyId:a,disabled:_,active:p==="general"})}),n&&e.jsx(js,{value:"branding",forceMount:!0,className:"mt-6 data-[state=inactive]:hidden",children:e.jsx(EA,{societyId:a,logoUrl:r?.logo_url,faviconUrl:r?.favicon_url,disabled:_,active:p==="branding"})}),e.jsxs(js,{value:"membership",forceMount:!0,className:"mt-6 data-[state=inactive]:hidden",children:[e.jsx(FA,{disabled:_}),n&&e.jsx("div",{className:"mt-6",children:e.jsx(RA,{societyId:a})})]}),n&&e.jsx(js,{value:"features",forceMount:!0,className:"mt-6 data-[state=inactive]:hidden",children:e.jsx($A,{societyId:a,disabled:_,onOpenTab:x,active:p==="features"})}),n&&e.jsx(js,{value:"integrations",className:"mt-6",children:e.jsx(QE,{societyId:a})}),n&&e.jsx(js,{value:"customization",className:"mt-6",children:e.jsx(XE,{societyId:a})})]})}),n?e.jsx(iT,{changeCount:ue,isSaving:_,error:ee,onDiscard:ke,onSave:Se}):e.jsxs("div",{className:"mt-6 space-y-3",children:[k&&e.jsxs("p",{className:"text-sm text-destructive",role:"alert",children:["Society not created. ",k.message]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(g,{type:"button",variant:"outline",onClick:()=>t("/platform/societies"),children:"Cancel"}),e.jsx(g,{type:"button",onClick:Se,disabled:_,children:_?"Creatingâ¦":"Create society"})]})]})]})]}),e.jsx(lT,{blocker:se,changeCount:ue,isSaving:_,isCreating:!n})]})}const dT=["name","slug","description","contact_email","contact_phone","website_url","primary_color","dues_cycle_start_day","grace_peri
3962od_days"];class ic extends Error{causes;constructor(s,a){super(s),this.causes=a}}function mT({control:t,baseline:s,onChange:a}){const n=Zp({control:t}),r=s?xl({...Tc,...n},s):_y,i=JSON.stringify(r);return o.useEffect(()=>{a(i)},[i,a]),null}function uT({onEdit:t,pageWriteRef:s}){const{watch:a}=Rr();return o.useEffect(()=>{const n=a((r,{name:i})=>{i&&!s.current&&t()});return()=>n.unsubscribe()},[a,t,s]),null}function hT({control:t}){const{setValue:s,getFieldState:a}=Rr(),n=Zp({control:t,name:"name"});return o.useEffect(()=>{if(a("slug").isTouched)return;const r=n.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"");s("slug",r)},[n,s,a]),null}function gh(){const{id:t}=Ds();return e.jsx(cT,{},t??"new")}function pT(){const{id:t}=Ds(),{search:s}=ta(),a=new URLSearchParams(s);return t&&(a.has("tab")||a.has("qbo"))?e.jsx(_t,{to:`/platform/societies/${t}/settings${s}`,replace:!0}):t?e.jsx(xT,{societyId:t},t):null}const Wd={staleTime:0,refetchOnMount:"always"},Sy={staleTime:3e4};function xT({societyId:t}){const s=Ir(t),a=Ms(s,t),n=Ms(re({queryKey:["setup-status",t],queryFn:()=>Ks.getSetupStatus(t),...Wd}),t),r=new URLSearchParams(ta().search).has("setup");if(s.isError&&!s.data)return e.jsxs("div",{className:"space-y-6",children:[e.jsx(fh,{}),e.jsx("div",{className:"rounded-lg border",children:e.jsx(ja,{title:"This society couldnât be loaded.",error:s.error,onRetry:()=>{s.refetch()},isRetrying:s.isFetching,notFound:"This society doesnât exist, or it was deleted."})})]});if(!s.data)return e.jsxs("div",{className:"space-y-6",children:[e.jsx(Y,{className:"h-10 w-72"}),e.jsx(Y,{className:"h-48 w-full"})]});const i=s.data;return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx(fh,{}),e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(ga,{className:"h-5 w-5","aria-hidden":"true"})}),e.jsxs("div",{className:"min-w-0 flex-1 basis-56",children:[e.jsxs("nav",{"aria-label":"Breadcrumb",className:"break-words text-xs text-muted-foreground",children:[e.jsx(je,{to:"/platform/societies",className:"hover:text-foreground hover:underline",children:"Societies"}),e.jsx("span",{"aria-hidden":"true",children:" / "}),e.jsx("span",{"aria-current":"page",children:i.name})]}),e.jsx("h1",{className:"break-words text-2xl font-semibold tracking-tight",children:i.name}),e.jsxs("p",{className:"mt-1 flex flex-wrap items-center gap-2 text-sm text-muted-foreground",children:[e.jsx("span",{className:"min-w-0 break-all",children:i.slug}),e.jsx("span",{"aria-hidden":"true",children:"·"}),e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx("span",{className:me("h-1.5 w-1.5 rounded-full",i.is_active?"bg-emerald-500":"bg-muted-foreground/60"),"aria-hidden":"true"}),i.is_active?"Active":"Inactive"]})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(g,{variant:"outline",asChild:!0,children:e.jsxs(je,{to:`/platform/societies/${t}/settings`,children:[e.jsx(cn,{className:"mr-2 h-4 w-4","aria-hidden":"true"}),"Settings"]})}),e.jsx(g,{asChild:!0,children:e.jsxs(je,{to:Br(t),children:[e.jsx(Xc,{className:"mr-2 h-4 w-4","aria-hidden":"true"}),"Open workspace"]})})]})]}),e.jsx(Ma,{view:a,what:"this society"}),e.jsx(yT,{societyId:t,view:n,emphasize:r}),e.jsx(fT,{societyId:t}),e.jsxs("div",{className:"grid gap-6 lg:grid-cols-2",children:[e.jsx(jT,{societyId:t}),e.jsx(vT,{societyId:t}),e.jsx(wT,{societyId:t,addAdminHref:n.readyData?.items.find(l=>l.key==="admin_user_exists")?.platform_url??`/platform/users?society=${t}&add=society_admin`}),e.jsx(NT,{societyId:t})]})]})}const gT=[{tab:"general",label:"General",detail:"Name, contact, active status, custom domain"},{tab:"branding",label:"Branding",detail:"Logo, favicon, brand color"}
3962,{tab:"membership",label:"Membership",detail:"Dues cycle and grace period"},{tab:"features",label:"Features",detail:"Commerce, committees, directory, and more"},{tab:"integrations",label:"Integrations",detail:"Stripe, email sender, Mailchimp, â¦"},{tab:"customization",label:"Customization",detail:"Custom fields, badge types"}];function fT({societyId:t}){return e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsx(Kr,{icon:cn,children:"Configuration"})}),e.jsx($,{children:e.jsx("ul",{className:"grid gap-2 sm:grid-cols-2 lg:grid-cols-3",children:gT.map(s=>e.jsx("li",{children:e.jsxs(je,{to:`/platform/societies/${t}/settings?tab=${s.tab}`,className:"block rounded-md border px-3 py-2 text-sm hover:bg-muted/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[e.jsx("span",{className:"font-medium",children:s.label}),e.jsx("span",{className:"block text-xs text-muted-foreground",children:s.detail})]})},s.tab))})})]})}function fh(){return e.jsx(g,{variant:"ghost",size:"icon",asChild:!0,children:e.jsx(je,{to:"/platform/societies","aria-label":"Back to societies",children:e.jsx(es,{className:"h-4 w-4","aria-hidden":"true"})})})}function Kr({icon:t,children:s}){return e.jsxs(ie,{className:"flex items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(t,{className:"h-4 w-4","aria-hidden":"true"})}),s]})}function yh(t){return t.charAt(0).toUpperCase()+t.slice(1)}function Sr({view:t,what:s,children:a}){return t.state==="ready"&&t.readyData!==void 0?e.jsxs("div",{className:"space-y-3",children:[e.jsx(Ma,{view:t,what:s}),a(t.readyData)]}):t.state==="offline"?e.jsx(Wa,{title:`${yh(s)} not loaded`}):t.state==="failed"?e.jsx(ja,{title:`${yh(s)} couldnât be loaded.`,error:t.error,onRetry:t.retry,isRetrying:t.retrying}):e.jsx(Y,{className:"h-16 w-full"})}function Cy(t,s){return s.platform_url??Br(t,s.url)}function yT({societyId:t,view:s,emphasize:a}){return e.jsxs(L,{className:me("min-w-0 overflow-hidden",a&&s.readyData?.required_complete!==!0&&"ring-2 ring-primary/40"),children:[e.jsx(ne,{className:"pb-3",children:e.jsx(Kr,{icon:Kt,children:"Setup"})}),e.jsx($,{children:e.jsx(Sr,{view:s,what:"setup status",children:n=>e.jsx(bT,{societyId:t,data:n})})})]})}function bT({societyId:t,data:s}){const a=s.items.filter(l=>l.required),n=s.items.filter(l=>!l.required),r=a.filter(l=>!l.configured),i=r[0]??n.find(l=>!l.configured);return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("p",{role:"status",className:"text-sm",children:[s.required_complete?e.jsx("span",{className:"font-medium text-emerald-700 dark:text-emerald-400",children:"Ready to operate: every required step is done."}):e.jsxs("span",{className:"font-medium text-amber-700 dark:text-amber-400",children:[r.length," required ",r.length===1?"step":"steps"," left before this society is ready."]})," ",e.jsx("span",{className:"text-muted-foreground",children:"Active or inactive is separate: an inactive society is closed to members and skips automatic renewal charges, dunning and renewal reminders."})]}),i&&e.jsx(g,{asChild:!0,size:"sm",variant:i.required?"default":"outline",children:e.jsxs(je,{to:Cy(t,i),children:[i.required?"Next":"Optional",": ",i.label,e.jsx(as,{className:"ml-2 h-4 w-4","aria-hidden":"true"})]})})]}),e.jsx(bh,{title:"Required",items:a,societyId:t}),e.jsx(bh,{title:"Optional",items:n,societyId:t})]})}function bh({title:t,items:s,societyId:a}){return s.length===0?null:e.jsxs("section",{"aria-label":`${t} setup`,children:[e.jsx("h3",{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:t}),e.jsx("ul",{className:"mt-2 divide-y rounded-md border",children:s.map(n=>e.jsxs("li",{className:"flex items-center gap-3 px-3 py-2 text-sm",children:[n.configured?e.jsx(Kt,{className:"h-4 w-4 shrink-0 text-emerald-600","aria-hidden":"true"}):e.jsx(Bl,{className:"h-4 w-4 shrink-0 text-muted-foreground","aria-hidden":"true"}),e.jsxs("span",{className:"min-w-0 flex-1",children:[n.label,e.jsx("span",{className:"sr-only",children:n.configured?" (done)":" (to do)"})]}),!n.configured&&e.jsx(je,{to:Cy(a,n),className:"shrink-0 text-sm font-medium text-primary underline-offset-2 hover:underline","aria-label":`${n.label}${n.platform_url?"":" (in the society workspace)"}`,children:n.platform_url?"Set up":"Open in workspace"})]},n.key))})]})}function jT({societyId:t}){const s=Ms(re({queryKey:["platform","integration-health",t],queryFn:()=>bi.getIntegrationHealth(t),...Wd}),t);return e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsx(Kr,{icon:Ql,children:"Services"})}),e.jsx($,{children:e.jsx(Sr,{view:s,what:"service status",children:a=>e.jsx(xy,{societyId:t,integrations:a})})})]})}function vT({societyId:t}){const s=Ms(re({queryKey:["society-stats",t],queryFn:()=>Ks.getStats(t),...Sy}),t);return e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsx(Kr,{icon:Lt,children:"Members"})}),e.jsx($,{children:e.jsx(Sr,{view:s,what:"member counts",children:a=>e.jsx("dl",{className:"grid grid-cols-2 gap-3 text-sm",children:[["Member records",a.total_members],["Active",a.active_members],["Pending",a.pending_members],["Expiring in 30 days",a.expiring_30_days]].map(([n,r])=>e.jsxs("div",{children:[e.jsx("dt",{className:"text-muted-foreground",children:n}),e.jsx("dd",{className:"text-lg font-semibold",children:(r??0).toLocaleStr
3962ing()})]},n))})})})]})}const jh=20;function wT({societyId:t,addAdminHref:s}){const a=i=>({queryKey:["users",{society_id:t,role:i,size:jh}],queryFn:()=>Pa.list({society_id:t,role:i,size:jh}),...Sy}),n=Ms(re(a("society_admin")),t),r=Ms(re(a("society_staff")),t);return e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsx(Kr,{icon:zc,children:"Administrators and staff"})}),e.jsxs($,{className:"space-y-4",children:[e.jsx(Sr,{view:n,what:"administrators",children:i=>e.jsxs("div",{className:"space-y-2",children:[!i.items.some(l=>l.is_active)&&i.total<=i.items.length&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:[i.total===0?"No society admin yet":"No active society admin",", so no one can run this society."," ",e.jsx(je,{to:s,className:"font-medium text-foreground underline underline-offset-2",children:"Add a society admin"}),"."]}),i.total>0&&e.jsx(vh,{societyId:t,users:i.items,total:i.total})]})}),e.jsx(Sr,{view:r,what:"staff",children:i=>i.total===0?null:e.jsx(vh,{societyId:t,users:i.items,total:i.total})})]})]})}function vh({societyId:t,users:s,total:a}){return e.jsxs("div",{className:"space-y-2 text-sm",children:[e.jsx("ul",{className:"space-y-2",children:s.map(n=>e.jsxs("li",{className:"flex items-center justify-between gap-3",children:[e.jsxs("span",{className:"min-w-0 truncate",children:[e.jsx("span",{className:"font-medium",children:ro(n).fullName||n.email})," ",e.jsxs("span",{className:"text-muted-foreground",children:["· ",Ea[n.role]]}),!n.is_active&&e.jsx("span",{className:"text-muted-foreground",children:" · inactive"})]}),e.jsx("span",{className:"shrink-0 text-xs text-muted-foreground",children:n.last_login_at?`Signed in ${Yn(n.last_login_at)}`:"Never signed in"})]},n.id))}),a>s.length&&e.jsxs("p",{className:"text-muted-foreground",children:["Showing ",s.length," of ",a,"."," ",e.jsx(je,{to:`/platform/users?society=${t}`,className:"font-medium text-foreground underline underline-offset-2",children:"See everyone in Users"})]})]})}function NT({societyId:t}){const s=Ms(re({queryKey:["audit","society-overview",t],queryFn:()=>ji.list({society_id:t,size:8}),...Wd}),t);return e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsx(Kr,{icon:Bc,children:"Recent activity"})}),e.jsx($,{children:e.jsx(Sr,{view:s,what:"activity",children:a=>a.items.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No activity recorded yet."}):e.jsx("ul",{className:"space-y-2 text-sm",children:a.items.map(n=>e.jsxs("li",{className:"min-w-0",children:[e.jsx("p",{className:"break-words",children:n.description}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[n.user_name??n.user_email??"System"," · ",Yn(n.created_at)]})]},n.id))})})})]})}const wh={disabled:"Sync is not enabled for this society.",connection_broken:"The QuickBooks connection is broken â reconnect from the integrations tab first.",realm_mismatch:"The saved configuration belongs to a different QuickBooks company â re-save the configuration first.",fee_discount_item_collision:"The fee item matches the discount item â fix the item configuration first.",stripe_not_configured:"Stripe keys are not configured for this society.",sync_in_progress:"A sync is already running for this society."};function Nh(t){if(t.summary){const n=t.summary,r=`${n.synced} synced · ${n.failed} failed · ${n.needs_review} needs review · ${n.skipped} skipped`,i=Object.keys(n.discovery_errors);return i.length>0?{tone:"partial",message:`Run incomplete â could not scan: ${i.join(", ")}. Counts may be missing records. ${r}`}:n.failed>0||n.needs_review>0||n.errors.length>0?{tone:"attention",message:`Run finished with records needing action â ${r}`}:{tone:"success",message:`Run complete â ${r}`}}const s=t.error?.response,a=typeof s?.data?.detail=="string"?s.data.detail:"";return s?.status===409&&Object.hasOwn(wh,a)?{tone:"blocked",message:wh[a]}:s?.status===503?{tone:"transient",message:"QuickBooks token refresh is temporarily unavailable â this usually self-heals; try again shortly."}:{tone:"generic",message:"The sync run could not be started."}}function kT(t){return t.status==="failed"?["force-retry","mark-resolved"]:t.status==="needs_review"?t.object_type==="refund_receipt"&&t.error_code==="parent_drift"?["re-snapsh
3962ot-parent","force-retry","mark-resolved"]:["force-retry","mark-resolved"]:[]}function _T(t){return t.qbo_id===null}const ST=/^[A-Za-z0-9._-]{1,21}$/;function Fc(t){return ST.test(t)}function CT(t){const s=t?.response,a=typeof s?.data?.detail=="string"?s.data.detail:"";return a==="sync_in_progress"?"A sync is running for this society â try again in a minute.":(s?.status===409||s?.status===422)&&a?a:s?.status===502&&a?`QuickBooks could not be reached (code: ${a}) â check the connection and try again.`:"The recovery action failed."}const PT="Transfers have no reference number in QuickBooks â this record can only be resolved externally or retried.",AT="This transfer's stored QuickBooks document will be re-verified (transfers have no reference number to look up).",ET={"force-retry":"Force retry","mark-resolved":"Mark resolved","re-snapshot-parent":"Re-snapshot parent receipt"},TT={"force-retry":"Re-runs this record now. A record that already created a QuickBooks document is re-checked against it â nothing is created twice.","mark-resolved":"Closes this record by hand.","re-snapshot-parent":"The original sale's QuickBooks receipt was edited after posting, which blocked this refund. This re-reads the receipt as it is now and adopts the edit, then you can force-retry the refund."};function FT({row:t,kind:s,societyId:a,open:n,onOpenChange:r,onSuccess:i}){const l=JA(),m=_T(t),c=s==="mark-resolved",d=t.object_type==="transfer"&&t.qbo_id!==null,[u,h]=o.useState(""),[p,x]=o.useState("document"),[f,b]=o.useState(t.qbo_doc_number??""),[N,j]=o.useState(null),w=c&&(!m||p==="document")&&!d,v=t.object_type==="transfer"&&w,k=f.trim(),S=k.length>0&&!Fc(k),_=l.isPending||u.trim().length===0||v||w&&(k.length===0||!Fc(k)),y=()=>{j(null),l.mutate({kind:s,recordId:t.id,societyId:a,note:u,qboDocNumber:w?k:void 0},{onSuccess:()=>{i?.(),r(!1)},onError:C=>j(CT(C))})};return e.jsx(Fe,{open:n,onOpenChange:l.isPending?void 0:r,children:e.jsxs(Te,{children:[e.jsxs(Ae,{children:[e.jsx(Ee,{children:ET[s]}),e.jsx(tt,{children:TT[s]})]}),c&&e.jsxs("div",{className:"space-y-3",children:[m?e.jsxs(Cn,{value:p,onValueChange:C=>x(C),children:[e.jsx("label",{htmlFor:"resolve-mode-document",className:"flex cursor-pointer flex-col gap-0.5 rounded-md border p-3 text-sm has-[[data-state=checked]]:border-brand-navy",children:e.jsxs("span",{className:"flex items-center gap-2 font-medium",children:[e.jsx(la,{id:"resolve-mode-document",value:"document"}),"Point at an existing QuickBooks document"]})}),e.jsxs("label",{htmlFor:"resolve-mode-external",className:"flex cursor-pointer flex-col gap-0.5 rounded-md border p-3 text-sm has-[[data-state=checked]]:border-brand-navy",children:[e.jsxs("span",{className:"flex items-center gap-2 font-medium",children:[e.jsx(la,{id:"resolve-mode-external",value:"external"}),"Resolved outside QuickBooks"]}),e.jsx("span",{className:"pl-6 text-xs text-muted-foreground",children:"Record is closed and no document will ever be linked."})]})]}):e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-sm font-medium",children:d?"Verify the stored QuickBooks document":"Point at an existing QuickBooks document"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:d?AT:"This record is already tied to a QuickBooks document â enter its reference number to verify against a different one, or leave the prefilled value."})]}),w&&!v&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(T,{htmlFor:"resolve-qbo-id",children:"QuickBooks reference no."}),e.jsx(O,{id:"resolve-qbo-id",value:f,onChange:C=>b(C.target.value),disabled:l.isPending}),S&&e.jsx("p",{className:"text-xs text-destructive",children:"Use letters, numbers, periods, underscores, or hyphens only (max 21 characters)."}),e.jsx("p",{className:"text-xs text-muted-foreground",children:'The "NO." shown on the transaction in QuickBooks â on the receipt itself and in every transaction list.'})]}),v&&m&&e.jsx("p",{className:"text-xs text-muted-foreground",children:PT})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(T,{htmlFor:"resolution-note",children:"Resolution note"}),e.jsx(It,{id:"resolution-note",value:u,onChange:C=>h(C.target.value),disabled:l.isPending})]}),N&&e.jsx("p",{className:"text-sm text-destructive",children:N}),e.jsxs(Ge,{children:[e.jsx(g,{type:"button",variant:"outline",onClick:()=>r(!1),disabled:l.isPending,children:"Cancel"}),e.jsx(g,{type:"button",onClick:y,disabled:_,children:l.isPending?"Workingâ¦":"Confirm"})]})]})})}const RT={unhandled_category:"Unhandled category",missing_in_ledger:"Missing from ledger",missing_in_qbo:"Missing in QuickBooks",total_mismatch_in_qbo:"Total mismatch in QuickBooks",clearing_variance:"Clearing variance"},kh={sales_receipt:"Sales receipt",refund_receipt:"Refund receipt",dispute_journal_entry:"Dispute journal entry",transfer:"Transfer",purchase:"Purchase"};function xi(t){return t?Object.hasOwn(kh,t)?kh[t]:t.length>0?t[0].toUpperCase()+t.slice(1).replace(/_/g," "):t:"â"}function MT(t){return t.status!=="open"?[]:t.flag_type==="missing_in_ledger"?["resolve-slots"]:t.flag_type==="missing_in_qbo"?["acknowledge","retarget","convert-external"]:["acknowledge"]}function DT(t){return t==="retarget"||t==="resolve-slots"}const _h={disabled:"Sync is not enabled for this society.",connection_broken:"The QuickBooks connection is broken â reconnect from the integrations tab first.",realm_mismatch:"The saved configuration belongs to a different QuickBooks company â re-save the configuration first.",stripe_not_configured:"Stripe keys are not configured for this society.",cutover_not_configured:"Set a cutover date for this society before running a tie-out.",pre_cutover_peri
3962od:"Run a tie-out only for months after the cutover date.",society_not_found:"Society not found."};function Py(t){const s=t?.response,a=typeof s?.data?.detail=="string"?s.data.detail:"";return a==="sync_in_progress"?"A sync is running for this society â try again in a minute.":s?.status===409&&Object.hasOwn(_h,a)?_h[a]:(s?.status===409||s?.status===422)&&a?a:s?.status===502&&a?`QuickBooks could not be reached (code: ${a}) â check the connection and try again.`:s?.status===503?"Token refresh is temporarily unavailable â try again shortly.":"The tie-out action failed."}function sn(t){return t==null?"â":new Intl.NumberFormat("en-US",{style:"currency",currency:"USD"}).format(t/100)}const Sh={payout_carryover_before_cutover:"a payout carried a balance from before the cutover date â set the cutover to a clean payout boundary",realm_mismatch:"the saved configuration belongs to a different QuickBooks company",unsupported_currency:"the clearing check only supports USD movements",cutover_not_midnight_aligned:"the cutover isn't midnight-aligned, so the clearing window is ambiguous",gl_report_parse:"QuickBooks returned a general-ledger report this check could not read",incomplete_leg1:"an earlier leg failed, so this check could not run",internal_error:"an unexpected error interrupted the check"};function lc(t){return Object.hasOwn(Sh,t)?Sh[t]:t}function LT(t){return Object.values(t.flags_created).reduce((s,a)=>s+a,0)}function $T(t){if(!t)return{tone:"none",badge:"No tie-out has run yet"};const s=Object.keys(t.errors).length;if(s>0)return{tone:"attention",badge:`Tie-out incomplete â ${s} check${s===1?"":"s"} could not run`};const a=t.variance_cents??0;return LT(t)>0||a!==0?{tone:"attention",badge:`Needs attention â variance ${sn(t.variance_cents)}`}:{tone:"ok",badge:`Books agree â variance ${sn(t.variance_cents)}`}}function qT(t){if(!t)return[];const s=(t.flags_created.unhandled_category??0)+(t.flags_created.missing_in_ledger??0),a=(t.flags_created.missing_in_qbo??0)+(t.flags_created.total_mismatch_in_qbo??0),n=t.errors.leg1,r=t.errors.leg2??t.errors.leg2_realm,i=t.errors.leg3,l=n?{name:"Stripe â ledger",desc:"Every owned movement has its document",result:`Skipped â ${lc(n)}`,tone:"attention"}:{name:"Stripe â ledger",desc:"Every owned movement has its document â no unmatched charges, refunds, disputes, or payouts",result:`${s>0?`${s} flag${s===1?"":"s"}`:"0 flags"}${(t.minimum_balance_suppressed??0)>0?` · ${t.minimum_balance_suppressed} skipped (minimum balance)`:""}`,tone:s>0?"attention":"ok"},m=r?{name:"Ledger â QuickBooks",desc:"Every synced document still exists in QuickBooks",result:`Skipped â ${lc(r)}`,tone:"attention"}:{name:"Ledger â QuickBooks",desc:"Every synced document still exists in QuickBooks with the expected total",result:a>0?`${a} flag${a===1?"":"s"} · ${t.leg2_checked} verified`:`${t.leg2_checked} verified`,tone:a>0?"attention":"ok"};let c;if(i)c={name:"Clearing account",desc:"Stripe clearing movement matches QuickBooks",result:`Skipped â ${lc(i)}`,tone:"attention"};else if(t.expected_movement_cents===null&&t.actual_movement_cents===null)c={name:"Clearing account",desc:"Stripe clearing movement matches QuickBooks",result:"No movement this period",tone:"ok"};else{const d=t.variance_cents??0;c={name:"Clearing account",desc:`Expected movement ${sn(t.expected_movement_cents)} · QuickBooks actual ${sn(t.actual_movement_cents)}`,result:`variance ${sn(t.variance_cents)}`,tone:d===0?"ok":"attention"}}return[l,m,c]}function Ay(t){const s=Mi(t);if(s)return`${s.getUTCFullYear()}-${String(s.getUTCMonth()+1).padStart(2,"0")}`}function IT(t=new Date,s){const a=t.getUTCFullYear(),n=t.getUTCMonth(),r=n===0?11:n-1,l=`${n===0?a-1:a}
3962-${String(r+1).padStart(2,"0")}`,m=Ay(s);return m&&m>l?m:l}function OT(t){return Ay(t?.cutover_at)}const UT=/^[0-9]+$/,zT="Transfers have no reference number â paste the id from the transfer's QuickBooks URL.",BT='The "NO." shown on the transaction in QuickBooks â on the document itself and in every transaction list.',KT={acknowledge:"Acknowledge flag",retarget:"Point at a QuickBooks document","convert-external":"Convert to external","resolve-slots":"Resolve missing documents"},QT={acknowledge:"Record that this movement has been handled manually in QuickBooks. Acknowledging does not change any books.",retarget:"Tie this flag to the QuickBooks document that already covers the movement. The reference is re-checked against QuickBooks before the flag closes.","convert-external":"The ledger entry will stop being verified against QuickBooks. The monthly clearing check still covers the movement's effect.","resolve-slots":"Tell the tie-out how each expected document was handled. Point at the QuickBooks document that covers it, or mark it resolved outside QuickBooks."};function Rc(t,s){return t==="transfer"?UT.test(s):Fc(s)}function Ch({id:t,objectType:s,value:a,onChange:n,disabled:r}){const i=s==="transfer",l=a.trim(),m=l.length>0&&!Rc(s,l);return e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(T,{htmlFor:t,children:i?"QuickBooks internal id":"QuickBooks reference no."}),e.jsx(O,{id:t,value:a,onChange:c=>n(c.target.value),disabled:r}),m&&e.jsx("p",{className:"text-xs text-destructive",children:i?"Use digits only â the id from the transferâs QuickBooks URL.":"Use letters, numbers, periods, underscores, or hyphens only (max 21 characters)."}),e.jsx("p",{className:"text-xs text-muted-foreground",children:i?zT:BT})]})}function WT({flag:t,action:s,societyId:a,open:n,onOpenChange:r}){const i=XA(),[l,m]=o.useState(""),[c,d]=o.useState(null),[u,h]=o.useState(""),p=t.missing_slots.includes("unavailable"),x=p?[]:t.missing_slots,[f,b]=o.useState(()=>x.map(()=>({flavor:"object",identifier:""}))),N=t.object_type==="transfer",j=l.trim().length===0,w=(y,C)=>{b(P=>P.map((A,E)=>E===y?{...A,...C}:A))};let v=!0;s==="retarget"?v=Rc(N?"transfer":t.object_type??"",u.trim()):s==="resolve-slots"&&(v=!p&&x.every((y,C)=>{const P=f[C];return P.flavor==="external"?!0:Rc(y,P.identifier.trim())}));const k=i.isPending||j||!v,S=()=>{d(null);const y={action:s,flagId:t.id,societyId:a,note:l};s==="retarget"?N?y.qboId=u.trim():y.qboDocNumber=u.trim():s==="resolve-slots"&&(y.dispositions=x.map((C,P)=>{const A=f[P];return A.flavor==="external"?{object_type:C,flavor:"external"}:C==="transfer"?{object_type:C,flavor:"object",qbo_id:A.identifier.trim()}:{object_type:C,flavor:"object",qbo_doc_number:A.identifier.trim()}})),i.mutate(y,{onSuccess:()=>r(!1),onError:C=>d(Py(C))})},_=s==="resolve-slots"&&x.length===0&&!p;return e.jsx(Fe,{open:n,onOpenChange:i.isPending?void 0:r,children:e.jsxs(Te,{children:[e.jsxs(Ae,{children:[e.jsx(Ee,{children:KT[s]}),e.jsx(tt,{children:QT[s]})]}),s==="retarget"&&e.jsx(Ch,{id:"tieout-retarget-id",objectType:N?"transfer":t.object_type??"",value:u,onChange:h,disabled:i.isPending}),s==="convert-external"&&e.jsx("p",{className:"rounded-md border border-amber-200 bg-amber-50 p-3 text-xs text-amber-700 dark:border-amber-900/40 dark:bg-amber-950/20 dark:text-amber-300",children:"The ledger entry will stop being verified against QuickBooks. The monthly clearing check still covers the movementâs effect."}),s==="resolve-slots"&&p&&e.jsx("p",{className:"rounded-md border border-amber-200 bg-amber-50 p-3 text-xs text-amber-700 dark:border-amber-900/40 dark:bg-amber-950/20 dark:text-amber-300",children:"Stripe could not be reached to enumerate the missing documents â retry later."}),_&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"All expected documents now exist in the ledger â confirming closes this flag."}),s==="resolve-slots"&&x.map((y,C)=>{const P=f[C];return e.jsxs("div",{className:"space-y-2 rounded-md border p-3",children:[e.jsx("p",{className:"text-sm font-medium",children:xi(y)}),e.jsxs(Cn,{value:P.flavor,onValueChange:A=>w(C,{flavor:A}),children:[e.jsxs("label",{htmlFor:`slot-${C}-object`,className:"flex cursor-pointer items-center gap-2 text-sm font-medium",children:[e.jsx(la,{id:`slot-${C}-object`,value:"object"}),"Point at an existing QuickBooks document"]}),e.jsxs("label",{htmlFor:`slot-${C}-external`,className:"flex cursor-pointer flex-col gap-0.5 text-sm",children:[e.jsxs("span",{className:"flex items-center gap-2 font-medium",children:[e.jsx(la,{id:`slot-${C}-external`,value:"external"}),"Resolved outside QuickBooks"]}),e.jsx("span",{className:"pl-6 text-xs text-muted-foreground",children:"The movement is recorded elsewhere and no QuickBooks document will be linked."})]})]}),P.flavor==="object"&&e.jsx(Ch,{id:`slot-${C}
3962-id`,objectType:y,value:P.identifier,onChange:A=>w(C,{identifier:A}),disabled:i.isPending})]},`${y}-${C}`)}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(T,{htmlFor:"tieout-note",children:"Resolution note"}),e.jsx(It,{id:"tieout-note",value:l,onChange:y=>m(y.target.value),disabled:i.isPending})]}),c&&e.jsx("p",{className:"text-sm text-destructive",children:c}),e.jsxs(Ge,{children:[e.jsx(g,{type:"button",variant:"outline",onClick:()=>r(!1),disabled:i.isPending,children:"Cancel"}),e.jsx(g,{type:"button",onClick:S,disabled:k,children:i.isPending?"Workingâ¦":"Confirm"})]})]})})}const VT="Reconnect QuickBooks to act on flags.",GT={acknowledge:"Acknowledge",retarget:"Point at document","convert-external":"Convert to external","resolve-slots":"Resolve"};function YT(t){const s=Mi(t);return s?Hp(s,{addSuffix:!0}):"never"}function HT({societyId:t,config:s}){const{data:a,isLoading:n,isError:r}=jy(t),[i,l]=o.useState(null),[m,c]=o.useState(null),d=s.connected===!0,u=a?.flags??[],h=s.last_tieout_summary,p=$T(h),x=qT(h),f=p.tone==="ok"?"bg-emerald-50 text-emerald-700 dark:bg-emerald-950/30 dark:text-emerald-300":p.tone==="attention"?"bg-amber-50 text-amber-700 dark:bg-amber-950/30 dark:text-amber-300":"bg-muted text-muted-foreground",b=p.tone==="ok"?"bg-emerald-500":p.tone==="attention"?"bg-amber-500":"bg-muted-foreground/60";return e.jsxs("section",{id:"tieout",className:"space-y-4 scroll-mt-6",children:[e.jsxs("div",{className:"flex flex-wrap items-baseline gap-x-3 gap-y-1",children:[e.jsx("h2",{className:"text-lg font-semibold tracking-tight",children:"Monthly tie-out"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:h?`Last run: ${h.period}, ${YT(s.last_tieout_at)}`:"No tie-out has run yet â run one after month-end to verify the books."}),e.jsx("span",{className:"flex-1"}),e.jsxs("span",{className:`inline-flex items-center gap-2 rounded-full px-3 py-1 text-xs font-semibold ${f}`,children:[e.jsx("span",{className:`h-1.5 w-1.5 shrink-0 rounded-full ${b}`}),p.badge]})]}),x.length>0&&e.jsx(L,{className:"min-w-0 overflow-hidden",children:e.jsx($,{className:"divide-y p-0",children:x.map(N=>e.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 px-4 py-3",children:[e.jsx("span",{className:"w-40 shrink-0 text-sm font-medium",children:N.name}),e.jsx("span",{className:"min-w-0 flex-1 text-xs text-muted-foreground",children:N.desc}),e.jsx("span",{className:`text-xs font-semibold tabular-nums ${N.tone==="ok"?"text-emerald-600 dark:text-emerald-400":"text-amber-600 dark:text-amber-400"}`,children:N.result})]},N.name))})}),e.jsx(L,{className:"min-w-0 overflow-hidden",children:e.jsx($,{className:"p-0",children:n?null:r?e.jsxs("div",{className:"m-3 flex items-start gap-2 rounded-lg border border-destructive/30 bg-destructive/10 p-3 text-sm text-destructive",children:[e.jsx(Dt,{className:"mt-0.5 h-4 w-4 shrink-0"}),e.jsx("p",{children:"Tie-out flags could not be loaded â refresh to retry."})]}):u.length===0?e.jsxs("div",{className:"flex flex-col items-center gap-1.5 py-10 text-center text-sm text-muted-foreground",children:[e.jsx(Kt,{className:"h-5 w-5 text-emerald-500"}),e.jsx("p",{children:"No open tie-out flags. Acknowledged flags move to the audit trail."})]}):e.jsxs(Pt,{children:[e.jsx(At,{className:"bg-muted/30",children:e.jsxs(Ue,{className:"hover:bg-transparent",children:[e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Period"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Type"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Document"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Amount"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Actions"})]})}),e.jsx(Et,{children:u.map(N=>{const j=MT(N),w=N.record_source_id??N.balance_txn_id;
3962return e.jsxs(Ue,{className:"hover:bg-brand-navy/[0.04] dark:hover:bg-brand-navy/10",children:[e.jsx(G,{className:"whitespace-nowrap text-xs font-mono",children:N.period}),e.jsx(G,{className:"whitespace-nowrap text-xs",children:e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-amber-500"}),e.jsx("span",{className:"font-medium",children:RT[N.flag_type]})]})}),e.jsxs(G,{className:"max-w-[18rem]",children:[e.jsx("div",{className:"truncate text-xs",title:xi(N.object_type),children:xi(N.object_type)}),w&&e.jsx("div",{className:"mt-0.5 truncate font-mono text-xs text-muted-foreground",title:w,children:w})]}),e.jsx(G,{className:"whitespace-nowrap font-mono text-xs",children:sn(N.amount_cents)}),e.jsx(G,{children:e.jsx("div",{className:"flex flex-wrap gap-2",children:j.map(v=>{const k=DT(v),S=m===N.id||k&&!d;return e.jsx(g,{type:"button",variant:"outline",size:"sm",disabled:S,title:k&&!d?VT:void 0,onClick:()=>{c(N.id),l({flag:N,action:v})},children:GT[v]},v)})})})]},N.id)})})]})})}),u.length>0&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Acknowledged flags leave this list â the audit log records them."}),i&&e.jsx(WT,{flag:i.flag,action:i.action,societyId:t,open:!!i,onOpenChange:N=>{N||(l(null),c(null))}})]})}function Vd(t){return t.status==="failed"||t.status==="needs_review"}function JT(t){return[...t.needs_review??[],...t.failed??[],...t.synced??[],...t.skipped??[]]}function ZT(t){return{all:t.length,needs_attention:t.filter(Vd).length,synced:t.filter(s=>s.status==="synced").length,skipped:t.filter(s=>s.status==="skipped").length}}function XT(t,s){return s==="all"?t:s==="needs_attention"?t.filter(Vd):s==="synced"?t.filter(a=>a.status==="synced"):t.filter(a=>a.status==="skipped")}function eF(t){return t.qbo_doc_number??t.qbo_id??null}function tF(t,s){const a=s.trim().toLowerCase();return a.length===0?!0:[t.source_id,t.qbo_doc_number,t.qbo_id,t.object_type].some(r=>(r??"").toLowerCase().includes(a))}function sF(t){switch(t){case"synced":return{label:"Synced",dot:"bg-emerald-500"};case"failed":return{label:"Failed",dot:"bg-red-500"};case"needs_review":return{label:"Needs review",dot:"bg-amber-500"};case"skipped":return{label:"Skipped",dot:"bg-muted-foreground/60"};default:return{label:xi(t),dot:"bg-muted-foreground/60"}}}function aF(t){return t.resolution_note&&t.resolved_at?{label:"Force-retried â synced",whenRaw:t.resolved_at}:t.synced_at?{label:"Auto-synced",whenRaw:t.synced_at}:{label:t.error_code??t.skip_reason??"Pending",whenRaw:t.last_attempt_at}}function nF(t,s){return(t?.synced_count??0)>(s?.length??0)}function Ph(t){return t==null?"(none)":typeof t=="boolean"?t?"on":"off":typeof t=="string"?t.length>0?t:"(empty)":typeof t=="object"?JSON.stringify(t):String(t)}function rF(t){return!t||typeof t!="object"?"":Object.entries(t).map(([a,n])=>{const r=n??{};return`${a}: ${Ph(r.old)} â ${Ph(r.new)}`}).join(" · ")}function iF(t){return t.changes&&typeof t.changes=="object"?t.changes:{}}function lF(t){if(!t||typeof t!="object")return!1;const s=t.enabled;if(!s||typeof s!="object")return!1;const{old:a,new:n}=s;return a!==n}function oc(t){return typeof t=="string"&&t.length>0?t:void 0}function Ey(t){return t.user_email??"Scheduled"}function oF(t){const s=iF(t),n={who:Ey(t),whenRaw:t.created_at},r=t.action??"";switch(r){case"qbo_tieout_run":{const i=oc(s.period);return{...n,tone:"ok",title:i?`Tie-out for ${i}`:"Tie-out run",detail:t.description||""}}case"qbo_recovery_force_retry":return{...n,tone:"ok",title:"Force retry",detail:t.description||""};case"qbo_recovery_mark_resolved":return{...n,tone:"ok",title:"Mark resolved",detail:t.description||""};case"qbo_recovery_re_snapshot":return{...n,tone:"ok",title:"Re-snapshot parent",detail:t.description||""};case"qbo_tieout_acknowledge":case"qbo_tieout_retarget":case"qbo_tieout_convert_external":case"qbo_tieout_resolve_slots":{const i={qbo_tieout_acknowledge:"Acknowledged tie-out flag",qbo_tieout_retarget:"Pointed tie-out flag at document",qbo_tieout_convert_external:"Converted tie-out flag to external",qbo_tieout_resolve_slots:"Resolved tie-out flag"}
3962,l=oc(s.flag_type),m=oc(s.period),c=[l,m].filter(Boolean).join(" · ");return{...n,tone:"ok",title:i[r],detail:c||t.description||""}}case"quickbooks_config_updated":{const i=rF(s.fields);return{...n,tone:lF(s.fields)?"warn":"mute",title:"Configuration updated",detail:i||t.description||""}}case"quickbooks_connected":return{...n,tone:"mute",title:"Connected QuickBooks",detail:t.description||""};case"quickbooks_disconnected":return{...n,tone:"mute",title:"Disconnected QuickBooks",detail:t.description||""};default:return{...n,tone:"mute",title:t.description||cF(r)||"Activity",detail:t.description??""}}}function cF(t){if(t.length===0)return"";const s=t.replace(/^(qbo_|quickbooks_)/,"").replace(/_/g," ");return s.length>0?s[0].toUpperCase()+s.slice(1):s}const dF={ok:"bg-emerald-500",warn:"bg-amber-500",bad:"bg-red-500",mute:"bg-muted-foreground/60"},mF=[{key:"all",label:"All"},{key:"needs_attention",label:"Needs attention"},{key:"synced",label:"Synced"},{key:"skipped",label:"Skipped"}];function Ah(t){if(an(t)){const s=t.response?.data?.detail;if(typeof s=="string"&&s.trim())return s}return"Something went wrong. Please try again."}function Eh(t){const s=Mi(t);return s?s.toLocaleString():"â"}const si={success:"border-emerald-200 bg-emerald-50 text-emerald-700 dark:border-emerald-900/40 dark:bg-emerald-950/20 dark:text-emerald-300",attention:"border-amber-200 bg-amber-50 text-amber-700 dark:border-amber-900/40 dark:bg-amber-950/20 dark:text-amber-300",blocked:"border-amber-200 bg-amber-50 text-amber-700 dark:border-amber-900/40 dark:bg-amber-950/20 dark:text-amber-300",transient:"border-amber-200 bg-amber-50 text-amber-700 dark:border-amber-900/40 dark:bg-amber-950/20 dark:text-amber-300",partial:"border-destructive/30 bg-destructive/10 text-destructive",generic:"border-destructive/30 bg-destructive/10 text-destructive"},uF={"force-retry":"Force retry","mark-resolved":"Mark resolved","re-snapshot-parent":"Re-snapshot parent"},cc="Reconnect QuickBooks to act on records.";function hF(t){const s=Object.values(t.flags_created).reduce((i,l)=>i+l,0),a=t.minimum_balance_suppressed??0,n=`Checked ${t.leg2_checked} documents · ${s} new flag${s===1?"":"s"} · variance ${sn(t.variance_cents)}${a>0?` · ${a} minimum-balance entr${a===1?"y":"ies"} skipped`:""}`,r=Object.keys(t.errors).length;return r>0?{tone:"partial",message:`Tie-out incomplete â ${r} check(s) could not run. ${n}`}:s>0||(t.variance_cents??0)!==0?{tone:"attention",message:n}:{tone:"success",message:`Tie-out clean â ${n}`}}function pF(t){return t?.connection_status==="connected"?{label:"Connected",dot:"bg-emerald-500"}:t?.connection_status==="broken"?{label:t.broken_reason?`Broken (${t.broken_reason})`:"Broken",dot:"bg-amber-500"}:{label:"Disconnected",dot:"bg-muted-foreground/60"}}function xF(){const{id:t}=Ds(),{data:s,isLoading:a}=Ir(t),{data:n,isError:r,error:i,refetch:l}=Qd(t),{data:m,isLoading:c,isError:d,error:u,refetch:h}=UA(t),p=HA(),x=ZA(),{data:f,isSuccess:b}=jy(t),N=zA(t),[j,w]=o.useState("ledger"),[v,k]=o.useState("all"),[S,_]=o.useState(""),[y,C]=o.useState(null),[P,A]=o.useState(null),[E,Q]=o.useState(null),[U,D]=o.useState(()=>IT(new Date,n?.cutover_at)),[K,xe]=o.useState(null),[z,ae]=o.useState(null),ue=`/platform/societies/${t}/settings?tab=integrations`,_e=n?.connected===!0,ee=Ce=>{h().then(ze=>{const Ze=ze.data?.synced?.find(de=>de.id===Ce);if(!Ze)return;const Re=Ze.qbo_doc_number??Ze.qbo_id;Q(Re?`Synced â QuickBooks ref ${Re}`:"Synced to QuickBooks.")})},se=()=>{t&&(C(null),p.mutate({societyId:t},{onSuccess:Ce=>C(Nh({summary:Ce})),onError:Ce=>C(Nh({error:Ce}))}))},le=()=>{t&&(A(null),x.mutate({societyId:t,period:Qe||void 0},{onSuccess:Ce=>A(hF(Ce)),onError:Ce=>A({tone:"generic",message:Py(Ce)})}))},oe=JT(m??{}),Pe=ZT(oe),M=XT(oe,v).filter(Ce=>tF(Ce,S)),I=nF(m?.totals,m?.synced),R=!m||m.failed.length===0&&m.needs_review.length===0&&m.skipped.length===0&&(m.synced?.length??0)===0,X=f?.open_count??0,Se=n?.connected===!1&&R&&b&&X===0,ce=Object.entries(m?.last_run_summary?.discovery_errors??{}),ke=Pe.needs_attention,ve=pF(n),Ne=OT(n),Qe=Ne&&U<Ne?Ne:U,Oe=(N.data?.activity??[]).map(Ce=>({id:Ce.id,...oF(Ce),who:Ey(Ce)}));return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx(g,{variant:"ghost",size:"icon",asChild:!0,children:e.jsx(je,{to:ue,"aria-label":"Back to integrations",children:e.jsx(es,{className:"h-4 w-4","aria-hidden":"true"})})}),e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-brand-navy
3962/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(Qp,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:"QuickBooks sync"}),e.jsx("p",{className:"mt-1 flex flex-wrap items-center gap-x-2 gap-y-0.5 text-sm text-muted-foreground",children:a||!s?"Loading societyâ¦":e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"font-medium text-foreground",children:s.name}),e.jsx("span",{"aria-hidden":!0,children:"·"}),e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx("span",{className:`h-1.5 w-1.5 shrink-0 rounded-full ${ve.dot}`}),ve.label]}),n?.company_name&&e.jsxs(e.Fragment,{children:[e.jsx("span",{"aria-hidden":!0,children:"·"}),e.jsx("span",{children:n.company_name})]})]})})]}),e.jsx(g,{variant:"outline",asChild:!0,children:e.jsx(je,{to:`/platform/societies/${t}/quickbooks/config`,children:"Configuration"})}),e.jsx(g,{onClick:se,disabled:p.isPending,children:p.isPending?"Runningâ¦":"Run sync now"}),e.jsxs("div",{className:"flex items-stretch",children:[e.jsx(g,{type:"button",className:"rounded-r-none",onClick:le,disabled:x.isPending||!_e,title:_e?void 0:cc,children:x.isPending?"Runningâ¦":"Run tie-out"}),e.jsx("input",{type:"month","aria-label":"Tie-out month",value:Qe,min:Ne,onChange:Ce=>D(Ce.target.value),className:"rounded-md rounded-l-none border border-l-0 border-input bg-background px-2 text-sm text-foreground focus:outline-none focus:ring-2 focus:ring-ring"})]})]}),E&&e.jsx("div",{className:`rounded-lg border p-3 text-sm ${si.success}`,children:E}),y&&e.jsx("div",{className:`rounded-lg border p-3 text-sm ${si[y.tone]??si.generic}`,children:y.message}),P&&e.jsx("div",{className:`rounded-lg border p-3 text-sm ${si[P.tone]??si.generic}`,children:P.message}),r?e.jsx(L,{className:"min-w-0 overflow-hidden border-destructive/30",children:e.jsxs($,{className:"flex flex-col items-center gap-2 py-8 text-center",children:[e.jsx(Bt,{className:"h-6 w-6 text-destructive"}),e.jsx("p",{className:"text-sm font-medium text-foreground",children:"Could not load the QuickBooks connection state"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:Ah(i)}),e.jsx(g,{type:"button",variant:"outline",className:"mt-2",onClick:()=>{l()},children:"Try again"})]})}):c?e.jsxs("div",{className:"space-y-3",children:[e.jsx(Y,{className:"h-10 w-full"}),e.jsx(Y,{className:"h-24 w-full"})]}):d?e.jsx(L,{className:"min-w-0 overflow-hidden border-destructive/30",children:e.jsxs($,{className:"flex flex-col items-center gap-2 py-8 text-center",children:[e.jsx(Bt,{className:"h-6 w-6 text-destructive"}),e.jsx("p",{className:"text-sm font-medium text-foreground",children:"Could not load the sync ledger."}),e.jsx("p",{className:"text-sm text-muted-foreground",children:Ah(u)}),e.jsx(g,{type:"button",variant:"outline",className:"mt-2",onClick:()=>{h()},children:"Try again"})]})}):Se?e.jsx(L,{className:"min-w-0 overflow-hidden",children:e.jsxs($,{className:"space-y-2 py-8 text-center",children:[e.jsx("p",{className:"text-sm text-foreground",children:"QuickBooks is not connected for this society."}),e.jsx(je,{to:ue,className:"text-sm font-medium text-brand-navy hover:underline dark:text-sky-300",children:"Go to integrations â"})]})}):e.jsxs(e.Fragment,{children:[ce.length>0&&e.jsxs("div",{className:"flex items-start gap-2 rounded-lg border border-destructive/30 bg-destructive/10 p-3 text-sm text-destructive",children:[e.jsx(Dt,{className:"mt-0.5 h-4 w-4 shrink-0"}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("p",{className:"font-medium",children:["Last run was incomplete â these categories could not be scanned:"," ",ce.map(([Ce,ze],Ze)=>e.jsxs("span",{children:[Ze>0&&", ",e.jsxs("span",{className:"font-mono",children:[Ce," â ",ze]})]},Ce)),"."]}),e.jsx("p",{className:"mt-1",children:"Counts below may be missing records."})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4 lg:grid-cols-4",children:[e.jsx(L,{className:"min-w-0 overflow-hidden",children:e.jsxs($,{className:"space-y-1 py-4",children:[e.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-wider text-muted-foreground",children:"Needs attention"}),e.jsx("p",{className:"text-2xl font-semibold tabular-nums tracking-tight text-foreground",children:ke}),e.jsxs("span",{className:"inline-flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx("span",{className:`h-1.5 w-1.5 shrink-0 rounded-full ${ke===0?"bg-emerald-500":"bg-amber-500"}`}),ke===0?"All clear":"Needs a look"]})]})}),e.jsx(L,{className:"min-w-0 overflow-hidden",children:e.jsxs($,{className:"space-y-1 py-4",children:[e.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-wider text-muted-foreground",children:"Open tie-out flags"}),e.jsx("p",{className:"text-2xl font-semibold tabular-nums tracking-tight text-foreground",children:f?.open_count??"â"}),e.jsx("a",{href:"#tieout",className:"text-xs font-medium text-brand-navy hover:underline dark:text-sky-300",children:"View tie-out â"})]})}),e.jsx(L,{className:"min-w-0 overflow-hidden",children:e.jsxs($,{className:"space-y-1 py-4",children:[e.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-wider text-muted-foreground",children:"Documents in QuickBooks"}),e.jsx("p",{className:"text-2xl font-semibold tabular-nums tracking-tight text-foreground",children:m?.totals?.synced_count??0}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[sn(m?.totals?.posted_amount_cents??0)," posted all-time"]})]})}),e.jsx(L,{className:"min-w-0 overflow-hidden",children:e.jsxs($,{className:"space-y-1 py-4",children:[e.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-wider text-muted-foreground",children:"Next scheduled runs"}),e.jsxs("p",{className:"text-xs text-foreground",children:["Sync ",m?.schedules?.sync??"â"]}
3962),e.jsxs("p",{className:"text-xs text-foreground",children:["Tie-out ",m?.schedules?.tieout??"â"]})]})})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(g,{type:"button",variant:j==="ledger"?"default":"outline",size:"sm",onClick:()=>w("ledger"),children:"Ledger"}),e.jsx(g,{type:"button",variant:j==="activity"?"default":"outline",size:"sm",onClick:()=>w("activity"),children:"Activity"}),e.jsx("span",{className:"flex-1"}),j==="ledger"&&e.jsxs(e.Fragment,{children:[e.jsx(O,{type:"search",value:S,onChange:Ce=>_(Ce.target.value),placeholder:"Search source or referenceâ¦",className:"h-8 w-full max-w-xs sm:w-56","aria-label":"Search ledger"}),e.jsxs(g,{type:"button",variant:"outline",size:"sm",onClick:()=>{t&&As.exportRecordsCsv(t)},disabled:!t,children:[e.jsx(vs,{className:"mr-2 h-4 w-4"}),"Export CSV"]})]})]}),j==="ledger"?e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"flex flex-wrap gap-2",children:mF.map(Ce=>e.jsxs("button",{type:"button",onClick:()=>k(Ce.key),className:`rounded-full border px-3 py-1 text-xs font-medium transition ${v===Ce.key?"border-foreground bg-foreground text-background":"border-border bg-card text-muted-foreground hover:border-brand-navy/40"}`,children:[Ce.label," (",Pe[Ce.key],")"]},Ce.key))}),e.jsx(L,{className:"min-w-0 overflow-hidden",children:e.jsxs($,{className:"p-0",children:[M.length===0?e.jsx("div",{className:"py-12 text-center text-sm text-muted-foreground",children:oe.length===0?"No documents yet â the sync has not posted anything for this society.":"No documents match this filter or search."}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(Pt,{children:[e.jsx(At,{className:"bg-muted/30",children:e.jsxs(Ue,{className:"hover:bg-transparent",children:[e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Type"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Source"}),e.jsx(H,{className:"h-10 text-right text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Amount"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Status"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"QuickBooks ref"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Last event"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Actions"})]})}),e.jsx(Et,{children:M.map(Ce=>{const ze=sF(Ce.status),Ze=eF(Ce),Re=aF(Ce),de=Vd(Ce)?kT(Ce):[];return e.jsxs(Ue,{className:"hover:bg-brand-navy/[0.04] dark:hover:bg-brand-navy/10",children:[e.jsx(G,{className:"whitespace-nowrap align-top text-xs",children:xi(Ce.object_type)}),e.jsx(G,{className:"max-w-[14rem] align-top",children:e.jsx("div",{className:"truncate font-mono text-xs",title:Ce.source_id,children:Ce.source_id})}),e.jsx(G,{className:"whitespace-nowrap align-top text-right text-xs tabular-nums",children:sn(Ce.amount_cents)}),e.jsx(G,{className:"whitespace-nowrap align-top text-xs",children:e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx("span",{className:`h-1.5 w-1.5 shrink-0 rounded-full ${ze.dot}`}),ze.label]})}),e.jsx(G,{className:"max-w-[10rem] align-top",children:Ze?e.jsx("div",{className:"truncate font-mono text-xs font-medium text-brand-navy dark:text-sky-300",title:Ze,children:Ze}):e.jsx("span",{className:"text-xs text-muted-foreground",children:"â"})}),e.jsxs(G,{className:"max-w-[16rem] align-top text-xs",children:[e.jsx("div",{className:"break-words",children:Re.label}),Re.whenRaw&&e.jsx("div",{className:"mt-0.5 text-[11px] text-muted-foreground",children:Eh(Re.whenRaw)})]}),e.jsx(G,{className:"align-top",children:e.jsxs("div",{className:"flex flex-wrap gap-2",children:[de.map(ge=>e.jsx(g,{type:"button",variant:"outline",size:"sm",disabled:z===Ce.id||!_e,title:_e?void 0:cc,onClick:()=>{ae(Ce.id),xe({row:Ce,kind:ge})},children:uF[ge]},ge)),!_e&&de.length>0&&e.jsx("p",{className:"w-full text-xs text-muted-foreground",children:cc})]})})]},Ce.id)})})]})}),I&&e.jsx("p",{className:"border-t px-4 py-2.5 text-[11px] text-muted-foreground",children:"Showing the 50 most recent synced documents."})]})})]}):e.jsx(L,{className:"min-w-0 overflow-hidden",children:e.jsx($,{className:"p-0",children:N.isLoading?e.jsxs("div",{className:"space-y-3 p-4",children:[e.jsx(Y,{className:"h-6 w-full"}),e.jsx(Y,{className:"h-6 w-full"})]}):N.isError?e.jsxs("div",{className:"m-3 flex items-start gap-2 rounded-lg border border-destructive/30 bg-destructive/10 p-3 text-sm text-destructive",children:[e.jsx(Dt,{className:"mt-0.5 h-4 w-4 shrink-0"}),e.jsx("p",{children:"Activity could not be loaded â refresh to retry."})]}):Oe.length===0?e.jsx("div",{className:"py-12 text-center text-sm text-muted-foreground",children:"No QuickBooks activity recorded yet."}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(Pt,{children:[e.jsx(At,{className:"bg-muted/30",children:e.jsxs(Ue,{className:"hover:bg-transparent",children:[e.jsx(H,{className:"h-10 w-6"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground
3962/80",children:"Event"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Detail"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Who"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"When"})]})}),e.jsx(Et,{children:Oe.map(Ce=>e.jsxs(Ue,{className:"hover:bg-transparent",children:[e.jsx(G,{className:"align-top",children:e.jsx("span",{className:`mt-1 inline-block h-2 w-2 rounded-full ${dF[Ce.tone]}`})}),e.jsx(G,{className:"align-top text-xs font-medium",children:Ce.title}),e.jsx(G,{className:"max-w-md whitespace-normal break-words align-top text-xs text-muted-foreground",children:Ce.detail||"â"}),e.jsx(G,{className:"whitespace-nowrap align-top text-xs",children:Ce.who}),e.jsx(G,{className:"whitespace-nowrap align-top text-xs text-muted-foreground",children:Eh(Ce.whenRaw)})]},Ce.id))})]})}),e.jsx("p",{className:"border-t px-4 py-2.5 text-[11px] text-muted-foreground",children:"Filtered to QuickBooks events â the newest 50 actions on this integration."})]})})})]}),t&&n&&e.jsx(HT,{societyId:t,config:n})]}),K&&t&&e.jsx(FT,{row:K.row,kind:K.kind,societyId:t,open:!!K,onSuccess:()=>ee(K.row.id),onOpenChange:Ce=>{Ce||(xe(null),ae(null))}})]})}function gF(t,s){const a=t??[],n=new Set(a.map(i=>i.key)),r=a.map(i=>({key:i.key,builtin:i.builtin,historical:i.snapshot&&!i.live&&!i.builtin,mappedOnly:!1,sources:i.sources??[]}));for(const i of Object.keys(s??{}))n.has(i)||r.push({key:i,builtin:!1,historical:!0,mappedOnly:!0,sources:[]});return r}function fF(t){const s={};for(const[a,n]of Object.entries(t))n.item_id===null&&n.class_id===null||(s[a]={...n.item_id!==null?{item_id:n.item_id}:{},...n.class_id!==null?{class_id:n.class_id}:{}});return s}function yF(t){return{enabled:t.enabled??!1,posting_mode:t.posting_mode??"primary",clearing_account_id:t.clearing_account_id??null,checking_account_id:t.checking_account_id??null,fee_item_id:t.fee_item_id??null,fee_class_id:t.fee_class_id??null,fee_expense_account_id:t.fee_expense_account_id??null,dispute_account_id:t.dispute_account_id??null,discount_item_id:t.discount_item_id??null,discount_class_id:t.discount_class_id??null,discount_account_id:t.discount_account_id??null,default_item_id:t.default_item_id??null,default_class_id:t.default_class_id??null,category_mappings:Object.fromEntries(Object.entries(t.category_mappings??{}).map(([s,a])=>[s,{item_id:a.item_id??null,class_id:a.class_id??null}])),cutover_at:kF(t.cutover_at),cutover_last_acodei_payout_id:t.cutover_last_acodei_payout_id??"",minimum_balance_dollars:bF(t.minimum_balance_cents)}}function bF(t){return t==null?"":(t/100).toFixed(2)}function jF(t){const s=t.trim();if(!s)return null;const a=Number(s);return!Number.isFinite(a)||a<=0?null:Math.round(a*100)}function vF(t){const s=t.trim();if(!s)return!1;const a=Number(s);return!Number.isFinite(a)||a<0}
3962const Ty="America/New_York";function Th(t){const s=new Intl.DateTimeFormat("en-US",{timeZone:Ty,hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"}),a={};for(const r of s.formatToParts(t))a[r.type]=r.value;return(Date.UTC(Number(a.year),Number(a.month)-1,Number(a.day),Number(a.hour),Number(a.minute),Number(a.second))-t.getTime())/6e4}function wF(t){const s=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})/.exec(t);if(!s)return null;const[,a,n,r,i,l]=s,m=Date.UTC(Number(a),Number(n)-1,Number(r),Number(i),Number(l)),c=new Set;for(const u of[-14,-1,0,1,14])c.add(Th(new Date(m+u*36e5)));const d=[];for(const u of c){const h=m-u*6e4;Th(new Date(h))===u&&d.push(h)}return d.length>0?new Date(Math.max(...d)):new Date(m-Math.min(...c)*6e4)}function NF(t){const s=new Intl.DateTimeFormat("en-CA",{timeZone:Ty,hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"}),a={};for(const n of s.formatToParts(t))a[n.type]=n.value;return`${a.year}-${a.month}-${a.day}T${a.hour}:${a.minute}`}function Mc(t){if(!t)return null;const s=wF(t);return s?s.toISOString().replace(/\.\d{3}Z$/,"Z"):null}function kF(t){const s=Mi(t);return s?NF(s):""}function _F(t,s){return{expected_realm_id:s,posting_mode:t.posting_mode,clearing_account_id:t.clearing_account_id,checking_account_id:t.checking_account_id,fee_expense_account_id:t.fee_expense_account_id,dispute_account_id:t.dispute_account_id,cutover_at:Mc(t.cutover_at),cutover_last_acodei_payout_id:t.cutover_last_acodei_payout_id||null,minimum_balance_cents:jF(t.minimum_balance_dollars)}}function SF(t,s){return{expected_realm_id:s,fee_item_id:t.fee_item_id,fee_class_id:t.fee_class_id,discount_item_id:t.discount_item_id,discount_class_id:t.discount_class_id,discount_account_id:t.discount_account_id,default_item_id:t.default_item_id,default_class_id:t.default_class_id}}function CF(t,s){return{expected_realm_id:s,category_mappings:fF(t.category_mappings)}}function ai(t,s){return t?t.filter(a=>a.account_type!==null&&s.includes(a.account_type)):[]}function PF(t,...s){return t?s.every(a=>a===t):!1}function AF(t){const s=t?.response,a=typeof s?.data?.detail=="string"?s.data.detail:"";return a==="realm_changed"?"The QuickBooks company changed since this page loaded â reload and try again.":a==="sync_in_progress"?"A sync is running for this society â try again in a minute.":s?.status===409&&a?a:s?.status===502&&a?`QuickBooks rejected the class (code: ${a})`:"Could not create the class"}function gl({societyId:t,realmId:s,onCreated:a,onRealmChanged:n,compact:r=!1,disabled:i=!1}){const[l,m]=o.useState(!1),[c,d]=o.useState(""),[u,h]=o.useState(null),p=YA(),x=()=>{c.trim()&&(h(null),p.mutate({societyId:t,name:c.trim(),expectedRealmId:s},{onSuccess:N=>{a(N.id),m(!1),d("")},onError:N=>{const j=AF(N);h(j),an(N)&&N.response?.data?.detail==="realm_changed"&&n()}}))},f=()=>{m(!1),d(""),h(null)},b=r?"":"+ Add class";return l?e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(O,{type:"text",placeholder:"Class nameâ¦",value:c,onChange:N=>{d(N.target.value),h(null)},disabled:i||p.isPending,className:"h-8"}),e.jsx(g,{type:"button",size:"sm",onClick:x,disabled:i||!c.trim()||p.isPending,children:p.isPending?e.jsxs(e.Fragment,{children:[e.jsx(He,{className:"mr-1.5 h-3.5 w-3.5 animate-spin"}),"Creatingâ¦"]}):"Create"}),e.jsx(g,{type:"button",variant:"outline",size:"sm",onClick:f,disabled:i||p.isPending,children:"Cancel"})]}),u&&e.jsx("p",{className:"text-sm text-destructive",children:u})]}):r?e.jsx(g,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7",title:"Add class",onClick:()=>m(!0),disabled:i,children:"+"}):e.jsx(g,{type:"button",variant:"ghost",onClick:()=>m(!0),className:"text-sm",disabled:i,children:b})}const EF={membership_dues:"Membership dues",event:"Events (no category)",product:"Products (no category)",donation:"Donations (no category)"},TF={event:"Events",product:"Products",donation:"Donations",dues:"Dues"},FF=[{key:"all",label:"All"},{key:"event",label:"Events"},{key:"product",label:"Products"},{key:"donation",label:"Donations"},{key:"dues",label:"Dues"},{key:"historical",label:"Historical"}];function RF(t,s){return s==="all"?!0:s==="historical"?t.historical:t.sources.includes(s)}const ol="text-[11px] font-semibold uppercase tracking-wider text-muted-foreground
3962/80";function MF({rows:t,mappings:s,onChange:a,items:n,classes:r,classRealmId:i,realmsOk:l,societyId:m,disabled:c,onRealmChanged:d}){const[u,h]=o.useState("all"),[p,x]=o.useState(""),f=o.useMemo(()=>{const b=p.trim().toLowerCase();return t.filter(N=>RF(N,u)&&(b===""||N.key.toLowerCase().includes(b)))},[t,u,p]);return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-sm font-medium text-foreground",children:"Category mappings"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Override the item and class QuickBooks uses for specific events, products, campaigns, or membership dues."})]}),t.length>0?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between",children:[e.jsx("div",{className:"flex flex-wrap gap-1.5",children:FF.map(b=>e.jsx(g,{type:"button",variant:u===b.key?"default":"outline",size:"sm",onClick:()=>h(b.key),children:b.label},b.key))}),e.jsx(O,{value:p,onChange:b=>x(b.target.value),placeholder:"Search categoriesâ¦",className:"sm:max-w-xs"})]}),f.length>0?e.jsx("div",{className:"rounded-lg border",children:e.jsxs(Pt,{children:[e.jsx(At,{children:e.jsxs(Ue,{children:[e.jsx(H,{className:ol,children:"Category"}),e.jsx(H,{className:ol,children:"Type"}),e.jsx(H,{className:ol,children:"Item"}),e.jsx(H,{className:ol,children:"Class"})]})}),e.jsx(Et,{children:f.map(b=>{const N=s[b.key]??{item_id:null,class_id:null};return e.jsxs(Ue,{children:[e.jsx(G,{children:e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"text-sm text-foreground",children:b.builtin?EF[b.key]??b.key:b.key}),b.historical&&e.jsxs("span",{className:"inline-flex items-center gap-1.5 whitespace-nowrap text-xs font-medium text-amber-700 dark:text-amber-400",title:"No longer on any live event, product, or campaign â kept because past sales reference it",children:[e.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-amber-500"}),"Historical"]})]})}),e.jsx(G,{children:b.sources.length>0?e.jsx("div",{className:"flex flex-wrap gap-1",children:b.sources.map(j=>e.jsx("span",{className:"inline-flex items-center rounded-full bg-muted px-2 py-0.5 text-xs text-muted-foreground",children:TF[j]??j},j))}):e.jsx("span",{className:"text-xs text-muted-foreground",children:"â"})}),e.jsx(G,{children:e.jsx(Ss,{value:N.item_id,onChange:j=>a(b.key,{item_id:j}),noneLabel:"Use default",placeholder:"Use default",disabled:c,children:n.map(j=>e.jsx(q,{value:j.id,children:j.name},j.id))})}),e.jsx(G,{children:e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(Ss,{value:N.class_id,onChange:j=>a(b.key,{class_id:j}),noneLabel:"Use default",placeholder:"Use default",disabled:c,children:r.map(j=>e.jsx(q,{value:j.id,children:j.name},j.id))}),i&&l&&e.jsx(gl,{societyId:m,realmId:i,onCreated:j=>a(b.key,{class_id:j}),onRealmChanged:d,compact:!0,disabled:c})]})})]},b.key)})})]})}):e.jsx("p",{className:"rounded-lg border border-dashed p-4 text-sm text-muted-foreground",children:"No categories match this filter or search."})]}):e.jsx("p",{className:"rounded-lg border border-dashed p-4 text-sm text-muted-foreground",children:"No categories found yet â events, products, and campaigns will appear here after your first sync."}),e.jsx("p",{className:"text-xs text-muted-foreground",children:'Rows left on "Use default" fall back to the default item and class above at sync time.'})]})}const DF=[{key:"accounts",label:"Accounts & connection"},{key:"defaults",label:"Default mappings"},{key:"categories",label:"Category mappings"}];function Fh(t){if(an(t)){const s=t.response?.data?.detail;if(typeof s=="string"&&s.trim())return s}return"Something went wrong. Please try again."}function LF(t){return t.connection_status==="connected"?{label:"Connected",dot:"bg-emerald-500"}:t.connection_status==="broken"?{label:t.broken_reason?`Broken (${t.broken_reason})`:"Broken",dot:"bg-amber-500"}:{label:"Disconnected",dot:"bg-muted-foreground/60"}}function cl({feedback:t}){return t?t.kind==="success"?e.jsxs("span",{className:"flex items-center gap-1.5 text-sm text-emerald-700 dark:text-emerald-400",children:[e.jsx(Kt,{className:"h-3.5 w-3.5"}),t.message??"Configuration saved."]}):t.kind==="realm_changed"?e.jsx("p",{className:"text-sm text-destructive",children:"The QuickBooks company changed since this page loaded. Settings reloaded â review and save again."}):t.kind==="sync_in_progress"?e.jsx("p",{className:"text-sm text-destructive",children:"A sync is running for this society â try again in a minute."}):t.kind==="validation"?e.jsx("ul",{className:"list-disc space-y-1 pl-5 text-sm text-destructive",children:t.problems.map((s,a)=>e.jsx("li",{children:s},a))}):e.jsx("p",{className:"text-sm text-destructive",children:t.message}):null}function $F(){const{id:t}=Ds(),s=J(),{data:a,isLoading:n}=Ir(t),{data:r,isError:i,error:l,refetch:m}=Qd(t),c=r?.connected===!0,d=BA(t,c),u=KA(t,c),h=QA(t,c),p=WA(t),x=nl(),f=nl(),b=nl(),N=nl(),[j,w]=o.useState("accounts"),[v,k]=o.useState(null),[S,_]=o.useState(null),[y,C]=o.useState(null),[P,A]=o.useState(null),[E,Q]=o.use
3962State(null),U=o.useRef(null);o.useEffect(()=>{if(!r)return;const de=`${t}:${r.realm_id??""}`;U.current!==de&&(k(yF(r)),U.current=de,_(null),C(null),A(null),Q(null))},[r,t]);const D=o.useRef(!1);o.useEffect(()=>{const de=d.isError||u.isError||h.isError;de&&!D.current?(D.current=!0,s.invalidateQueries({queryKey:["qbo-config",t]})):de||(D.current=!1)},[d.isError,u.isError,h.isError,s,t]);const K=d.data!==void 0&&u.data!==void 0&&h.data!==void 0,xe=PF(r?.realm_id,d.data?.realm_id,u.data?.realm_id,h.data?.realm_id),z=c&&K&&!xe,ae=c&&(d.isError||u.isError||h.isError),ue=o.useRef(!1);o.useEffect(()=>{z&&!ue.current?(ue.current=!0,s.invalidateQueries({queryKey:["qbo-config",t]}),s.invalidateQueries({queryKey:["qbo-accounts",t]}),s.invalidateQueries({queryKey:["qbo-items",t]}),s.invalidateQueries({queryKey:["qbo-classes",t]})):z||(ue.current=!1)},[z,s,t]);const _e=`/platform/societies/${t}/settings?tab=integrations`;if(!t)return null;const ee=r?.connection_status==="broken",se=ee||!xe,le=(de,ge)=>{k(mt=>{if(!mt)return mt;const ye=mt.category_mappings[de]??{item_id:null,class_id:null};return{...mt,category_mappings:{...mt.category_mappings,[de]:{...ye,...ge}}}})},oe=()=>{_({kind:"realm_changed"}),C({kind:"realm_changed"}),A({kind:"realm_changed"}),U.current=null,m(),s.invalidateQueries({queryKey:["qbo-accounts",t]}),s.invalidateQueries({queryKey:["qbo-items",t]}),s.invalidateQueries({queryKey:["qbo-classes",t]})},Pe=(de,ge,mt,ye)=>{mt(null),de.mutate({societyId:t,data:ge},{onSuccess:()=>mt({kind:"success",message:ye}),onError:Ke=>{const ut=an(Ke)?Ke.response?.status:void 0,De=an(Ke)?Ke.response?.data?.detail:void 0;if(ut===409&&De==="realm_changed"){oe();return}if(ut===409&&De==="sync_in_progress"){mt({kind:"sync_in_progress"});return}if(ut===422&&Array.isArray(De)){mt({kind:"validation",problems:De});return}mt({kind:"error",message:Fh(Ke)})}})},M=()=>{!r?.realm_id||!v||Pe(x,_F(v,r.realm_id),_)},I=()=>{!r?.realm_id||!v||Pe(f,SF(v,r.realm_id),C)},R=()=>{!r?.realm_id||!v||Pe(b,CF(v,r.realm_id),A)},X=de=>{r?.realm_id&&Pe(N,{expected_realm_id:r.realm_id,enabled:de},Q,de?"Sync enabled.":"Sync paused.")},Se=r?Mi(r.last_refresh_at):null,ce=r?LF(r):null,ke=!!v&&r?.enabled===!0&&v.posting_mode!==(r.posting_mode??"primary"),ve=se||x.isPending,Ne=se||f.isPending,Qe=se||b.isPending,Oe=ee||N.isPending,Ce=!!v&&vF(v.minimum_balance_dollars),ze=ve||!r?.realm_id||Ce,Ze=Ne||!r?.realm_id,Re=Qe||!r?.realm_id;return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(g,{variant:"ghost",size:"icon",asChild:!0,children:e.jsx(je,{to:_e,"aria-label":"Back to integrations",children:e.jsx(es,{className:"h-4 w-4","aria-hidden":"true"})})}),e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(Qp,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:"QuickBooks configuration"}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:n||!a?"Loading societyâ¦":e.jsxs(e.Fragment,{children:["Connection, defaults, and category mappings for ",e.jsx("strong",{children:a.name})]})})]})]}),i?e.jsx(L,{className:"min-w-0 overflow-hidden border-destructive/30",children:e.jsxs($,{className:"flex flex-col items-center gap-2 py-8 text-center",children:[e.jsx(Bt,{className:"h-6 w-6 text-destructive"}),e.jsx("p",{className:"text-sm font-medium text-foreground",children:"Could not load the QuickBooks configuration"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:Fh(l)}),e.jsx(g,{type:"button",variant:"outline",className:"mt-2",onClick:()=>{m()},children:"Try again"})]})}):!r||!v?e.jsxs("div",{className:"space-y-3",children:[e.jsx(Y,{className:"h-20 w-full"}),e.jsx(Y,{className:"h-64 w-full"})]}):e.jsxs(e.Fragment,{children:[e.jsx(L,{className:"min-w-0 overflow-hidden",children:e.jsxs($,{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"min-w-0 space-y-1",children:[e.jsx("p",{className:"truncate text-sm font-medium text-foreground",children:r.company_name||"QuickBooks company"}),e.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1",children:[r.realm_id&&e.jsx("span",{className:"font-mono text-xs text-muted-foreground",children:r.realm_id}),e.jsxs("span",{className:"inline-flex items-center gap-1.5 whitespace-nowrap",children:[e.jsx("span",{className:`h-1.5 w-1.5 shrink-0 rounded-full ${ce?.dot}`}),e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:ce?.label})]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["Last refresh: ",Se?Se.toLocaleStr
3962ing():"never"]})]})]}),e.jsx(je,{to:`/platform/societies/${t}/quickbooks`,className:"shrink-0 text-sm font-medium text-brand-navy hover:underline dark:text-sky-300",children:"View sync status â"})]}),ee&&e.jsxs("div",{className:"flex items-start gap-2 rounded-md bg-amber-50 p-3 text-sm text-amber-700 dark:bg-amber-950/20 dark:text-amber-300",children:[e.jsx(Dt,{className:"mt-0.5 h-4 w-4 shrink-0"}),"Reconnect from the QuickBooks card on the integrations tab to resume â configuration is preserved."]}),(r.warnings??[]).map(de=>e.jsxs("div",{className:"flex items-start gap-2 rounded-md bg-amber-50 p-3 text-sm text-amber-700 dark:bg-amber-950/20 dark:text-amber-300",children:[e.jsx(Bt,{className:"mt-0.5 h-4 w-4 shrink-0"}),de]},de)),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-4",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(T,{htmlFor:"qbo-sync-enabled",children:"Sync enabled"}),ee&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Sync cannot be toggled while the connection is broken."})]}),e.jsx(ss,{id:"qbo-sync-enabled",checked:r.enabled??!1,onCheckedChange:X,disabled:Oe})]}),e.jsx(cl,{feedback:E}),z&&e.jsxs("p",{className:"flex items-start gap-1.5 rounded-md bg-amber-50 p-2 text-sm text-amber-700 dark:bg-amber-950/20 dark:text-amber-300",children:[e.jsx(Dt,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),"The QuickBooks company changed while this page was open â reloading the pickersâ¦"]}),!z&&ae&&e.jsxs("p",{className:"flex items-start gap-1.5 text-sm text-destructive",children:[e.jsx(Dt,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),"Could not load QuickBooks accounts, items, or classes â the connection may be broken. Reconnect from the QuickBooks card on the integrations tab, or try again."]})]})}),e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:DF.map(de=>e.jsx(g,{type:"button",variant:j===de.key?"default":"outline",size:"sm",onClick:()=>w(de.key),children:de.label},de.key))}),j==="accounts"&&e.jsx(L,{className:"min-w-0 overflow-hidden",children:e.jsxs($,{className:"space-y-6 py-6",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(T,{htmlFor:"qbo-posting-mode",children:"Posting mode"}),e.jsxs(qe,{value:v.posting_mode,onValueChange:de=>k(ge=>ge&&{...ge,posting_mode:de}),disabled:ve,children:[e.jsx(Le,{id:"qbo-posting-mode",className:"w-full sm:w-64",children:e.jsx(Ie,{})}),e.jsxs($e,{children:[e.jsx(q,{value:"primary",children:"Primary"}),e.jsx(q,{value:"fallback",children:"Fallback"})]})]}),ke&&e.jsxs("p",{className:"flex items-start gap-1.5 text-sm text-amber-700 dark:text-amber-300",children:[e.jsx(Dt,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),"Changing the posting mode only affects charges that first sync after the change â already-synced and in-flight records keep their original document shape."]})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(T,{children:"Clearing account"}),e.jsx(Ss,{value:v.clearing_account_id,onChange:de=>k(ge=>ge&&{...ge,clearing_account_id:de}),noneLabel:"None",placeholder:"Select accountâ¦",disabled:ve,children:ai(d.data?.items,["Bank","Other Current Asset"]).map(de=>e.jsx(q,{value:de.id,children:de.name},de.id))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(T,{children:"Checking account"}),e.jsx(Ss,{value:v.checking_account_id,onChange:de=>k(ge=>ge&&{...ge,checking_account_id:de}),noneLabel:"None",placeholder:"Select accountâ¦",disabled:ve,children:ai(d.data?.items,["Bank"]).map(de=>e.jsx(q,{value:de.id,children:de.name},de.id))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(T,{children:"Fee expense account"}),e.jsx(Ss,{value:v.fee_expense_account_id,onChange:de=>k(ge=>ge&&{...ge,fee_expense_account_id:de}),noneLabel:"None",placeholder:"Select accountâ¦",disabled:ve,children:ai(d.data?.items,["Expense","Cost of Goods Sold","Other Expense"]).map(de=>e.jsx(q,{value:de.id,children:de.name},de.id))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(T,{children:"Dispute account"}),e.jsx(Ss,{value:v.dispute_account_id,onChange:de=>k(ge=>ge&&{...ge,dispute_account_id:de}),noneLabel:"None",placeholder:"Select accountâ¦",disabled:ve,children:ai(d.data?.items,["Expense","Other Expense"]).map(de=>
3962e.jsx(q,{value:de.id,children:de.name},de.id))})]})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(T,{htmlFor:"qbo-cutover-at",children:"Cutover"}),e.jsx(O,{id:"qbo-cutover-at",type:"datetime-local",value:v.cutover_at,onChange:de=>k(ge=>ge&&{...ge,cutover_at:de.target.value}),disabled:ve}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Eastern time â the exact moment the previous sync service was (or will be) disabled"}),v.cutover_at&&Mc(v.cutover_at)&&e.jsxs("p",{className:"font-mono text-xs text-muted-foreground",children:["= ",Mc(v.cutover_at)]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(T,{htmlFor:"qbo-cutover-payout",children:"Last Acodei payout ID"}),e.jsx(O,{id:"qbo-cutover-payout",value:v.cutover_last_acodei_payout_id,onChange:de=>k(ge=>ge&&{...ge,cutover_last_acodei_payout_id:de.target.value}),placeholder:"po_...",disabled:ve})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(T,{htmlFor:"qbo-minimum-balance",children:"Stripe minimum balance ($)"}),e.jsx(O,{id:"qbo-minimum-balance",type:"number",min:"0",step:"0.01",value:v.minimum_balance_dollars,onChange:de=>k(ge=>ge&&{...ge,minimum_balance_dollars:de.target.value}),placeholder:"25.00",disabled:ve}),Ce?e.jsx("p",{className:"text-xs text-destructive",children:"Enter a positive dollar amount, or leave blank for none."}):e.jsx("p",{className:"text-xs text-muted-foreground",children:"Optional â match the minimum balance set in the Stripe dashboard. Monthly tie-outs then skip the matching payout hold/release entries instead of flagging them for review."})]})]}),e.jsx("div",{className:"space-y-2 border-t pt-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(g,{type:"button",onClick:M,disabled:ze,children:x.isPending?"Savingâ¦":"Save"}),e.jsx(cl,{feedback:S})]})})]})}),j==="defaults"&&e.jsx(L,{className:"min-w-0 overflow-hidden",children:e.jsxs($,{className:"space-y-6 py-6",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2",children:[v.posting_mode==="primary"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(T,{children:"Fee item"}),e.jsx(Ss,{value:v.fee_item_id,onChange:de=>k(ge=>ge&&{...ge,fee_item_id:de}),noneLabel:"None",placeholder:"Select itemâ¦",disabled:Ne,children:(u.data?.items??[]).map(de=>e.jsx(q,{value:de.id,children:de.name},de.id))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(T,{children:"Discount item"}),e.jsx(Ss,{value:v.discount_item_id,onChange:de=>k(ge=>ge&&{...ge,discount_item_id:de}),noneLabel:"None",placeholder:"Select itemâ¦",disabled:Ne,children:(u.data?.items??[]).map(de=>e.jsx(q,{value:de.id,children:de.name},de.id))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(T,{children:"Default item"}),e.jsx(Ss,{value:v.default_item_id,onChange:de=>k(ge=>ge&&{...ge,default_item_id:de}),noneLabel:"None",placeholder:"Select itemâ¦",disabled:Ne,children:(u.data?.items??[]).map(de=>e.jsx(q,{value:de.id,children:de.name},de.id))})]})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(T,{children:"Fee class"}),e.jsx(Ss,{value:v.fee_class_id,onChange:de=>k(ge=>ge&&{...ge,fee_class_id:de}),noneLabel:"None",placeholder:"Select classâ¦",disabled:Ne,children:(h.data?.items??[]).map(de=>e.jsx(q,{value:de.id,children:de.name},de.id))}),h.data?.realm_id&&xe&&e.jsx(gl,{societyId:t,realmId:h.data.realm_id,onCreated:de=>k(ge=>ge&&{...ge,fee_class_id:de}),onRealmChanged:oe,disabled:Ne})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(T,{children:"Discount class"}),e.jsx(Ss,{value:v.discount_class_id,onChange:de=>k(ge=>ge&&{...ge,discount_class_id:de}),noneLabel:"None",placeholder:"Select classâ¦",disabled:Ne,children:(h.data?.items??[]).map(de=>e.jsx(q,{value:de.id,children:de.name},de.id))}),h.data?.realm_id&&xe&&e.jsx(gl,{societyId:t,realmId:h.data.realm_id,onCreated:de=>k(ge=>ge&&{...ge,discount_class_id:de}),onRealmChanged:oe,disabled:Ne})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(T,{children:"Default class"}),e.jsx(Ss,{value:v.default_class_id,onChange:de=>k(ge=>ge&&{...ge,default_class_id:de}),noneLabel:"None",placeholder:"Select classâ¦",disabled:Ne,children:(h.data?.items??[]).map(de=>
3962e.jsx(q,{value:de.id,children:de.name},de.id))}),h.data?.realm_id&&xe&&e.jsx(gl,{societyId:t,realmId:h.data.realm_id,onCreated:de=>k(ge=>ge&&{...ge,default_class_id:de}),onRealmChanged:oe,disabled:Ne})]}),v.posting_mode==="fallback"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(T,{children:"Discount account"}),e.jsx(Ss,{value:v.discount_account_id,onChange:de=>k(ge=>ge&&{...ge,discount_account_id:de}),noneLabel:"None",placeholder:"Select accountâ¦",disabled:Ne,children:ai(d.data?.items,["Income","Other Income"]).map(de=>e.jsx(q,{value:de.id,children:de.name},de.id))})]})]}),e.jsx("div",{className:"space-y-2 border-t pt-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(g,{type:"button",onClick:I,disabled:Ze,children:f.isPending?"Savingâ¦":"Save"}),e.jsx(cl,{feedback:y})]})})]})}),j==="categories"&&e.jsx(L,{className:"min-w-0 overflow-hidden",children:e.jsxs($,{className:"space-y-6 py-6",children:[e.jsx(MF,{rows:gF(p.data?.categories,v.category_mappings),mappings:v.category_mappings,onChange:le,items:u.data?.items??[],classes:h.data?.items??[],classRealmId:h.data?.realm_id,realmsOk:xe,societyId:t,disabled:Qe,onRealmChanged:oe}),e.jsx("div",{className:"space-y-2 border-t pt-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(g,{type:"button",onClick:R,disabled:Re,children:b.isPending?"Savingâ¦":"Save"}),e.jsx(cl,{feedback:P})]})})]})})]})]})}const Rh={expired:"This link has expired. Ask your administrator to send a new one.",used:"This link has already been used. Sign in, or ask your administrator for a new link.",revoked:"This link is no longer valid. Ask your administrator for a new one.",invalid:"This link isnât valid. Check that you used the whole link from the email."};function qF(t){return t.length<8?"Use at least 8 characters.":/[A-Z]/.test(t)?/[a-z]/.test(t)?/\d/.test(t)?null:"Include a number.":"Include a lowercase letter.":"Include an uppercase letter."}function IF(){const[t]=o.useState(()=>new URLSearchParams(window.location.search).get("token")??"");return o.useEffect(()=>{window.location.search.includes("token=")&&window.history.replaceState(window.history.state,"",window.location.pathname)},[]),t}function OF(){const t=IF(),{user:s}=V(),a=re({queryKey:["account-link",t],queryFn:()=>Nn.inspectLink(t),enabled:!!t,retry:!1,staleTime:1/0}),[n,r]=o.useState(""),[i,l]=o.useState(""),[m,c]=o.useState(null),[d,u]=o.useState(!1),[h,p]=o.useState(null),x=a.data,f=x?.purpose==="invite",b=async j=>{j.preventDefault();const w=qF(n);if(w)return c(w);if(n!==i)return c("The two passwords donât match.");c(null),u(!0);try{const v=await Nn.completeLink(t,n);s&&await Nn.endSessionQuietly(),p(v)}catch(v){c(Xn(v,"Your password couldnât be set. Please try again."))}finally{u(!1)}};let N;return t?a.isPending?N=e.jsx("p",{className:"text-sm text-muted-foreground",children:"Checking your linkâ¦"}):a.isError||!x?N=e.jsxs("div",{className:"space-y-3 text-sm",children:[e.jsx("p",{className:"text-muted-foreground",children:"Your link couldnât be checked right now."}),e.jsx(g,{variant:"outline",onClick:()=>{a.refetch()},children:"Try again"})]}):h?N=e.jsxs("div",{className:"space-y-4 text-sm",children:[e.jsxs("p",{role:"status",children:[h.purpose==="invite"?"Your account is ready.":"Your password has been changed, your other sessions have been signed out, and this accountâs passkeys were removed."," ","Sign in with ",h.email," and your new password."]}),e.jsx(g,{asChild:!0,className:"w-full",children:e.jsx("a",{href:"/login",children:"Sign in"})})]}):x.state!=="valid"?N=e.jsxs("div",{className:"space-y-4 text-sm",children:[e.jsx("p",{role:"alert",children:Rh[x.state]}),e.jsx(g,{asChild:!0,variant:"outline",className:"w-full",children:e.jsx(je,{to:"/login",children:"Go to sign in"})})]}):N=e.jsxs("form",{onSubmit:j=>{b(j)},className:"space-y-4",noValidate:!0,children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:f?e.jsxs(e.Fragment,{children:[x.first_name?`Hi ${x.first_name}. `:"","Youâve been invited as"," ",e.jsx("strong",{className:"text-foreground",children:x.role_label}
3962),x.society_name?e.jsxs(e.Fragment,{children:[" ","for ",e.jsx("strong",{className:"text-foreground",children:x.society_name})]}):null,". Choose a password for ",x.email,"."]}):e.jsxs(e.Fragment,{children:["Choose a new password for ",x.email,". Your other sessions will be signed out, and this accountâs passkeys removed (you can add one again after signing in)."]})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"link-password",children:"New password"}),e.jsx(O,{id:"link-password",type:"password",autoComplete:"new-password",value:n,onChange:j=>r(j.target.value),"aria-describedby":"link-password-help"}),e.jsx("p",{id:"link-password-help",className:"text-xs text-muted-foreground",children:"At least 8 characters, with uppercase and lowercase letters and a number."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(T,{htmlFor:"link-confirm",children:"Confirm password"}),e.jsx(O,{id:"link-confirm",type:"password",autoComplete:"new-password",value:i,onChange:j=>l(j.target.value)})]}),m&&e.jsx("p",{role:"alert",className:"text-sm text-destructive",children:m}),e.jsx(g,{type:"submit",className:"w-full",disabled:d,children:d?"Savingâ¦":f?"Set up my account":"Set new password"})]}):N=e.jsx("p",{className:"text-sm text-muted-foreground",children:Rh.invalid}),e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-muted/30 p-4",children:e.jsxs(L,{className:"w-full max-w-md",children:[e.jsxs(ne,{className:"space-y-3",children:[e.jsx("img",{src:pn,alt:"Korevera",className:"h-8 w-auto self-start"}),e.jsx(ie,{children:x?.purpose==="reset"?"Reset your password":"Set up your account"}),e.jsx(Ci,{children:"Korevera administration"})]}),e.jsx($,{children:N})]})})}const UF=50,dc="__all__",Dc="__notable__",zF=[{value:Dc,label:"Notable (routine hidden)"},{value:"changes",label:"Record changes"},{value:"money",label:"Payments, refunds and disputes"},{value:"problems",label:"Failures"},{value:"sign_ins",label:"Sign-ins"},{value:"all",label:"Everything"}],BF=new Set(["changes","money","problems","sign_ins","all"]);function KF(t){return t.actor_kind==="user"?t.actor_name??t.actor_email??"A deleted user":t.actor_kind==="member"?"A member":"No user recorded"}function QF(){const[t,s]=ws(),a=_r.test(t.get("society")??"")?t.get("society"):void 0,n=t.get("category"),r=BF.has(n??"")?n:void 0,i=Sm(t.get("from")??"")?t.get("from"):"",l=Sm(t.get("to")??"")?t.get("to"):"",m=Number(t.get("page")??"1"),c=Number.isSafeInteger(m)&&m>0?m:1,d=qr().data??[],u=b=>{const N=new URLSearchParams(t);for(const[j,w]of Object.entries(b))w?N.set(j,w):N.delete(j);"page"in b||N.delete("page"),s(N,{replace:!0})},h={society_id:a,category:r,date_from:i||void 0,date_to:l||void 0,page:c,size:UF},p=Ms(re({queryKey:["platform","activity",h],queryFn:()=>bi.listActivity(h),placeholderData:sa,staleTime:0,refetchOnMount:"always"}),JSON.stringify(h)),x=p.data,f=!!(a||r||i||l);return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(Bc,{className:"h-5 w-5","aria-hidden":"true"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:"Activity"}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"Audited events across every society, newest first"})]})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(T,{htmlFor:"activity-society",children:"Society"}),e.jsxs(qe,{value:a??dc,onValueChange:b=>u({society:b===dc?void 0:b}),children:[e.jsx(Le,{id:"activity-society",children:e.jsx(Ie,{})}),e.jsxs($e,{children:[e.jsx(q,{value:dc,children:"All societies"}),d.map(b=>e.jsx(q,{value:b.id,children:b.name},b.id))]})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(T,{htmlFor:"activity-category",children:"Type"}),e.jsxs(qe,{value:r??Dc,onValueChange:b=>u({category:b===Dc?void 0:b}),children:[e.jsx(Le,{id:"activity-category",children:e.jsx(Ie,{})}),e.jsx($e,{children:zF.map(b=>e.jsx(q,{value:b.value,children:b.label},b.value))})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(T,{htmlFor:"activity-from",children:"From (UTC)"}),e.jsx(O,{id:"activity-from",type:"date",value:i,max:l||void 0,onChange:b=>u({from:b.target.value||void 0})})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(T,{htmlFor:"activity-to",children:"To (UTC)"}),e.jsx(O,{id:"activity-to",type:"date",value:l,min:i||void 0,onChange:b=>u({to:b.target.value||void 0})})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Shows what is audited. Some changes arenât recorded yet (for example society settings, feature switches and platform users), and older entries are archived after a year."}),e.jsx(Ma,{view:p,what:"activity"}),e.jsx("div",{className:"rounded-lg border","aria-busy":p.updating,children:p.state==="loading"?e.jsx("div",{className:"space-y-2 p-4",children:[1,2,3,4,5].map(b=>e.jsx(Y,{className:"h-10 w-full"},b))}):p.state==="offline"?e.jsx(Wa,{title:"Activity canât be loaded right now."}):p.state==="failed"||!x?e.jsx(ja,{title:"Activity couldnât be loaded.",error:p.error,onRetry:p.retry,isRetrying:p.retrying}):x.items.length===0&&x.total>0&&!p.updating?e.jsx(tn,{title:"This page is past the end of the list.",action:e.jsx(g,{variant:"outline",onClick:()=>u({page:void 0}),children:"Go to the first page"})}):x.items.length===0&&!p.updating?e.jsx(tn,{title:f?"Nothing matches these filters.":"No activity recorded yet.",action:f?e.jsx(g,{variant:"outline",onClick:()=>s({},{replace:!0}),children:"Clear filters"}):void 0}):e.jsx("ul",{className:"divide-y",children:x.items.map(b=>e.jsxs("li",{className:"px-4 py-3 text-sm",children:[e.jsxs("p",{className:"break-words",children:[b.description,b.summarized&&b.society_id&&b.society_n
3962ame&&e.jsxs(e.Fragment,{children:[" ",e.jsx(je,{to:`/audit?society=${b.society_id}`,className:"text-xs text-muted-foreground underline underline-offset-2",children:"Details in the societyâs audit log"})]})]}),e.jsxs("p",{className:"mt-0.5 text-xs text-muted-foreground",children:[b.society_id&&!b.society_name?e.jsx("span",{className:"font-medium text-foreground",children:"Deleted society"}):b.society_id?e.jsx(je,{to:`/platform/societies/${b.society_id}`,className:"font-medium text-foreground hover:underline",children:b.society_name}):e.jsx("span",{className:"font-medium text-foreground",children:"Platform"})," ","· ",KF(b)," · ",e.jsxs("time",{dateTime:b.created_at,children:[_d(b.created_at,!0)," UTC"]})]})]},b.id))})}),x&&(x.pages>1||x.total_capped)&&e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("p",{className:"text-muted-foreground",children:["Page ",x.page," of ",x.pages,x.total_capped?"+":""," · ",x.total.toLocaleString(),x.total_capped?"+":""," events"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(g,{variant:"outline",size:"sm",disabled:c<=1||p.updating,onClick:()=>u({page:String(c-1)}),children:[e.jsx(Gs,{className:"mr-1 h-4 w-4","aria-hidden":"true"}),"Newer"]}),e.jsxs(g,{variant:"outline",size:"sm",disabled:p.updating||!x.has_more,onClick:()=>u({page:String(c+1)}),children:["Older",e.jsx(ts,{className:"ml-1 h-4 w-4","aria-hidden":"true"})]})]})]})]})}const WF={super_admin:{label:Ea.super_admin,dot:"bg-red-500"},society_admin:{label:Ea.society_admin,dot:"bg-muted-foreground/60"},society_staff:{label:Ea.society_staff,dot:"bg-muted-foreground/60"}};function mc(t){return Ni(t)??(t?.message||"An error occurred")}const uc="__all__";function VF({user:t}){return t.society_id?t.society_deleted?e.jsx("span",{className:"text-muted-foreground",children:"Deleted society"}):t.society_name??"â":"â"}function GF(){const t=o.useId(),s=o.useId(),{page:a,setPage:n,search:r,setSearch:i,appliedSearch:l,clampPage:m}=pf(),[c,d]=o.useState("all"),[u,h]=ws(),p=u.get("society"),x=u.get("add")==="society_admin"&&!!p,[f,b]=o.useState(x),N=R=>{if(b(R),!R&&u.has("add")){const X=new URLSearchParams(u);X.delete("add"),h(X,{replace:!0})}},[j,w]=o.useState(null),[v,k]=o.useState(null),[S,_]=o.useState(""),y=o.useMemo(()=>({page:a,size:20,query:l||void 0,role:c!=="all"?c:void 0,society_id:p??void 0}),[a,l,c,p]),C=Ms(re({queryKey:["users","platform",y],queryFn:()=>Pa.list(y),placeholderData:sa}),JSON.stringify(y)),P=C.data,A=C.updating,E=Ms(qr()),Q=E.data,U=o.useMemo(()=>{const R=new Map;if(Q)for(const X of Q)R.set(X.id,X.name);return R},[Q]),D=Ir(p&&!U.has(p)?p:void 0).data,K=(p&&U.get(p))??D?.name??"this society",xe=J(),z=Hx(),ae=W({mutationFn:({id:R,data:X})=>Pa.update(R,X),onSuccess:()=>xe.invalidateQueries({queryKey:["users"]})}),ue=W({mutationFn:R=>Pa.delete(R),onSuccess:()=>{xe.invalidateQueries({queryKey:["users"]}),k(null)}}),_e=async R=>{try{_(""),await z.mutateAsync(R),N(!1)}catch(X){_(mc(X))}},ee=async(R,X)=>{try{_(""),await ae.mutateAsync({id:R,data:X}),w(null)}catch(Se){_(mc(Se))}},se=async()=>{if(v)try{_(""),await ue.mutateAsync(v.id)}catch(R){_(mc(R))}},le=!!l||c!=="all"||!!p,oe=C.state==="failed",Pe=C.state==="offline",M=C.state==="ready"&&!A&&!!P&&P.items.length===0;C.state==="ready"&&!A&&P&&m(P.pages);const I=()=>{i(""),d("all"),n(1),p&&h({},{replace:!0})};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(Lt,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:"People & access"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Platform and society administrators, and staff, across all societies"})]})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:e.jsxs(g,{onClick:()=>N(!0),children:[e.jsx(Rt,{className:"mr-2 h-4 w-4"}),"Invite user"]})})]}),p&&e.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 rounded-lg border bg-muted/30 px-4 py-2 text-sm",children:[e.jsxs("span",{children:["Showing users of ",e.jsx("span",{className:"font-medium",children:K})]}),e.jsx(je,{to:`/platform/societies/${p}`,className:"font-medium text-primary underline-offset-2 hover:underline",children:"Back to the society"}),e.jsx("button",{type:"button",onClick:()=>{h({},{replace:!0}),n(1)},className:"font-medium text-primary underline-offset-2 hover:underline",children:"Show all users"})]}),e.jsxs("div",{className:"flex flex-col gap-3 lg:flex-row lg:items-end",children:[e.jsx("div",{className:"min-w-0 flex-1",children:e.jsx(df,{search:r,onSearchChange:i,role:c,onRoleChange:R=>{d(R),n(1)}})}),e.jsxs("div",{className:"w-full lg:w-64",children:[e.jsx(T,{id:t,htmlFor:s,className:"sr-only",children:"Society"}),e.jsxs(qe,{value:p??uc,onValueChange:R=>{const X=new URLSearchParams(u);R===uc?X.delete("society"):X.set("society",R),X.delete("add"),h(X,{replace:!0}),n(1)},children:[e.jsx(Le,{id:s,"aria-labelledby":`${t} ${s}`,children:e.jsx(Ie,{})}),e.jsxs($e,{children:[e.jsx(q,{value:uc,children:"All societies"}),(Q??[]).map(R=>e.jsx(q,{value:R.id,children:R.name},R.id))]})]})]})]}),e.jsx(Ma,{view:C,what:"users"}),(E.state==="failed"||E.state==="offline")&&e.jsxs("div",{role:"alert",className:"flex flex-col gap-2 rounded-lg border border-amber-500/40 bg-amber-50 px-4 py-3 text-sm text-amber-900 dark:bg-amber-950/30 dark:text-amber-200 sm:flex-row sm:items-center sm:justify-between",children:[e.jsx("p",{children:"Societies couldnât be loaded, so society names and s
3962ociety choices for new users arenât available right now."}),E.state==="failed"&&e.jsx(g,{size:"sm",variant:"outline",onClick:E.retry,disabled:E.retrying,children:E.retrying?"Trying againâ¦":"Try again"})]}),A&&e.jsx("p",{role:"status",className:"text-sm text-muted-foreground",children:"Updating resultsâ¦"}),e.jsx(L,{className:"min-w-0 overflow-hidden",children:e.jsx($,{className:"p-0",children:Pe?e.jsx(Wa,{title:"Users canât be loaded right now."}):oe?e.jsx(ja,{title:"Users couldnât be loaded.",error:C.error,onRetry:C.retry,isRetrying:C.retrying,children:a>1&&e.jsx(g,{variant:"ghost",onClick:()=>n(1),children:"Back to the first page"})}):C.state==="loading"||A&&!P?.items?.length?e.jsx("div",{className:"space-y-3 p-6",children:Array.from({length:5}).map((R,X)=>e.jsx(Y,{className:"h-12 w-full"},X))}):M?p&&!l&&c==="all"?e.jsx(tn,{title:`No administrators or staff for ${K} yet.`,action:e.jsxs("div",{className:"flex flex-wrap justify-center gap-2",children:[e.jsxs(g,{onClick:()=>N(!0),children:[e.jsx(Rt,{className:"mr-2 h-4 w-4"}),"Invite user"]}),e.jsx(g,{variant:"outline",onClick:I,children:"Show all users"})]})}):le?e.jsx(tn,{title:"No users match your filters.",action:e.jsx(g,{variant:"outline",onClick:I,children:"Clear filters"})}):e.jsx(tn,{title:"No administrators yet.",description:"Add a platform or society administrator to get started.",action:e.jsxs(g,{onClick:()=>N(!0),children:[e.jsx(Rt,{className:"mr-2 h-4 w-4"}),"Invite user"]})}):e.jsx("div",{"aria-busy":A,inert:A,className:A?"pointer-events-none opacity-60 transition-opacity":void 0,children:e.jsxs(Pt,{children:[e.jsx(At,{className:"bg-muted/30",children:e.jsxs(Ue,{className:"hover:bg-transparent",children:[e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Name"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Email"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Role"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Society"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Status"}),e.jsx(H,{className:"h-10 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80",children:"Last login"}),e.jsx(H,{className:"h-10 w-[120px] text-[11px] font-semibold uppercase tracking-wider text-muted-foreground/80"})]})}),e.jsx(Et,{children:(P?.items||[]).map(R=>{const X=WF[R.role]||{label:R.role,dot:"bg-muted-foreground/60"};return e.jsxs(Ue,{className:"hover:bg-brand-navy/[0.04] dark:hover:bg-brand-navy/10",children:[e.jsxs(G,{className:"font-medium",children:[R.first_name," ",R.last_name]}),e.jsx(G,{children:R.email}),e.jsx(G,{children:e.jsxs("span",{className:"inline-flex items-center gap-1.5 whitespace-nowrap",children:[e.jsx("span",{className:`h-1.5 w-1.5 shrink-0 rounded-full ${X.dot}`}),e.jsx("span",{className:"text-xs font-medium",children:X.label})]})}),e.jsx(G,{children:e.jsx(VF,{user:R})}),e.jsx(G,{children:e.jsx(cf,{user:R})}),e.jsx(G,{children:R.last_login_at?Be(Ct(R.last_login_at),"MMM d, yyyy h:mm a"):"â"}),e.jsx(G,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(g,{variant:"ghost",size:"icon",className:"h-7 w-7",title:"Edit","aria-label":"Edit user",onClick:()=>w(R),children:e.jsx(Hs,{className:"h-4 w-4"})}),(R.invitation||R.is_active)&&e.jsxs(Ws,{children:[e.jsx(Vs,{asChild:!0,children:e.jsx(g,{variant:"ghost",size:"icon",className:"h-7 w-7",title:"Access","aria-label":`Access for ${R.first_name} ${R.last_name}`,children:e.jsx(An,{className:"h-4 w-4","aria-hidden":"true"})})}),e.jsx($s,{align:"end",children:e.jsx(of,{user:R})})]}),e.jsx(g,{variant:"ghost",size:"icon",className:"h-7 w-7 text-destructive hover:text-destructive",title:"Delete","aria-label":"Delete user",onClick:()=>k(R),children:e.jsx(Ft,{className:"h-4 w-4"})})]})})]},R.id)})})]})})})}),P&&!Pe&&!oe&&P.pages>1&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:!A&&e.jsxs(e.Fragment,{children:["Showing ",(a-1)*20+1," to ",Math.min(a*20,P.total)," of ",P.total," ","users"]})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(g,{variant:"outline",size:"sm",onClick:()=>n(a-1),disabled:a===1||A,children:[e.jsx(Gs,{className:"h-4 w-4"}),"Previous"]}),e.jsxs("span",{className:"text-sm",children:["Page ",a," of ",P.pages]}),e.jsxs(g,{variant:"outline",size:"sm",onClick:()=>n(a+1),disabled:a===P.pages||A,children:["Next",e.jsx(ts,{className:"h-4 w-4"})]})]})]}),e.jsx(mf,{open:f,onOpenChange:R=>{N(R),R||_("")},onSubmit:_e,isPending:z.isPending,error:S,mode:"platform",societies:Q??[],initial:p?{role:"society_admin",society_id:p}:void 0},p??"all"),e.jsx(uf,{user:j,open:!!j,onOpenChange:R=>{R||(w(null),_(""))},onSubmit:ee,isPending:ae.isPending,error:S,mode:"platform",societies:Q??[]}),e.jsx(Fe,{open:!!v,onOpenChange:R=>{R||(k(null),_(""))},children:e.jsxs(Te,{children:[e.jsxs(Ae,{children:[e.jsx(Ee,{children:"Delete user"}),e.jsxs(tt,{children:["Are you sure you want to delete ",v?.first_name," ",v?.last_name,"
3962(",v?.email,")? This will deactivate their account."]})]}),S&&e.jsx("p",{className:"text-sm text-destructive",children:S}),e.jsxs(Ge,{children:[e.jsx(g,{variant:"outline",onClick:()=>k(null),disabled:ue.isPending,children:"Cancel"}),e.jsx(g,{variant:"destructive",onClick:se,disabled:ue.isPending,children:ue.isPending?"Deletingâ¦":"Delete user"})]})]})})]})}const Fy={list:async t=>(await F.get("/platform/feedback",{params:t})).data,triage:async(t,s)=>(await F.patch(`/platform/feedback/${t}`,s)).data},YF=25,xr="__all__",hc="__none__",Ry=[{value:"open",label:"Open"},{value:"new",label:"New"},{value:"reviewed",label:"Reviewed"},{value:"resolved",label:"Resolved"},{value:"all",label:"All"}],HF=new Set(Ry.map(t=>t.value)),Lc={new:"New",reviewed:"Reviewed",resolved:"Resolved"},JF={new:"Reopened",reviewed:"Reviewed",resolved:"Resolved"},ZF={new:"bg-sky-500",reviewed:"bg-amber-500",resolved:"bg-emerald-500"};function XF(){const[t,s]=ws(),a=t.get("status")??"open",n=HF.has(a)?a:"open",r=_r.test(t.get("society")??"")?t.get("society"):void 0,i=t.get("owner"),l=i==="me"||i==="unassigned"?i:void 0,m=Number(t.get("page")??"1"),c=Number.isSafeInteger(m)&&m>0?m:1,d=(t.get("q")??"").slice(0,200),[u,h]=o.useState(d),p=hf(u),[x,f]=o.useState(d);d!==x&&(f(d),h(d)),o.useEffect(()=>{p===x||p!==u.trim()||s(y=>{const C=new URLSearchParams(y);return p?C.set("q",p):C.delete("q"),C.delete("page"),C},{replace:!0})},[p,u,x,s]);const b=qr().data??[],N=y=>{const C=new URLSearchParams(t);for(const[P,A]of Object.entries(y))A?C.set(P,A):C.delete(P);"page"in y||C.delete("page"),s(C,{replace:!0})},j={status:n,society_id:r,q:d||void 0,owner:l,page:c,size:YF},w=Ms(re({queryKey:["platform-feedback",j],queryFn:()=>Fy.list(j),placeholderData:sa,staleTime:0,refetchOnMount:"always"}),JSON.stringify(j)),v=w.data,k=!!(r||d||l),S=re({queryKey:["users",{role:"super_admin",size:100}],queryFn:()=>Pa.list({role:"super_admin",size:100}),staleTime:5*6e4}),_=S.data?.items.filter(y=>y.is_active)??[];return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(rj,{className:"h-5 w-5","aria-hidden":"true"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:"Portal feedback"}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"Review, assign and resolve what members send from the portal. Members arenât notified of any change here."})]})]}),e.jsx("div",{role:"group","aria-label":"Status",className:"flex flex-wrap gap-1 rounded-lg bg-muted/60 p-1",children:Ry.map(y=>{const C=v&&(y.value==="open"?v.counts.new+v.counts.reviewed:y.value==="all"?v.counts.new+v.counts.reviewed+v.counts.resolved:v.counts[y.value]);return e.jsxs("button",{type:"button","aria-pressed":n===y.value,"aria-label":C===void 0?y.label:`${y.label} (${C})`,onClick:()=>N({status:y.value==="open"?void 0:y.value}),className:me("rounded-md px-3 py-1.5 text-sm font-medium",n===y.value?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:[y.label,C!==void 0&&e.jsxs("span",{className:"ml-1 text-xs",children:[" (",C,")"]})]},y.value)})}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(T,{htmlFor:"feedback-search",children:"Search"}),e.jsxs("div",{className:"relative",children:[e.jsx(ya,{className:"pointer-events-none absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground","aria-hidden":"true"}),e.jsx(O,{id:"feedback-search",value:u,onChange:y=>h(y.target.value),placeholder:"Text, member, or page",maxLength:200,className:"pl-8"})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(T,{htmlFor:"feedback-society",children:"Society"}),e.jsxs(qe,{value:r??xr,onValueChange:y=>N({society:y===xr?void 0:y}),children:[e.jsx(Le,{id:"feedback-society",children:e.jsx(Ie,{})}),e.jsxs($e,{children:[e.jsx(q,{value:xr,children:"All societies"}),b.map(y=>e.jsx(q,{value:y.id,children:y.name},y.id))]})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(T,{htmlFor:"feedback-owner",children:"Owner"}),e.jsxs(qe,{value:l??xr,onValueChange:y=>N({owner:y===xr?void 0:y}),children:[e.jsx(Le,{id:"feedback-owner",children:e.jsx(Ie,{})}),e.jsxs($e,{children:[e.jsx(q,{value:xr,children:"Anyone"}),e.jsx(q,{value:"me",children:"Assigned to me"}),e.jsx(q,{value:"unassigned",children:"Unassigned"})]})]})]})]}),e.jsx(Ma,{view:w,what:"feedback"}),S.isError&&e.jsxs("p",{role:"alert",className:"text-sm text-muted-foreground",children:["The list of platform admins couldnât be loaded, so feedback can only be assigned to you for now."," ",e.jsx("button",{type:"button",onClick:()=>{S.refetch()},className:"font-medium text-foreground underline underline-offset-2",children:"Try again"})]}),e.jsx("div",{"aria-busy":w.updating,children:w.state==="loading"?e.jsxs("div",{className:"space-y-3",children:[e.jsx(Y,{className:"h-28 w-full"}),e.jsx(Y,{className:"h-28 w-full"})]}):w.state==="offline"?e.jsx(L,{children:e.jsx(Wa,{title:"Feedback canât be loaded right now."})}):w.state==="failed"||!v?e.jsx(L,{children:e.jsx(ja,{title:"Feedback couldnât be loaded.",error:w.error,onRetry:w.retry,isRetrying:w.retrying})}):v.items.length===0&&v.total>0&&!w.updating?e.jsx(L,{children:e.jsx(tn,{title:"This page is past the end of the list.",action:e.jsx(g,{variant:"outline",onClick:()=>N({page:void 0}),children:"Go to the first page"})})}):v.items.length===0&&!w.updating?e.jsx(L,{children:e.jsx(tn,{title:k?"No feedback matches these filters.":n==="open"?"Nothing open. New feedback from members will appear here.":`No ${n==="all"?"":Lc[n].toLowerCase()+" "}feedback.`,description:!k&&n==="open"&&v.counts.resolved>0?`${v.counts.resolved} resolved.`:void 0,action:k?e.jsx(g,{variant:"outline",onClick:()=>{h(""),N({society:void 0,q:void 0,owner:void 0})},children:"Clear filters"}):void 0})}):e.jsx("ul",{className:"space-y-3",children:v.items.map(y=>e.jsx(eR,{item:y,adminOptions:_},y.id))})}),v&&v.pages>1&&e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("p",{className:"text-muted-foreground",children:["Page ",v.page," of ",v.pages," · ",v.total," items"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(g,{variant:"outline",size:"sm",disabled:c<=1||w.updating,onClick:()=>N({page:String(c-1)}),children:[e.jsx(Gs,{className:"mr-1 h-4 w-4","aria-hidden":"true"}),"Newer"]}),e.jsxs(g,{variant:"outline",size:"sm",disabled:c>=v.pages||w.updating,onClick:()=>N({page:String(c+1)}),children:["Older",e.jsx(ts,{className:"ml-1 h-4 w-4","aria-hidden":"true"})]})]})]})]})}function eR({item:t,adminOptions:s}){const a=J(),{user:n}=V(),r=o.useRef(!1),i=W({mutationFn:c=>
3962Fy.triage(t.id,{...c,expected_version:t.version}),meta:{suppressErrorToast:!0},onSuccess:(c,d)=>{a.setQueriesData({queryKey:["platform-feedback"]},u=>u&&{...u,items:u.items.map(h=>h.id===c.id?c:h)}),Ut.success(d.status?c.status==="new"?"Reopened":`Marked ${Lc[c.status].toLowerCase()}`:c.owner_name?`Assigned to ${c.owner_name}`:"Unassigned")},onError:async c=>{if(c.response?.status===409){await a.invalidateQueries({queryKey:["platform-feedback"]}),Ut.error("Someone else changed this feedback first. It now shows their change.");return}Ut.error(`Not saved: ${Xn(c,"something went wrong")}`)},onSettled:(c,d)=>(r.current=!1,d?.response?.status===409?void 0:a.invalidateQueries({queryKey:["platform-feedback"]}))}),l=i.isPending,m=c=>{r.current||(r.current=!0,i.mutate(c))};return e.jsx("li",{children:e.jsx(L,{className:"min-w-0 overflow-hidden",children:e.jsxs($,{className:"space-y-3 p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsx("p",{className:"min-w-0 flex-1 whitespace-pre-wrap break-words text-sm",children:t.content}),e.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1.5 text-xs font-medium",children:[e.jsx("span",{className:me("h-1.5 w-1.5 rounded-full",ZF[t.status]),"aria-hidden":"true"}),Lc[t.status]]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-muted-foreground",children:[e.jsx("span",{className:"font-medium text-foreground",children:t.member_name}),e.jsx("span",{children:t.member_email}),e.jsx(je,{to:`/platform/societies/${t.society_id}`,className:"font-medium text-foreground hover:underline",children:t.society_name}),e.jsx("time",{dateTime:t.created_at,title:`${_d(t.created_at,!0)} UTC`,children:Yn(t.created_at)}),t.page_url&&(t.source_url?e.jsxs("a",{href:t.source_url,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1 font-mono text-[11px] hover:underline",children:[t.page_url,e.jsx(Rs,{className:"h-3 w-3","aria-hidden":"true"}),e.jsx("span",{className:"sr-only",children:"(opens the portal page in a new tab)"})]}):e.jsx("span",{className:"font-mono text-[11px]",children:t.page_url}))]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 border-t pt-3",children:[e.jsx("div",{className:"w-52",children:e.jsxs(qe,{value:t.owner_user_id??hc,disabled:l,onValueChange:c=>m({owner_user_id:c===hc?null:c}),children:[e.jsx(Le,{"aria-label":"Assign owner",className:"h-9",children:e.jsx(Ie,{children:t.owner_name??"Unassigned"})}),e.jsxs($e,{children:[e.jsx(q,{value:hc,children:"Unassigned"}),n&&!s.some(c=>c.id===n.id)&&e.jsx(q,{value:n.id,children:"Me"}),s.map(c=>e.jsx(q,{value:c.id,children:c.id===n?.id?"Me":`${c.first_name} ${c.last_name}`.trim()||c.email},c.id))]})]})}),t.status==="new"&&e.jsx(g,{size:"sm",variant:"outline",disabled:l,onClick:()=>m({status:"reviewed"}),children:"Mark reviewed"}),t.status!=="resolved"?e.jsx(g,{size:"sm",disabled:l,onClick:()=>m({status:"resolved"}),children:"Resolve"}):e.jsx(g,{size:"sm",variant:"outline",disabled:l,onClick:()=>m({status:"new"}),children:"Reopen"}),t.status_changed_at&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:[JF[t.status],t.status_changed_by_name?` by ${t.status_changed_by_name}`:""," ",Yn(t.status_changed_at)]})]})]})})})}function Mh(){const{user:t}=V(),{fullName:s}=ro(t);return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-brand-navy/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(Vc,{className:"h-5 w-5","aria-hidden":"true"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:"Your account"}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"Your personal sign-in settings. They apply wherever you use Korevera."})]})]}),e.jsx(L,{className:"min-w-0 overflow-hidden",children:e.jsxs($,{className:"grid gap-3 pt-6 text-sm sm:grid-cols-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-muted-foreground",children:"Name"}),e.jsx("p",{className:"truncate font-medium",children:s||"â"})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-muted-foreground",children:"Email"}),e.jsx("p",{className:"truncate font-medium",children:t?.email})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-muted-foreground",children:"Role"}),e.jsx("p",{className:"font-medium",children:t?Ea[t.role]:""})]})]})}),e.jsxs(L,{className:"min-w-0 overflow-hidden",children:[e.jsx(ne,{className:"pb-3",children:e.jsxs(ie,{className:"flex min-w-0 items-center gap-2.5 text-sm font-semibold tracking-tight",children:[e.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-brand-navy
3962/10 text-brand-navy dark:bg-brand-navy/40 dark:text-sky-300",children:e.jsx(Hc,{className:"h-4 w-4","aria-hidden":"true"})}),"Passkeys"]})}),e.jsx($,{children:e.jsx(ry,{listCredentials:Xa.listCredentials,getRegisterOptions:Xa.getRegisterOptions,verifyRegistration:Xa.verifyRegistration,renameCredential:Xa.renameCredential,deleteCredential:Xa.deleteCredential,queryKey:"admin-passkeys"})})]})]})}function Dh({tab:t}){const{id:s}=Ds();return e.jsx(_t,{to:`/platform/societies/${s}/settings?tab=${t}`,replace:!0})}function tR(){const{societySlug:t}=Ds(),{isCustomDomain:s}=da(),{data:a,isLoading:n}=ma(s?void 0:t||void 0);return s?e.jsx(Ll,{}):n?e.jsx("div",{className:"flex min-h-screen items-center justify-center",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-b-2 border-primary"})}):a?.society?e.jsx(_t,{to:`/${t}/portal/login`,replace:!0}):e.jsx(Yf,{})}function sR(){const{isCustomDomain:t}=da();return t?e.jsx(Ll,{}):e.jsx(Yf,{})}function aR(){const{isCustomDomain:t,domainSlug:s}=da(),{societySlug:a}=Ds(),{societySlug:n}=ft(),r=s||a||n||"";return t?"/portal/login":`/${r}/portal/login`}function My(){const{isCustomDomain:t,domainSlug:s}=da(),{societySlug:a}=Ds(),{societySlug:n}=ft(),r=s||a||n||"";return t?"/portal/dashboard":`/${r}/portal/dashboard`}function nR({children:t}){const{user:s,isLoading:a}=V(),{isCustomDomain:n}=da(),r=ta();if(n)return e.jsx(_t,{to:"/portal/login",replace:!0});if(a)return e.jsx("div",{className:"flex min-h-screen items-center justify-center",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-b-2 border-primary"})});
3962if(s){const i=hd(new URLSearchParams(r.search).get("next"));return e.jsx(_t,{to:i??"/",replace:!0})}return e.jsx(e.Fragment,{children:t})}function rR(){const{isPlatformMode:t}=V(),[s]=ws();return t&&!s.get("society")?e.jsx(_t,{to:"/platform/account",replace:!0}):e.jsx(os,{children:e.jsx(ls,{})})}function iR(){const{user:t,isLoading:s,isPlatformMode:a}=V(),{isCustomDomain:n,domainSlug:r,isResolving:i}=da();return s||i?e.jsx("div",{className:"flex min-h-screen items-center justify-center",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-b-2 border-primary"})}):n&&r?e.jsx(_t,{to:"/portal/login",replace:!0}):t?a?e.jsx(_t,{to:"/platform",replace:!0}):e.jsx(_t,{to:"/dashboard",replace:!0}):e.jsx(_t,{to:"/login",replace:!0})}function lR({children:t}){const{user:s,isLoading:a,exitToPlatform:n}=V(),{isCustomDomain:r}=da(),i=ta(),l=kt(),m=i.state?.exitWorkspace;return o.useEffect(()=>{m&&(n(),l({pathname:i.pathname,search:i.search,hash:i.hash},{replace:!0}))},[m,n,l,i.pathname,i.search,i.hash]),r?e.jsx(_t,{to:"/portal/login",replace:!0}):a?e.jsx("div",{className:"flex min-h-screen items-center justify-center",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-b-2 border-primary"})}):s?s.role!=="super_admin"?e.jsx(_t,{to:"/",replace:!0}):e.jsx(e.Fragment,{children:t}):e.jsx(_t,{to:pd(i.pathname+i.search),replace:!0})}function os({children:t}){const{user:s,isLoading:a,isPlatformMode:n,setSelectedSocietyId:r}=V(),{isCustomDomain:i}=da(),[l]=ws(),m=l.get("society"),c=!!(m&&s?.role==="super_admin"),d=ta(),u=kt(),h=o.useRef(null);return o.useEffect(()=>{if(!c||!m||h.current===d.key)return;h.current=d.key,r(m);const p=new URLSearchParams(l);p.delete("society");const x=p.toString();u({pathname:d.pathname,search:x?`?${x}`:"",hash:d.hash},{replace:!0,state:d.state})},[c,m,l,d,u,r]),i?e.jsx(_t,{to:"/portal/login",replace:!0}):a?e.jsx("div",{className:"flex min-h-screen items-center justify-center",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-b-2 border-primary"})}):s?c?e.jsx("div",{className:"flex min-h-screen items-center justify-center",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-b-2 border-primary"})}
3962):n?e.jsx(_t,{to:"/platform",replace:!0}):e.jsx(e.Fragment,{children:t}):e.jsx(_t,{to:pd(d.pathname+d.search),replace:!0})}function oR(){const{isCustomDomain:t,domainSlug:s}=da(),{societySlug:a}=Ds(),{societySlug:n}=ft(),r=s||a||n||"";return t?"/portal/set-password":`/${r}/portal/set-password`}function Lh({children:t}){const{isAuthenticated:s,hasPassword:a}=ft(),n=aR(),r=oR();return s?a?e.jsx(e.Fragment,{children:t}):e.jsx(_t,{to:r,replace:!0}):e.jsx(_t,{to:n,replace:!0})}function $h({children:t}){const{isAuthenticated:s}=ft(),a=My();return s?e.jsx(_t,{to:a,replace:!0}):e.jsx(e.Fragment,{children:t})}function qh({children:t}){const{data:s,isLoading:a}=Qa(),n=My();return a||s===void 0?null:s.is_real_member?e.jsx(e.Fragment,{children:t}):e.jsx(_t,{to:n,replace:!0})}const Ih=[{path:"dashboard",element:e.jsx(V3,{})},{path:"profile",element:e.jsx(sP,{})},{path:"payments",element:e.jsx(nP,{})},{path:"subscription",element:e.jsx(dP,{})},{path:"invoices",element:e.jsx(CP,{})},{path:"events",element:e.jsx(PP,{})},{path:"events/:id",element:e.jsx(QP,{})},{path:"products",element:e.jsx(WP,{})},{path:"cart",element:e.jsx(GP,{})},{path:"checkout",element:e.jsx(ZP,{})},{path:"checkout/success",element:e.jsx(eA,{})},{path:"orders",element:e.jsx(oA,{})},{path:"committees",element:e.jsx(qh,{children:e.jsx(tA,{})})},{path:"directory",element:e.jsx(qh,{children:e.jsx(sA,{})})}],cR=By([{path:"/account-link",element:e.jsx(OF,{})},{path:"/login",element:e.jsx(nR,{children:e.jsx(vN,{})})},{path:"/",element:e.jsx(iR,{})},{path:"/dashboard",element:e.jsx(os,{children:e.jsx(ls,{})}),children:[{index:!0,element:e.jsx(Zk,{})}]},{path:"/platform",element:e.jsx(lR,{children:e.jsx(Dw,{})}),children:[{index:!0,element:e.jsx(uA,{})},{path:"societies",element:e.jsx(vA,{})},{path:"societies/new",element:e.jsx(gh,{})},{path:"societies/:id",element:e.jsx(pT,{})},{path:"societies/:id/settings",element:e.jsx(gh,{})},{path:"societies/:id/quickbooks",element:e.jsx(xF,{})},{path:"societies/:id/quickbooks/config",element:e.jsx($F,{})},{path:"societies/:id/custom-fields",element:e.jsx(Dh,{tab:"customization"})},{path:"societies/:id/badge-types",element:e.jsx(Dh,{tab:"customization"})},{path:"users",element:e.jsx(GF,{})},{path:"activity",element:e.jsx(QF,{})},{path:"feedback",element:e.jsx(XF,{})},{path:"account",element:e.jsx(Mh,{})},{path:"settings",element:e.jsx(_t,{to:"/platform/account",replace:!0})}]},{path:"/members",element:e.jsx(os,{children:e.jsx(ls,{})}),children:[{index:!0,element:e.jsx(ES,{})},{path:"new",element:e.jsx(qm,{})},{path:"duplicates",element:e.jsx(MS,{})},{path:":id",element:e.jsx(JS,{})},{path:":id/edit",element:e.jsx(qm,{})}]},{path:"/membership-types",element:e.jsx(os,{children:e.jsx(ls,{})}),children:[{index:!0,element:e.jsx(j1,{})}]},{path:"/payments",element:e.jsx(os,{children:e.jsx(ls,{})}),children:[{index:!0,element:e.jsx(k1,{})}]},{path:"/invoices",element:e.jsx(os,{children:e.jsx(ls,{})}),children:[{index:!0,element:e.jsx(r2,{})},{path:"new-batch",element:e.jsx(i2,{})}]},{path:"/emails",element:e.jsx(os,{children:e.jsx(ls,{})}),children:[{index:!0,element:e.jsx(wC,{})},{path:"templates",element:e.jsx(kC,{})},{path:"templates/new",element:e.jsx(Lo,{})},{path:"templates/:id",element:e.jsx(Lo,{})},{path:"campaigns",element:e.jsx(MC,{})},{path:"renewals",element:e.jsx(f2,{})},{path:"logs",element:e.jsx(DC,{})},{path:"suppressions",element:e.jsx(IC,{})},{path:"sending",element:e.jsx(BC,{})},{path:"new",element:e.jsx(_t,{to:"/emails/templates/new",replace:!0})},{path:"sync-rules",element:e.jsx(J5,{})},{path:":id",element:e.jsx(Lo,{})}]},{path:"/renewal-sequence",element:e.jsx(_t,{to:"/emails/renewals",replace:!0})},{path:"/reports",element:e.jsx(os,{children:e.jsx(ls,{})}),children:[{index:!0,element:e.jsx(C1,{})}]},{path:"/users",element:e.jsx(os,{children:e.jsx(ls,{})}),children:[{index:!0,element:e.jsx(z1,{})}]},{path:"/audit",element:e.jsx(os,{children:e.jsx(ls,{})}),children:[{index:!0,element:e.jsx(JC,{})}]},{path:"/admin/event-app/revoke-queue",element:e.jsx(os,{children:e.jsx(ls,{})}),children:[{index:!0,element:e.jsx(e3,{})}]},{path:"/admin/members/merged",element:e.jsx(os,{children:e.jsx(ls,{})}),children:[{index:!0,element:e.jsx(s3,{})}]},{path:"/admin/members/link-history",element:e.jsx(os,{children:e.jsx(ls,{})}),children:[{index:!0,element:e.jsx(r3,{})}]},{path:"/import-export",element:e.jsx(os,{children:e.jsx(ls,{})}),children:[{index:!0,element:e.jsx(l2,{})}]},{path:"/events",element:e.jsx(os,{children:e.jsx(ls,{})}),children:[{index:!0,element:e.jsx(K4,{})},{path:":id",element:e.jsx(G4,{})},{path:":eventId/walk-in",element:e.jsx(Y4,{})}]},{path:"/products",element:e.jsx(os,{children:e.jsx(ls,{})}),children:[{index:!0,element:e.jsx(J4,{})}]},{path:"/donation-campaigns",element:e.jsx(os,{children:e.jsx(ls,{})}),children:[{index:!0,element:e.jsx(X4,{})}]},{path:"/registration-forms",element:e.jsx(os,{children:e.jsx(ls,{})}),children:[{index:!0,element:e.jsx(h5,{})}]},{path:"/promo-codes",element:e.jsx(os,{children:e.jsx(ls,{})}),children:[{index:!0,element:e.jsx(l5,{})}]},{path:"/orders",element:e.jsx(os,{children:e.jsx(ls,{})}),children:[{index:!0,element:e.jsx(n5,{})}]},{path:"/disputes",element:e.jsx(os,{children:e.jsx(ls,{})}),children:[{index:!0,element:e.jsx(q5,{})}]},{path:"/polls",element:e.jsx(os,{children:e.jsx(ls,{})}),children:[{index:!0,element:e.jsx(P5,{})}]},{path:"/announcements",element:e.jsx(os,{children:e.jsx(ls,{})}),children:[{index:!0,element:e.jsx(F5,{})}]},{path:"/committees",element:e.jsx(os,{children:e.jsx(ls,{})}),children:[{index:!0,element:e.jsx(D5,{})}]},{path:"/settings",element:e.jsx(os,{children:e.jsx(ls,{})}),children:[{index:!0,element:e.jsx(p1,{})}]},{path:"/account",element:e.jsx(rR,{}),children:[{index:!0,element:e.jsx(Mh,{})}]},{path:"/help",element:e.jsx(os,{children:e.jsx(ls,{})}),children:[{index:!0,element:e.jsx(G5,{})},{path:":slug",element:e.jsx(Y5,{})}]},{path:"/:societySlug",element:e.jsx(tR,{})},{path:"/:societySlug/portal/login",element:e.jsx($h,{children:e.jsx(Eu,{})})},{path:"/:societySlug/portal/signup",element:e.jsx(Ku,{})},{path:"/:societySlug/portal/complete-payment",element:e.jsx(Qu,{})},{path:"/:societySlug/portal/terms",element:e.jsx(ah,{})},{path:"/:societySlug/portal/privacy",element:e.jsx(nh,{})},{path:"/:societySlug/portal/forgot-password",element:e.jsx(Ju,{})},{path:"/:societySlug/portal/reset-password",element:e.jsx(Zu,{})},{path:"/:societySlug/portal/verify-email-change",element:e.jsx(Xu,{})}
3962,{path:"/:societySlug/unsubscribe",element:e.jsx(Su,{})},{path:"/:societySlug/portal/verify-magic-link",element:e.jsx(eh,{})},{path:"/:societySlug/portal/set-password",element:e.jsx(th,{})},{path:"/:societySlug/portal/*",element:e.jsx(Ll,{})},{path:"/:societySlug/portal",element:e.jsx(Lh,{children:e.jsx(Nm,{})}),children:Ih},{path:"/portal/login",element:e.jsx($h,{children:e.jsx(Eu,{})})},{path:"/portal/signup",element:e.jsx(Ku,{})},{path:"/portal/complete-payment",element:e.jsx(Qu,{})},{path:"/portal/terms",element:e.jsx(ah,{})},{path:"/portal/privacy",element:e.jsx(nh,{})},{path:"/portal/forgot-password",element:e.jsx(Ju,{})},{path:"/portal/reset-password",element:e.jsx(Zu,{})},{path:"/portal/verify-email-change",element:e.jsx(Xu,{})},{path:"/unsubscribe",element:e.jsx(Su,{})},{path:"/portal/verify-magic-link",element:e.jsx(eh,{})},{path:"/portal/set-password",element:e.jsx(th,{})},{path:"/portal/*",element:e.jsx(Ll,{})},{path:"/portal",element:e.jsx(Lh,{children:e.jsx(Nm,{})}),children:Ih},{path:"*",element:e.jsx(sR,{})}]),dR=/([?&](?:token|code|payment_intent_client_secret)=)[^&#\s]*/gi;function dl(t){return t.replace(dR,"$1[redacted]")}Sj({dsn:"https://95318dddccc7b160277efa081a3d1ce3@o4510902745169920.ingest.us.sentry.io/4510902761553920",environment:"production",tracesSampleRate:.1,ignoreErrors:["Object Not Found Matching Id"],beforeSend(t){return t.request?.url&&(t.request.url=dl(t.request.url)),t.request?.query_string&&typeof t.request.query_string=="string"&&(t.request.query_string=dl(`?${t.request.query_string}`).slice(1)),t},beforeBreadcrumb(t){for(const s of["from","to","url"]){const a=t.data?.[s];typeof a=="string"&&(t.data[s]=dl(a))}return t.message&&(t.message=dl(t.message)),t}});Ky.createRoot(document.getElementById("root")).render(e.jsx(o.StrictMode,{children:e.jsx(Cj,{children:e.jsx(Xl,{children:e.jsx(cv,{children:e.jsx(av,{children:e.jsx(lv,{children:e.jsx(Tj,{children:e.jsx(tv,{children:e.jsxs($r,{delayDuration:300,children:[e.jsx(Qy,{router:cR}),e.jsx(Hy,{richColors:!0,closeButton:!0,position:"top-right"})]})})})})})})})})}));
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.